OSDN Git Service

b73ec5efc4fcd18cd1e6bcc870a76994aa96b570
[luatex-ja/luatexja.git] / src / ltj-jfmglue.lua
1 --
2 -- luatexja/ltj-jfmglue.lua
3 --
4 luatexbase.provides_module({
5   name = 'luatexja.jfmglue',
6   date = '2014/10/03',
7   description = 'Insertion process of JFM glues and kanjiskip',
8 })
9 module('luatexja.jfmglue', package.seeall)
10 local err, warn, info, log = luatexbase .errwarinf(_NAME)
11
12 luatexja.load_module('base');      local ltjb = luatexja.base
13 luatexja.load_module('stack');     local ltjs = luatexja.stack
14 luatexja.load_module('jfont');     local ltjf = luatexja.jfont
15 luatexja.load_module('direction'); local ltjd = luatexja.direction
16 luatexja.load_module('setwidth');      local ltjw = luatexja.setwidth
17 local pairs = pairs
18
19 local Dnode = node.direct or node
20
21 local nullfunc = function(n) return n end
22 local to_node = (Dnode ~= node) and Dnode.tonode or nullfunc
23 local to_direct = (Dnode ~= node) and Dnode.todirect or nullfunc
24
25 local setfield = (Dnode ~= node) and Dnode.setfield or function(n, i, c) n[i] = c end
26 local getfield = (Dnode ~= node) and Dnode.getfield or function(n, i) return n[i] end
27 local getid = (Dnode ~= node) and Dnode.getid or function(n) return n.id end
28 local getfont = (Dnode ~= node) and Dnode.getfont or function(n) return n.font end
29 local getlist = (Dnode ~= node) and Dnode.getlist or function(n) return n.head end
30 local getchar = (Dnode ~= node) and Dnode.getchar or function(n) return n.char end
31 local getsubtype = (Dnode ~= node) and Dnode.getsubtype or function(n) return n.subtype end
32
33 local has_attr = Dnode.has_attribute
34 local set_attr = Dnode.set_attribute
35 local insert_before = Dnode.insert_before
36 local insert_after = Dnode.insert_after
37 local node_next = (Dnode ~= node) and Dnode.getnext or node.next
38 local round = tex.round
39 local ltjd_make_dir_whatsit = ltjd.make_dir_whatsit
40 local ltjf_font_metric_table = ltjf.font_metric_table
41 local ltjf_find_char_class = ltjf.find_char_class
42 local node_new = Dnode.new
43 local node_copy = Dnode.copy
44 local node_remove = Dnode.remove
45 local node_tail = Dnode.tail
46 local node_free = Dnode.free
47 local node_end_of_math = Dnode.end_of_math
48
49 local id_glyph = node.id('glyph')
50 local id_hlist = node.id('hlist')
51 local id_vlist = node.id('vlist')
52 local id_rule = node.id('rule')
53 local id_ins = node.id('ins')
54 local id_mark = node.id('mark')
55 local id_adjust = node.id('adjust')
56 local id_disc = node.id('disc')
57 local id_whatsit = node.id('whatsit')
58 local id_math = node.id('math')
59 local id_glue = node.id('glue')
60 local id_kern = node.id('kern')
61 local id_penalty = node.id('penalty')
62
63 local id_glue_spec = node.id('glue_spec')
64 local id_jglyph    = 512 -- Japanese character
65 local id_box_like  = 256 -- vbox, shifted hbox
66 local id_pbox      = 257 -- already processed nodes (by \unhbox)
67 local id_pbox_w    = 258 -- cluster which consists of a whatsit
68 local sid_user = node.subtype('user_defined')
69
70 local sid_start_link = node.subtype('pdf_start_link')
71 local sid_start_thread = node.subtype('pdf_start_thread')
72 local sid_end_link = node.subtype('pdf_end_link')
73 local sid_end_thread = node.subtype('pdf_end_thread')
74
75 local ITALIC       = luatexja.icflag_table.ITALIC
76 local PACKED       = luatexja.icflag_table.PACKED
77 local KINSOKU      = luatexja.icflag_table.KINSOKU
78 local FROM_JFM     = luatexja.icflag_table.FROM_JFM
79 local PROCESSED    = luatexja.icflag_table.PROCESSED
80 local IC_PROCESSED = luatexja.icflag_table.IC_PROCESSED
81 local BOXBDD       = luatexja.icflag_table.BOXBDD
82 local PROCESSED_BEGIN_FLAG = luatexja.icflag_table.PROCESSED_BEGIN_FLAG
83 local kanji_skip
84 local xkanji_skip
85 local table_current_stack
86 local list_dir
87 local capsule_glyph
88 local tex_dir
89 local attr_ablshift
90 local set_np_xspc_jachar
91
92 local attr_curjfnt = luatexbase.attributes['ltj@curjfnt']
93 local attr_dir = luatexbase.attributes['ltj@dir']
94 local attr_icflag = luatexbase.attributes['ltj@icflag']
95
96 local function get_attr_icflag(p)
97    return (has_attr(p, attr_icflag) or 0)%PROCESSED_BEGIN_FLAG
98 end
99
100 -------------------- Helper functions
101
102 local function copy_attr(new, old)
103   -- 仕様が決まるまで off にしておく
104 end
105
106 -- This function is called only for acquiring `special' characters.
107 local function fast_find_char_class(c,m)
108    return m.chars[c] or 0
109 end
110
111 -- 文字クラスの決定
112 local slow_find_char_class
113 do
114    local start_time_measure = ltjb.start_time_measure
115    local stop_time_measure = ltjb.stop_time_measure
116    slow_find_char_class = function (c, m, oc)
117       local cls = ltjf_find_char_class(oc, m)
118       if oc~=c and cls==0 then
119          return ltjf_find_char_class(-c, m), oc
120       else
121          return cls, oc
122       end
123    end
124 end
125
126 local zero_glue = node_new(id_glue)
127 spec_zero_glue = to_node(node_new(id_glue_spec))
128   -- must be public, since mentioned from other sources
129 local spec_zero_glue = to_direct(spec_zero_glue)
130 setfield(spec_zero_glue, 'width', 0)
131 setfield(spec_zero_glue, 'stretch', 0)
132 setfield(spec_zero_glue, 'shrink', 0)
133 setfield(spec_zero_glue, 'stretch_order', 0)
134 setfield(spec_zero_glue, 'shrink_order', 0)
135 setfield(zero_glue, 'spec', spec_zero_glue)
136
137 local function skip_table_to_spec(n)
138    local g, st = node_new(id_glue_spec), ltjs.fast_get_stack_skip(n)
139    setfield(g, 'width', st.width)
140    setfield(g, 'stretch', st.stretch)
141    setfield(g, 'shrink', st.shrink)
142    setfield(g, 'stretch_order', st.stretch_order)
143    setfield(g, 'shrink_order', st.shrink_order)
144    return g
145 end
146
147
148 -- penalty 値の計算
149 local function add_penalty(p,e)
150    local pp = getfield(p, 'penalty')
151    if pp>=10000 then
152       if e<=-10000 then pp = 0 end
153    elseif pp<=-10000 then
154       if e>=10000 then pp = 0 end
155    else
156       pp = pp + e
157       if pp>=10000 then      setfield(p, 'penalty', 10000)
158       elseif pp<=-10000 then setfield(p, 'penalty', -10000)
159       else                   setfield(p, 'penalty', pp) end
160    end
161    return
162 end
163
164 -- 「異なる JFM」の間の調整方法
165 diffmet_rule = math.two_paverage
166 function math.two_add(a,b) return a+b end
167 function math.two_average(a,b) return (a+b)*0.5 end
168 function math.two_paverage(a,b) return (a+b)/2 end
169 function math.two_pleft(a,b) return a end
170 function math.two_pright(a,b) return b end
171
172 local head -- the head of current list
173
174 local Np, Nq, Bp
175 local widow_Bp, widow_Np -- \jcharwidowpenalty 挿入位置管理用
176
177 local ihb_flag -- JFM グルー挿入抑止用 flag
178                -- on: \inhibitglue 指定時,hlist の周囲
179
180 -------------------- hlist 内の文字の検索
181
182 local first_char, last_char, find_first_char
183 do
184 local ltjd_glyph_from_packed = ltjd.glyph_from_packed
185 local function check_box(box_ptr, box_end)
186    local p = box_ptr; local found_visible_node = false
187    if not p then
188       find_first_char = false; last_char = nil
189       return true
190    end
191    while p and p~=box_end do
192       local pid = getid(p)
193       if pid==id_kern and getsubtype(p)==2 then
194          p = node_next(node_next(node_next(p))); pid = getid(p) -- p must be glyph_node
195        end
196       if pid==id_glyph then
197          repeat
198             if find_first_char then
199                first_char = p; find_first_char = false
200             end
201             last_char = p; found_visible_node = true; p=node_next(p)
202             if (not p) or p==box_end then
203                return found_visible_node
204             end
205          until getid(p)~=id_glyph
206          pid = getid(p) -- p must be non-nil
207       end
208       if pid==id_kern then
209          local pa = get_attr_icflag(p)
210          if pa==IC_PROCESSED then
211             -- do nothing
212          elseif getsubtype(p)==2 then
213             p = node_next(node_next(p));
214             -- Note that another node_next will be executed outside this if-statement.
215          else
216             found_visible_node = true
217             find_first_char = false; last_char = nil
218          end
219       elseif pid==id_hlist then
220          if PACKED == get_attr_icflag(p) then
221             local s = ltjd_glyph_from_packed(p)
222             if find_first_char then
223                first_char = s; find_first_char = false
224             end
225             last_char = s; found_visible_node = true
226          else
227             if getfield(p, 'shift')==0 then
228                if check_box(getlist(p), nil) then found_visible_node = true end
229             else
230                find_first_char = false; last_char = nil
231             end
232          end
233       elseif pid==id_math then
234          if find_first_char then
235             first_char = p; find_first_char = false
236          end
237          last_char = p; found_visible_node = true
238          --elseif pid==id_rule and get_attr_icflag(p)==PACKED then -- do nothing
239       elseif not (pid==id_ins   or pid==id_mark
240                   or pid==id_adjust or pid==id_whatsit
241                   or pid==id_penalty) then
242          found_visible_node = true
243          find_first_char = false; last_char = nil
244       end
245       p = node_next(p)
246    end
247    return found_visible_node
248 end
249
250 function check_box_high(Nx, box_ptr, box_end)
251    first_char = nil;  last_char = nil;  find_first_char = true
252    if check_box(box_ptr, box_end) then
253       local first_char = first_char
254       if first_char then
255          if getid(first_char)==id_glyph then
256             if getfont(first_char) == (has_attr(first_char, attr_curjfnt) or -1) then
257                set_np_xspc_jachar(Nx, first_char)
258             else
259                set_np_xspc_alchar(Nx, getchar(first_char),first_char, 1)
260             end
261          else -- math_node
262             set_np_xspc_alchar(Nx, -1,first_char)
263          end
264       end
265    end
266    return last_char
267 end
268 end
269 -------------------- Np の計算と情報取得
270
271 luatexbase.create_callback("luatexja.jfmglue.whatsit_getinfo", "data",
272                            function (Np, lp, Nq)
273                               if Np.nuc then return Np
274                               else
275                                  return Np  -- your code
276                               end
277                            end)
278 luatexbase.create_callback("luatexja.jfmglue.whatsit_after", "data",
279                            function (stat, Nq, Np) return false end)
280
281 -- calc next Np
282 do
283
284 local function set_attr_icflag_processed(p)
285    if get_attr_icflag(p)<= ITALIC then
286       set_attr(p, attr_icflag, PROCESSED)
287    end
288 end
289
290 local function check_next_ickern(lp)
291    if lp and getid(lp) == id_kern and ITALIC == get_attr_icflag(lp) then
292       set_attr(lp, attr_icflag, IC_PROCESSED)
293       Np.last = lp; return node_next(lp)
294    else
295       Np.last = Np.nuc; return lp
296    end
297 end
298
299 local function calc_np_pbox(lp, last)
300    local first, lpa, nc = (not Np.first), KINSOKU, nil
301    Np.first = Np.first or lp; Np.id = id_pbox
302    set_attr(lp, attr_icflag, get_attr_icflag(lp));
303    while lp ~=last and (lpa>=PACKED) and (lpa<BOXBDD) do
304       if getid(lp)==id_hlist or getid(lp)==id_vlist then
305          head, lp, nc = ltjd_make_dir_whatsit(head, lp, list_dir, 'jfm pbox')
306          if first then Np.first = nc end
307       else
308          nc, lp = lp, node_next(lp)
309       end
310       first, lpa = false, (lp and has_attr(lp, attr_icflag) or 0)
311      -- get_attr_icflag() ではいけない!
312    end
313    Np.nuc = nc
314    return check_next_ickern(lp)
315 end
316
317 local ltjw_apply_ashift_math = ltjw.apply_ashift_math
318 local function calc_np_aux_glyph_common(lp)
319    Np.nuc = lp
320    Np.id = npi
321    if (getfont(lp) == (has_attr(lp, attr_curjfnt) or -1)) then
322       Np.id = id_jglyph
323       set_np_xspc_jachar(Np, lp)
324       local npi
325       lp, head, npi = capsule_glyph(lp, Np.met, Np.class, head, tex_dir)
326       Np.first = (Np.first~=Np.nuc) and Np.first or npi
327       Np.nuc = npi
328    else
329       Np.id = id_glyph
330       set_np_xspc_alchar(Np, getchar(lp), lp, 1)
331       set_attr(lp, attr_icflag, PROCESSED)
332       setfield(lp, 'yoffset',
333                getfield(lp, 'yoffset') - (has_attr(lp,attr_ablshift) or 0))
334       lp = node_next(lp)
335    end
336    return true, check_next_ickern(lp);
337 end
338 local calc_np_auxtable = {
339    [id_glyph] = function (lp)
340       Np.first= (Np.first or lp)
341       return calc_np_aux_glyph_common(lp)
342    end,
343    [id_hlist] = function(lp)
344       local op, flag
345       head, lp, op, flag = ltjd_make_dir_whatsit(head, lp, list_dir, 'jfm hlist')
346       set_attr(op, attr_icflag, PROCESSED)
347       Np.first = Np.first or op; Np.last = op; Np.nuc = op;
348       if (flag or getfield(op, 'shift')~=0) then
349          Np.id = id_box_like
350       else
351          Np.id = id_hlist
352          Np.last_char = check_box_high(Np, getlist(op), nil)
353       end
354       return true, lp
355    end,
356    [id_vlist] =  function(lp)
357       local op
358       head, lp, op = ltjd_make_dir_whatsit(head, lp, list_dir, 'jfm:' .. getid(lp))
359       Np.first = Np.first or op; Np.last = op; Np.nuc = op;
360       Np.id = id_box_like;
361       return true, lp
362    end,
363    box_like = function(lp)
364       Np.first = Np.first or lp; Np.last = lp; Np.nuc = lp;
365       Np.id = id_box_like;
366       return true, node_next(lp)
367    end,
368    skip = function(lp)
369       set_attr(lp, attr_icflag, PROCESSED)
370       return false, node_next(lp)
371    end,
372    [id_whatsit] = function(lp)
373       local lps = getsubtype(lp)
374       if lps==sid_user then
375          if getfield(lp, 'user_id')==luatexja.userid_table.IHB then
376             local lq = node_next(lp);
377             head = node_remove(head, lp); node_free(lp); ihb_flag = true
378             return false, lq;
379          else
380             set_attr(lp, attr_icflag, PROCESSED)
381             luatexbase.call_callback("luatexja.jfmglue.whatsit_getinfo",
382                                      Np, lp, Nq)
383             if Np.nuc then
384                Np.id = id_pbox_w; Np.first = Np.nuc; Np.last = Np.nuc;
385                return true, node_next(lp)
386             else
387                return false, node_next(lp)
388             end
389          end
390       else
391          -- we do special treatment for these whatsit nodes.
392          if lps == sid_start_link or lps == sid_start_thread then
393             Np.first = lp
394          elseif lps == sid_end_link or lps == sid_end_thread then
395             Np.first, Nq.last = nil, lp;
396          end
397          set_attr(lp, attr_icflag, PROCESSED)
398          return false, node_next(lp)
399       end
400    end,
401    [id_math] = function(lp)
402       Np.first, Np.nuc = (Np.first or lp), lp;
403       set_attr(lp, attr_icflag, PROCESSED)
404       set_np_xspc_alchar(Np, -1, lp)
405       local end_math  = node_end_of_math(lp)
406       ltjw_apply_ashift_math(lp, end_math, attr_ablshift)
407       set_attr(end_math, attr_icflag, PROCESSED)
408       Np.last, Np.id = end_math, id_math;
409       return true, node_next(end_math);
410    end,
411    discglue = function(lp)
412       Np.first, Np.nuc, Np.last = (Np.first or lp), lp, lp;
413       Np.id = getid(lp); set_attr(lp, attr_icflag, PROCESSED)
414       return true, node_next(lp)
415    end,
416    [id_kern] = function(lp)
417       Np.first = Np.first or lp
418       if getsubtype(lp)==2 then
419          set_attr(lp, attr_icflag, PROCESSED); lp = node_next(lp)
420          set_attr(lp, attr_icflag, PROCESSED); lp = node_next(lp)
421          set_attr(lp, attr_icflag, PROCESSED); lp = node_next(lp)
422          set_attr(lp, attr_icflag, PROCESSED);
423          return calc_np_aux_glyph_common(lp)
424       else
425          Np.id = id_kern; set_attr(lp, attr_icflag, PROCESSED)
426          Np.last = lp; return true, node_next(lp)
427       end
428    end,
429    [id_penalty] = function(lp)
430       Bp[#Bp+1] = lp; set_attr(lp, attr_icflag, PROCESSED)
431       return false, node_next(lp)
432    end,
433 }
434 calc_np_auxtable[id_rule]   = calc_np_auxtable.box_like
435 calc_np_auxtable[13]        = calc_np_auxtable.box_like
436 calc_np_auxtable[id_ins]    = calc_np_auxtable.skip
437 calc_np_auxtable[id_mark]   = calc_np_auxtable.skip
438 calc_np_auxtable[id_adjust] = calc_np_auxtable.skip
439 calc_np_auxtable[id_disc]   = calc_np_auxtable.discglue
440 calc_np_auxtable[id_glue]   = calc_np_auxtable.discglue
441
442 function calc_np(lp, last)
443    local k
444    -- We assume lp = node_next(Np.last)
445    Np, Nq, ihb_flag = Nq, Np, nil
446    -- We clear `predefined' entries of Np before pairs() loop,
447    -- because using only pairs() loop is slower.
448    Np.post, Np.pre, Np.xspc = nil, nil, nil
449    Np.first, Np.id, Np.last, Np.met, Np.class= nil, nil, nil, nil
450    Np.auto_kspc, Np.auto_xspc, Np.char, Np.nuc = nil, nil, nil, nil
451    for k in pairs(Np) do Np[k] = nil end
452
453    for k = 1,#Bp do Bp[k] = nil end
454    while lp ~= last  do
455       local lpa = has_attr(lp, attr_icflag) or 0
456        -- unbox 由来ノードの検出
457       if lpa>=PACKED then
458          if lpa%PROCESSED_BEGIN_FLAG == BOXBDD then
459             local lq = node_next(lp)
460             head = node_remove(head, lp); node_free(lp); lp = lq
461          else
462             return calc_np_pbox(lp, last)
463          end -- id_pbox
464       else
465          k, lp = calc_np_auxtable[getid(lp)](lp)
466          if k then return lp end
467       end
468    end
469    Np = nil; return lp
470 end
471
472 end
473 local calc_np = calc_np
474
475 -- extract informations from Np
476 -- We think that "Np is a Japanese character" if Np.met~=nil,
477 --            "Np is an alphabetic character" if Np.pre~=nil,
478 --            "Np is not a character" otherwise.
479 after_hlist = nil -- global
480 local after_alchar, extract_np
481 do
482   local PRE  = luatexja.stack_table_index.PRE
483   local POST = luatexja.stack_table_index.POST
484   local KCAT = luatexja.stack_table_index.KCAT
485   local XSP  = luatexja.stack_table_index.XSP
486   local dir_tate = luatexja.dir_table.dir_tate
487
488 -- 和文文字のデータを取得
489    local attr_jchar_class = luatexbase.attributes['ltj@charclass']
490    local attr_orig_char = luatexbase.attributes['ltj@origchar']
491    local attr_autospc = luatexbase.attributes['ltj@autospc']
492    local attr_autoxspc = luatexbase.attributes['ltj@autoxspc']
493    function set_np_xspc_jachar_yoko(Nx, x)
494       local m = ltjf_font_metric_table[getfont(x)]
495       local cls, c = slow_find_char_class(has_attr(x, attr_orig_char), m, getchar(x))
496       Nx.met, Nx.char = m, c; Nx.class = cls;
497       if cls~=0 then set_attr(x, attr_jchar_class, cls) end
498       Nx.pre  = table_current_stack[PRE + c]  or 0
499       Nx.post = table_current_stack[POST + c] or 0
500       Nx.xspc = table_current_stack[XSP  + c] or 3
501       Nx.kcat = table_current_stack[KCAT + c] or 0
502       Nx.auto_kspc, Nx.auto_xspc = (has_attr(x, attr_autospc)==1), (has_attr(x, attr_autoxspc)==1)
503    end
504    function set_np_xspc_jachar_tate(Nx, x)
505       local m = ltjf_font_metric_table[getfont(x)]
506       local cls, c
507       local c1, c2 = getchar(x), has_attr(x, attr_orig_char)
508       c = has_attr(x, attr_dir) or c1 or c2
509       cls = ltjf_find_char_class(c, m)
510       if cls==0 then cls = slow_find_char_class(c2, m, c1) end
511       Nx.met, Nx.char = m, c; Nx.class = cls;
512       if cls~=0 then set_attr(x, attr_jchar_class, cls) end
513       Nx.pre  = table_current_stack[PRE + c]  or 0
514       Nx.post = table_current_stack[POST + c] or 0
515       Nx.xspc = table_current_stack[XSP  + c] or 3
516       Nx.kcat = table_current_stack[KCAT + c] or 0
517       Nx.auto_kspc, Nx.auto_xspc = (has_attr(x, attr_autospc)==1), (has_attr(x, attr_autoxspc)==1)
518    end
519
520 -- 欧文文字のデータを取得
521    local floor = math.floor
522    function set_np_xspc_alchar(Nx, c,x, lig)
523       if c~=-1 then
524          local f = (lig ==1) and nullfunc or node_tail
525          local xc, xs = getfield(x, 'components'), getsubtype(x)
526          while xc and xs and xs%4>=2 do
527             x = f(xc); xc, xs = getfield(x, 'components'), getsubtype(x)
528          end
529          c = getchar(x)
530          Nx.pre  = table_current_stack[PRE + c]  or 0
531          Nx.post = table_current_stack[POST + c] or 0
532          Nx.xspc = table_current_stack[XSP  + c] or 3
533          Nx.char = 'jcharbdd'
534       else
535          Nx.pre, Nx.post, Nx.char = 0, 0, -1
536          Nx.xspc = table_current_stack[XSP - 1] or 3
537       end
538       Nx.met = nil
539       Nx.auto_xspc = (has_attr(x, attr_autoxspc)==1)
540    end
541    local set_np_xspc_alchar = set_np_xspc_alchar
542
543 -- Np の情報取得メインルーチン
544    extract_np = function ()
545       local x, i = Np.nuc, Np.id;
546 --      if i ==  id_jglyph then return set_np_xspc_jachar(Np, x)
547 --      elseif i == id_glyph then return set_np_xspc_alchar(Np, getchar(x), x, 1)
548 --      if i == id_hlist then Np.last_char = check_box_high(Np, getlist(x), nil)
549       if i == id_pbox then Np.last_char = check_box_high(Np, Np.first, node_next(Np.last))
550       elseif i == id_disc then Np.last_char = check_box_high(Np, getfield(x, 'replace'), nil)
551 --      elseif i == id_math then return set_np_xspc_alchar(Np, -1, x)
552       end
553    end
554
555    -- change the information for the next loop
556    -- (will be done if Nx is an alphabetic character or a hlist)
557    after_hlist = function (Nx)
558       local s = Nx.last_char
559       if s then
560          if getid(s)==id_glyph then
561             if getfont(s) == (has_attr(s, attr_curjfnt) or -1) then
562                set_np_xspc_jachar(Nx, s)
563             else
564                set_np_xspc_alchar(Nx, getchar(s), s, 2)
565             end
566          else
567             set_np_xspc_alchar(Nx, -1, s)
568          end
569       else
570          Nx.pre, Nx.met = nil, nil
571       end
572    end
573
574    after_alchar = function (Nx)
575       local x = Nx.nuc
576       return set_np_xspc_alchar(Nx, getchar(x), x, 2)
577    end
578
579 end
580
581 -------------------- 最下層の処理
582
583 -- change penalties (or create a new penalty, if needed)
584 local function handle_penalty_normal(post, pre, g)
585    local a = (pre or 0) + (post or 0)
586    if #Bp == 0 then
587       if (a~=0 and not(g and getid(g)==id_kern)) then
588          local p = node_new(id_penalty)
589          if a<-10000 then a = -10000 elseif a>10000 then a = 10000 end
590          setfield(p, 'penalty', a)
591          head = insert_before(head, Np.first, p)
592          Bp[1]=p;
593          set_attr(p, attr_icflag, KINSOKU)
594       end
595    else for _, v in pairs(Bp) do add_penalty(v,a) end
596    end
597 end
598
599 local function handle_penalty_always(post, pre, g)
600    local a = (pre or 0) + (post or 0)
601    if #Bp == 0 then
602       if not (g and getid(g)==id_glue) or a~=0 then
603          local p = node_new(id_penalty)
604          if a<-10000 then a = -10000 elseif a>10000 then a = 10000 end
605          setfield(p, 'penalty', a)
606          head = insert_before(head, Np.first, p)
607          Bp[1]=p
608          set_attr(p, attr_icflag, KINSOKU)
609       end
610    else for _, v in pairs(Bp) do add_penalty(v,a) end
611    end
612 end
613
614 local function handle_penalty_suppress(post, pre, g)
615    local a = (pre or 0) + (post or 0)
616    if #Bp == 0 then
617       if g and getid(g)==id_glue then
618          local p = node_new(id_penalty)
619          setfield(p, 'penalty', 10000); head = insert_before(head, Np.first, p)
620          Bp[1]=p
621          set_attr(p, attr_icflag, KINSOKU)
622       end
623    else for _, v in pairs(Bp) do add_penalty(v,a) end
624    end
625 end
626
627 -- 和文文字間の JFM glue を node 化
628 local function new_jfm_glue(m, bc, ac)
629 -- bc, ac: char classes
630    local g, d = m.char_type[bc][ac], 0
631    local n
632    if g then
633       n,d = node_copy(g[2]), g[3]
634       if g[1] then
635          local f = node_new(id_glue)
636          set_attr(f, attr_icflag, g[4])
637          setfield(f, 'spec', n)
638          return f, d
639       end
640    end
641    return n, d
642 end
643
644 -- Nq.last (kern w) .... (glue/kern g) Np.first
645 local function real_insert(g)
646    if g then
647       head  = insert_before(head, Np.first, g)
648       Np.first = g
649    end
650 end
651
652
653 -------------------- 和文文字間空白量の決定
654
655 -- get kanjiskip
656 local get_kanjiskip
657 local get_kanjiskip_normal, get_kanjiskip_jfm
658 do
659    local KANJI_SKIP   = luatexja.icflag_table.KANJI_SKIP
660    local KANJI_SKIP_JFM   = luatexja.icflag_table.KANJI_SKIP_JFM
661    get_kanjiskip_normal = function ()
662       if Np.auto_kspc or Nq.auto_kspc then
663          return node_copy(kanji_skip)
664       else
665          local g = node_copy(zero_glue)
666          set_attr(g, attr_icflag, KANJI_SKIP)
667          return g
668       end
669    end
670
671    get_kanjiskip_jfm = function ()
672       local g
673       if Np.auto_kspc or Nq.auto_kspc then
674          g = node_new(id_glue); --copy_attr(g, Nq.nuc)
675          local gx = node_new(id_glue_spec);
676          setfield(gx, 'stretch_order', 0); setfield(gx, 'shrink_order', 0)
677          local pm, qm = Np.met, Nq.met
678          local bk = qm.kanjiskip or {0, 0, 0}
679          if (pm.char_type==qm.char_type) and (qm.var==pm.var) then
680             setfield(gx, 'width', bk[1])
681             setfield(gx, 'stretch', bk[2])
682             setfield(gx, 'shrink', bk[3])
683          else
684             local ak = pm.kanjiskip or {0, 0, 0}
685             setfield(gx, 'width', round(diffmet_rule(bk[1], ak[1])))
686             setfield(gx, 'stretch', round(diffmet_rule(bk[2], ak[2])))
687             setfield(gx, 'shrink', -round(diffmet_rule(-bk[3], -ak[3])))
688          end
689          setfield(g, 'spec', gx)
690       else
691          g =  node_copy(zero_glue)
692       end
693       set_attr(g, attr_icflag, KANJI_SKIP_JFM)
694       return g
695    end
696 end
697
698 local calc_ja_ja_aux
699 do
700    local bg_ag = 2*id_glue - id_glue
701    local bg_ak = 2*id_glue - id_kern
702    local bk_ag = 2*id_kern - id_glue
703    local bk_ak = 2*id_kern - id_kern
704
705    calc_ja_ja_aux = function (gb,ga, db, da)
706       local rbb, rab = (1-db)/2, (1-da)/2 -- 「前の文字」由来のグルーの割合
707       local rba, raa = (1+db)/2, (1+da)/2 -- 「前の文字」由来のグルーの割合
708       if diffmet_rule ~= math.two_pleft and diffmet_rule ~= math.two_pright
709           and diffmet_rule ~= math.two_paverage then
710          rbb, rab, rba, raa = 1,0,0,1
711       end
712       if not gb then
713          if ga then
714             gb = node_new(id_kern); setfield(gb, 'kern', 0)
715          else return nil end
716       elseif not ga then
717          ga = node_new(id_kern); setfield(ga, 'kern', 0)
718       end
719
720       local k = 2*getid(gb) - getid(ga)
721       if k == bg_ag then
722          local bs, as = getfield(gb, 'spec'), getfield(ga, 'spec')
723          -- 両方とも glue.
724          local bd, ad = getfield(bs, 'width'), getfield(as, 'width')
725          setfield(bs, 'width', round(diffmet_rule(rbb*bd + rba*ad, rab*bd + raa*ad)))
726          bd, ad = getfield(bs, 'stretch'), getfield(as, 'stretch')
727          setfield(bs, 'stretch', round(diffmet_rule(rbb*bd + rba*ad, rab*bd + raa*ad)))
728          bd, ad = getfield(bs, 'shrink'), getfield(as, 'shrink')
729          setfield(bs, 'shrink', -round(diffmet_rule(-rbb*bd - rba*ad, -rab*bd - raa*ad)))
730          node_free(ga)
731          return gb
732       elseif k == bk_ak then
733          -- 両方とも kern.
734          local bd, ad = getfield(gb, 'kern'), getfield(ga, 'kern')
735          setfield(gb, 'kern', round(diffmet_rule(rbb*bd + rba*ad, rab*bd + raa*ad)))
736          node_free(ga)
737          return gb
738       elseif k == bk_ag then
739          local as = getfield(ga, 'spec')
740          -- gb: kern, ga: glue
741          local bd, ad = getfield(gb, 'kern'), getfield(as, 'width')
742          setfield(as, 'width', round(diffmet_rule(rbb*bd + rba*ad, rab*bd + raa*ad)))
743          ad = getfield(as, 'stretch')
744          setfield(bs, 'stretch', round(diffmet_rule(rba*ad, raa*ad)))
745          ad = getfield(as, 'shrink')
746          setfield(bs, 'shrink', -round(diffmet_rule(-rba*ad, -raa*ad)))
747          node_free(gb)
748          return ga
749       else
750          local bs = getfield(gb, 'spec')
751          -- gb: glue, ga: kern
752          local bd, ad = getfield(bs, 'width'), getfield(ga, 'kern')
753          setfield(bs, 'width', round(diffmet_rule(rbb*bd + rba*ad, rab*bd + raa*ad)))
754          bd = getfield(bs, 'stretch')
755          setfield(bs, 'stretch', round(diffmet_rule(rbb*bd, rab*bd)))
756          bd = getfield(bs, 'shrink')
757          setfield(bs, 'shrink', -round(diffmet_rule(-rbb*bd, -rab*bd)))
758          node_free(ga)
759          return gb
760       end
761    end
762 end
763
764 local function calc_ja_ja_glue()
765    if  ihb_flag then return nil
766    else
767       local qm, pm = Nq.met, Np.met
768       if (qm.char_type==pm.char_type) and (qm.var==pm.var) then
769          return new_jfm_glue(qm, Nq.class, Np.class)
770       else
771          local npn, nqn = Np.nuc, Nq.nuc
772          local gb, db = new_jfm_glue(qm, Nq.class,
773                                      slow_find_char_class(has_attr(npn, attr_orig_char),
774                                                           qm, getchar(npn)))
775          local ga, da = new_jfm_glue(pm,
776                                      slow_find_char_class(has_attr(nqn, attr_orig_char),
777                                                           pm, getchar(nqn)),
778                                Np.class)
779          return calc_ja_ja_aux(gb, ga, db, da);
780       end
781    end
782 end
783
784 -------------------- 和欧文間空白量の決定
785
786 -- get xkanjiskip
787 local get_xkanjiskip
788 local get_xkanjiskip_normal, get_xkanjiskip_jfm
789 do
790    local XKANJI_SKIP   = luatexja.icflag_table.XKANJI_SKIP
791    local XKANJI_SKIP_JFM   = luatexja.icflag_table.XKANJI_SKIP_JFM
792    get_xkanjiskip_normal = function (Nn)
793       if (Nq.xspc>=2) and (Np.xspc%2==1) and (Nq.auto_xspc or Np.auto_xspc) then
794          local f = node_copy(xkanji_skip)
795          return f
796       else
797          local g = node_copy(zero_glue)
798          set_attr(g, attr_icflag, XKANJI_SKIP)
799          return g
800       end
801    end
802    get_xkanjiskip_jfm = function (Nn)
803       local g
804       if (Nq.xspc>=2) and (Np.xspc%2==1) and (Nq.auto_xspc or Np.auto_xspc) then
805          g = node_new(id_glue)
806          local gx = node_new(id_glue_spec);
807          setfield(gx, 'stretch_order', 0); setfield(gx, 'shrink_order', 0)
808          local bk = Nn.met.xkanjiskip or {0, 0, 0}
809          setfield(gx, 'width', bk[1])
810          setfield(gx, 'stretch', bk[2])
811          setfield(gx, 'shrink', bk[3])
812          setfield(g, 'spec', gx)
813       else
814          g = node_copy(zero_glue)
815       end
816       set_attr(g, attr_icflag, XKANJI_SKIP_JFM)
817       return g
818    end
819 end
820
821 -------------------- 隣接した「塊」間の処理
822
823 local function get_OA_skip()
824    if not ihb_flag then
825       local pm = Np.met
826       return new_jfm_glue(pm,
827         fast_find_char_class(((Nq.id == id_math and -1) or (type(Nq.char)=='string' and Nq.char or 'jcharbdd')), pm), Np.class)
828    else return nil
829    end
830 end
831 local function get_OB_skip()
832    if not ihb_flag then
833       local qm = Nq.met
834       return new_jfm_glue(qm, Nq.class,
835         fast_find_char_class(((Np.id == id_math and -1) or'jcharbdd'), qm))
836    else return nil
837    end
838 end
839
840 -- (anything) .. jachar
841 local function handle_np_jachar(mode)
842    local qid = Nq.id
843    if qid==id_jglyph or ((qid==id_pbox or qid==id_pbox_w) and Nq.met) then
844       local g = calc_ja_ja_glue() or get_kanjiskip() -- M->K
845       handle_penalty_normal(Nq.post, Np.pre, g); real_insert(g)
846    elseif Nq.met then  -- qid==id_hlist
847       local g = get_OA_skip() or get_kanjiskip() -- O_A->K
848       handle_penalty_normal(0, Np.pre, g); real_insert(g)
849    elseif Nq.pre then
850       local g = get_OA_skip() or get_xkanjiskip(Np) -- O_A->X
851       handle_penalty_normal((qid==id_hlist and 0 or Nq.post), Np.pre, g); real_insert(g)
852    else
853       local g = get_OA_skip() -- O_A
854       if qid==id_glue then handle_penalty_normal(0, Np.pre, g)
855       elseif qid==id_kern then handle_penalty_suppress(0, Np.pre, g)
856       else handle_penalty_always(0, Np.pre, g)
857       end
858       real_insert(g)
859    end
860    if mode and Np.kcat%2~=1 then
861       widow_Np.first, widow_Bp, Bp = Np.first, Bp, widow_Bp
862    end
863 end
864
865
866 -- jachar .. (anything)
867 local function handle_nq_jachar()
868     if Np.pre then
869       local g = get_OB_skip() or get_xkanjiskip(Nq) -- O_B->X
870       handle_penalty_normal(Nq.post, (Np.id==id_hlist and 0 or Np.pre), g); real_insert(g)
871    else
872       local g = get_OB_skip() -- O_B
873       if Np.id==id_glue then handle_penalty_normal(Nq.post, 0, g)
874       elseif Np.id==id_kern then handle_penalty_suppress(Nq.post, 0, g)
875       else handle_penalty_always(Nq.post, 0, g)
876       end
877       real_insert(g)
878    end
879 end
880
881 -- (anything) .. (和文文字で始まる hlist)
882 local function handle_np_ja_hlist()
883    local qid = Nq.id
884    if qid==id_jglyph or ((qid==id_pbox or Nq.id == id_pbox_w) and Nq.met) then
885       local g = get_OB_skip() or get_kanjiskip() -- O_B->K
886       handle_penalty_normal(Nq.post, 0, g); real_insert(g)
887    elseif Nq.met then  -- Nq.id==id_hlist
888       local g = get_kanjiskip() -- K
889       handle_penalty_suppress(0, 0, g); real_insert(g)
890    elseif Nq.pre then
891       local g = get_xkanjiskip(Np) -- X
892       handle_penalty_suppress(0, 0, g); real_insert(g)
893    end
894 end
895
896 -- (和文文字で終わる hlist) .. (anything)
897 local function handle_nq_ja_hlist()
898    if Np.pre then
899       local g = get_xkanjiskip(Nq) -- X
900       handle_penalty_suppress(0, 0, g); real_insert(g)
901    end
902 end
903
904
905 -- Nq が前側のクラスタとなることによる修正
906 do
907    local adjust_nq_aux = {
908       [id_glyph] = function()
909                       local x = Nq.nuc
910                       return set_np_xspc_alchar(Nq, getchar(x),x, 2)
911                    end, -- after_alchar(Nq)
912       [id_hlist]  = function() after_hlist(Nq) end,
913       [id_pbox]  = function() after_hlist(Nq) end,
914       [id_disc]  = function() after_hlist(Nq) end,
915       [id_pbox_w]  = function()
916                         luatexbase.call_callback("luatexja.jfmglue.whatsit_after",
917                                                  false, Nq, Np)
918                      end,
919    }
920
921    function adjust_nq()
922       local x = adjust_nq_aux[Nq.id]
923       if x then x()  end
924    end
925 end
926
927
928 -------------------- 開始・終了時の処理
929 do
930
931 -- リスト末尾の処理
932 local JWP  = luatexja.stack_table_index.JWP
933 local function handle_list_tail(mode)
934    adjust_nq(); Np = Nq
935    if mode then
936       -- the current list is to be line-breaked.
937       -- Insert \jcharwidowpenalty
938       Bp = widow_Bp; Np = widow_Np
939       if Np.first then
940          handle_penalty_normal(0,
941                                table_current_stack[JWP] or 0)
942       end
943    else
944       -- the current list is the contents of a hbox
945       local npi, pm = Np.id, Np.met
946       if npi == id_jglyph or (npi==id_pbox and pm) then
947          local g = new_jfm_glue(pm, Np.class, fast_find_char_class('boxbdd', pm))
948          if g then
949             set_attr(g, attr_icflag, BOXBDD)
950             head = insert_after(head, Np.last, g)
951          end
952       end
953    end
954 end
955
956 -- リスト先頭の処理
957 local function handle_list_head(par_indented)
958    local npi, pm = Np.id, Np.met
959    if npi ==  id_jglyph or (npi==id_pbox and pm) then
960       if not ihb_flag then
961          local g = new_jfm_glue(pm, fast_find_char_class(par_indented, pm), Np.class)
962          if g then
963             set_attr(g, attr_icflag, BOXBDD)
964             if getid(g)==id_glue and #Bp==0 then
965                local h = node_new(id_penalty)
966                setfield(h, 'penalty', 10000); set_attr(h, attr_icflag, BOXBDD)
967             end
968             head = insert_before(head, Np.first, g)
969          end
970       end
971    end
972 end
973
974 -- initialize
975 -- return value: (the initial cursor lp), (last node)
976 local init_var
977 do
978    local KANJI_SKIP   = luatexja.icflag_table.KANJI_SKIP
979    local XKANJI_SKIP   = luatexja.icflag_table.XKANJI_SKIP
980    local KSK  = luatexja.stack_table_index.KSK
981    local XSK  = luatexja.stack_table_index.XSK
982    local dir_yoko = luatexja.dir_table.dir_yoko
983    local dir_tate = luatexja.dir_table.dir_tate
984    local attr_yablshift = luatexbase.attributes['ltj@yablshift']
985    local attr_tablshift = luatexbase.attributes['ltj@tablshift']
986    init_var = function (mode,dir)
987       -- 1073741823: max_dimen
988       Bp, widow_Bp, widow_Np = {}, {}, {first = nil}
989       table_current_stack = ltjs.table_current_stack
990
991       list_dir = ltjs.list_dir or dir_yoko
992       local is_dir_tate = list_dir==dir_tate
993       capsule_glyph = is_dir_tate and ltjw.capsule_glyph_tate or ltjw.capsule_glyph_yoko
994       attr_ablshift = is_dir_tate and attr_tablshift or attr_yablshift
995       set_np_xspc_jachar = is_dir_tate and set_np_xspc_jachar_tate or set_np_xspc_jachar_yoko
996
997
998       tex_dir = dir or 'TLT'
999       kanji_skip = node_new(id_glue)
1000       setfield(kanji_skip, 'spec', skip_table_to_spec(KSK))
1001       set_attr(kanji_skip, attr_icflag, KANJI_SKIP)
1002       get_kanjiskip = (getfield(getfield(kanji_skip, 'spec'), 'width') == 1073741823)
1003          and get_kanjiskip_jfm or get_kanjiskip_normal
1004
1005       xkanji_skip = node_new(id_glue)
1006       setfield(xkanji_skip, 'spec', skip_table_to_spec(XSK))
1007       set_attr(xkanji_skip, attr_icflag, XKANJI_SKIP)
1008       get_xkanjiskip = (getfield(getfield(xkanji_skip, 'spec'), 'width') == 1073741823)
1009          and get_xkanjiskip_jfm or get_xkanjiskip_normal
1010
1011       Np = {
1012          auto_kspc=nil, auto_xspc=nil, char=nil, class=nil,
1013          first=nil, id=nil, last=nil, met=nil, nuc=nil,
1014          post=nil, pre=nil, xspc=nil,
1015       }
1016       Nq = {
1017          auto_kspc=nil, auto_xspc=nil, char=nil, class=nil,
1018          first=nil, id=nil, last=nil, met=nil, nuc=nil,
1019          post=nil, pre=nil, xspc=nil,
1020       }
1021       if mode then
1022          -- the current list is to be line-breaked:
1023          -- hbox from \parindent is skipped.
1024          local lp, par_indented, lpi, lps  = head, 'boxbdd', getid(head), getsubtype(head)
1025          while lp and ((lpi==id_whatsit and lps~=sid_user)
1026                        or ((lpi==id_hlist) and (lps==3))) do
1027             if (lpi==id_hlist) and (lps==3) then
1028                Np.char, par_indented = 'parbdd', 'parbdd'
1029                Np.width = getfield(lp, 'width')
1030             end
1031             lp=node_next(lp); lpi, lps = getid(lp), getsubtype(lp) end
1032          return lp, node_tail(head), par_indented
1033       else
1034          return head, nil, 'boxbdd'
1035       end
1036    end
1037 end
1038
1039 local tex_set_attr = tex.setattribute
1040 local function cleanup(mode)
1041    -- adjust attr_icflag for avoiding error
1042    tex_set_attr('global', attr_icflag, 0)
1043    node_free(kanji_skip); node_free(xkanji_skip)
1044    if mode then
1045       local h = node_next(head)
1046       if getid(h) == id_penalty and getfield(h, 'penalty') == 10000 then
1047          h = node_next(h)
1048          if getid(h) == id_glue and getsubtype(h) == 15 and not node_next(h) then
1049             return false
1050          end
1051       end
1052    end
1053    return head
1054 end
1055 -------------------- 外部から呼ばれる関数
1056
1057 -- main interface
1058 function main(ahead, mode, dir)
1059    if not ahead then return ahead end
1060    head = ahead;
1061    local lp, last, par_indented = init_var(mode,dir)
1062    lp = calc_np(lp, last)
1063    if Np then
1064       extract_np(); handle_list_head(par_indented)
1065    else
1066       return cleanup(mode)
1067    end
1068    lp = calc_np(lp, last)
1069    while Np do
1070       extract_np();
1071       adjust_nq();
1072       local pid, pm = Np.id, Np.met
1073       -- 挿入部
1074       if pid == id_jglyph then
1075          handle_np_jachar(mode)
1076       elseif pm then
1077          if pid==id_hlist then handle_np_ja_hlist()
1078          else handle_np_jachar() end
1079       elseif Nq.met then
1080          if Nq.id==id_hlist then handle_nq_ja_hlist()
1081          else handle_nq_jachar() end
1082       end
1083       lp = calc_np(lp, last)
1084    end
1085    handle_list_tail(mode)
1086    return cleanup(mode)
1087 end
1088 end
1089
1090 do
1091    local IHB  = luatexja.userid_table.IHB
1092    local BPAR = luatexja.userid_table.BPAR
1093    local node_prev = (Dnode ~= node) and Dnode.getprev or node.prev
1094    local node_write = Dnode.write
1095
1096    -- \inhibitglue
1097    function create_inhibitglue_node()
1098       local tn = node_new(id_whatsit, sid_user)
1099       setfield(tn, 'user_id', IHB)
1100       setfield(tn, 'type', 100)
1101       setfield(tn, 'value', 1)
1102       node_write(tn)
1103    end
1104
1105    -- Node for indicating beginning of a paragraph
1106    -- (for ltjsclasses)
1107    function create_beginpar_node()
1108       local tn = node_new(id_whatsit, sid_user)
1109       setfield(tn, 'user_id', BPAR)
1110       setfield(tn, 'type', 100)
1111       setfield(tn, 'value', 1)
1112       node_write(tn)
1113    end
1114
1115    local function whatsit_callback(Np, lp, Nq)
1116       if Np and Np.nuc then return Np
1117       elseif Np and getfield(lp, 'user_id') == BPAR then
1118          Np.first = lp; Np.nuc = lp; Np.last = lp
1119          Np.char = 'parbdd'
1120          Np.met = nil
1121          Np.pre = 0; Np.post = 0
1122          Np.xspc = 0
1123          Np.auto_xspc = false
1124          return Np
1125       end
1126    end
1127
1128     local function whatsit_after_callback(s, Nq, Np)
1129        if not s and getfield(Nq.nuc, 'user_id') == BPAR then
1130          local x, y = node_prev(Nq.nuc), Nq.nuc
1131          Nq.first, Nq.nuc, Nq.last = x, x, x
1132          head = node_remove(head, y)
1133          node_free(y)
1134       end
1135       return s
1136    end
1137
1138    luatexbase.add_to_callback("luatexja.jfmglue.whatsit_getinfo", whatsit_callback,
1139                               "luatexja.beginpar.np_info", 1)
1140    luatexbase.add_to_callback("luatexja.jfmglue.whatsit_after", whatsit_after_callback,
1141                               "luatexja.beginpar.np_info_after", 1)
1142
1143 end