OSDN Git Service

Releases 20240514.0
[luatex-ja/luatexja.git] / src / ltj-jfmglue.lua
1 --
2 -- ltj-jfmglue.lua
3 --
4 luatexbase.provides_module({
5   name = 'luatexja.jfmglue',
6   date = '2022-08-29',
7   description = 'Insertion process of JFM glues, [x]kanjiskip and others',
8 })
9 luatexja.jfmglue = luatexja.jfmglue or {}
10
11 luatexja.load_module 'base';      local ltjb = luatexja.base
12 luatexja.load_module 'stack';     local ltjs = luatexja.stack
13 luatexja.load_module 'jfont';     local ltjf = luatexja.jfont
14 luatexja.load_module 'direction'; local ltjd = luatexja.direction
15 luatexja.load_module 'setwidth';  local ltjw = luatexja.setwidth
16 luatexja.load_module 'lotf_aux';  local ltju = luatexja.lotf_aux
17 local pairs = pairs
18
19 --local to_node = node.direct.tonode
20 --local to_direct = node.direct.todirect
21
22 local getfield = node.direct.getfield
23 local getid = node.direct.getid
24 local getfont = node.direct.getfont
25 local getlist = node.direct.getlist
26 local getchar = node.direct.getchar
27 local getglue = node.direct.getglue
28 local getsubtype = node.direct.getsubtype
29 local getshift = node.direct.getshift
30 local getwidth = node.direct.getwidth
31 local getdepth = node.direct.getdepth
32 local getpenalty = node.direct.getpenalty
33 local setfield = node.direct.setfield
34 local setglue = node.direct.setglue
35 local setshift = node.direct.setshift
36 local if_lang_ja
37 do
38     local lang_ja = luatexja.lang_ja
39     local getlang = node.direct.getlang
40     -- glyph with font number 0 (\nullfont) is always considered an ALchar node
41     if_lang_ja = function (n) return (getlang(n)==lang_ja)and(getfont(n)~=0) end
42 end
43 local setpenalty = node.direct.setpenalty
44 local setkern = node.direct.setkern
45 local call_callback = luatexbase.call_callback
46
47 local get_attr = node.direct.get_attribute
48 local set_attr = node.direct.set_attribute
49 local insert_before = node.direct.insert_before
50 local insert_after = node.direct.insert_after
51 local node_next = node.direct.getnext
52 local ltjd_make_dir_whatsit = ltjd.make_dir_whatsit
53 local ltjf_font_metric_table = ltjf.font_metric_table
54 local ltjf_find_char_class = ltjf.find_char_class
55 local node_new = luatexja.dnode_new
56 local node_copy = node.direct.copy
57 local node_tail = node.direct.tail
58 local node_free = node.direct.flush_node or node.direct.free
59 local node_remove = node.direct.remove
60 local node_inherit_attr = luatexja.node_inherit_attr
61
62 local id_glyph = node.id 'glyph'
63 local id_hlist = node.id 'hlist'
64 local id_vlist = node.id 'vlist'
65 local id_rule  = node.id 'rule'
66 local id_ins   = node.id 'ins'
67 local id_mark  = node.id 'mark'
68 local id_adjust = node.id 'adjust'
69 local id_disc  = node.id 'disc'
70 local id_whatsit = node.id 'whatsit'
71 local id_math  = node.id 'math'
72 local id_glue  = node.id 'glue'
73 local id_kern  = node.id 'kern'
74 local id_penalty = node.id 'penalty'
75
76 local id_jglyph    = 512 -- Japanese character
77 local id_box_like  = 256 -- vbox, shifted hbox
78 local id_pbox      = 257 -- already processed nodes (by \unhbox)
79 local id_pbox_w    = 258 -- cluster which consists of a whatsit
80 local sid_user = node.subtype 'user_defined'
81
82 local ITALIC       = luatexja.icflag_table.ITALIC
83 local PACKED       = luatexja.icflag_table.PACKED
84 local KINSOKU      = luatexja.icflag_table.KINSOKU
85 local FROM_JFM     = luatexja.icflag_table.FROM_JFM
86 local PROCESSED    = luatexja.icflag_table.PROCESSED
87 local IC_PROCESSED = luatexja.icflag_table.IC_PROCESSED
88 local BOXBDD       = luatexja.icflag_table.BOXBDD
89 local SPECIAL_JAGLUE = luatexja.icflag_table.SPECIAL_JAGLUE
90 local PROCESSED_BEGIN_FLAG = luatexja.icflag_table.PROCESSED_BEGIN_FLAG
91
92 local attr_icflag = luatexbase.attributes['ltj@icflag']
93 local kanji_skip
94 local xkanji_skip
95 local table_current_stack
96 local list_dir
97 local capsule_glyph
98 local tex_dir
99 local attr_ablshift
100 local set_np_xspc_jachar, set_np_xspc_alchar
101 local set_np_xspc_jachar_hbox
102
103 local ltjs_orig_char_table = ltjs.orig_char_table
104
105 local function get_attr_icflag(p)
106    return (get_attr(p, attr_icflag) or 0)%PROCESSED_BEGIN_FLAG
107 end
108
109 -------------------- Helper functions
110
111 -- This function is called only for acquiring `special' characters.
112 local function fast_find_char_class(c,m)
113    return m.chars[c] or 0
114 end
115
116 -- 文字クラスの決定
117 local slow_find_char_class, skip_table_to_glue
118 do
119    local start_time_measure = ltjb.start_time_measure
120    local stop_time_measure = ltjb.stop_time_measure
121    local fast_get_stack_skip = ltjs.fast_get_stack_skip
122    function slow_find_char_class (c, m, oc)
123       local cls = ltjf_find_char_class(oc, m)
124       if oc~=c and c and cls==0 then
125          return ltjf_find_char_class(c, m)
126       else
127          return cls
128       end
129    end
130    function skip_table_to_glue(n)
131       local g, st = node_new(id_glue), fast_get_stack_skip(n)
132       setglue(g, st[1], st[2], st[3], st[4], st[5])
133       return g, (st[1]==1073741823)
134    end
135 end
136
137
138 -- penalty 値の計算
139 local add_penalty
140 do
141 function add_penalty(p,e)
142    local pp = getpenalty(p)
143    if (pp>-10000) and (pp<10000) then
144       if e>=10000 then       setpenalty(p, 10000)
145       elseif e<=-10000 then  setpenalty(p, -10000)
146       else
147          pp = pp + e
148          if pp>=10000 then      setpenalty(p, 10000)
149          elseif pp<=-10000 then setpenalty(p, -10000)
150          else                   setpenalty(p, pp) end
151       end
152    end
153 end
154 end
155
156 -- 「異なる JFM」の間の調整方法
157 luatexja.jfmglue.diffmet_rule = math.two_paverage
158 function math.two_add(a,b) return a+b end
159 function math.two_average(a,b) return (a+b)*0.5 end
160 function math.two_paverage(a,b) return (a+b)/2 end
161 function math.two_pleft(a,b) return a end
162 function math.two_pright(a,b) return b end
163
164 local head -- the head of current list
165
166 local Np, Nq, Bp
167 local widow_Bp, widow_Np -- \jcharwidowpenalty 挿入位置管理用
168
169 local non_ihb_flag -- JFM グルー挿入抑止用 flag
170 -- false: \inhibitglue 指定時 true: それ以外
171
172 -------------------- hlist 内の文字の検索
173
174 local first_char, last_char, find_first_char
175 local check_box_high
176 do
177 local ltjd_glyph_from_packed = ltjd.glyph_from_packed
178 local function check_box(box_ptr, box_end)
179    local p = box_ptr; local found_visible_node = false
180    if not p then
181       find_first_char = false; last_char = nil
182       return true
183    end
184    while p and p~=box_end do
185       local pid = getid(p)
186       if pid==id_kern and getsubtype(p)==2 then
187          p = node_next(node_next(node_next(p))); pid = getid(p) -- p must be glyph_node
188       end
189       if pid==id_glyph then
190          repeat
191             if find_first_char then first_char = p; find_first_char = false end
192             last_char = p; found_visible_node = true; p=node_next(p)
193             if (not p) or p==box_end then return found_visible_node end
194          until getid(p)~=id_glyph
195          pid = getid(p) -- p must be non-nil
196       end
197       if pid==id_kern then
198          local pa = get_attr_icflag(p)
199          if pa==IC_PROCESSED then
200             -- do nothing
201          elseif getsubtype(p)==2 then
202             p = node_next(node_next(p));
203             -- Note that another node_next will be executed outside this if-statement.
204          else
205             found_visible_node = true
206             find_first_char = false; last_char = nil
207          end
208       elseif pid==id_hlist then
209          if PACKED == get_attr_icflag(p) then
210             local s = ltjd_glyph_from_packed(p)
211             if find_first_char then first_char = s; find_first_char = false end
212             last_char = s; found_visible_node = true
213          else
214             if getshift(p)==0 then
215                last_char = nil
216                if check_box(getlist(p), nil) then found_visible_node = true end
217                find_first_char = false
218             else
219                find_first_char = false; last_char = nil
220             end
221          end
222       elseif pid==id_math then
223          if find_first_char then first_char = p; find_first_char = false end
224          last_char = p; found_visible_node = true
225       elseif pid==id_rule and get_attr_icflag(p)==PACKED then
226          -- do nothing
227       elseif not (pid==id_ins   or pid==id_mark
228                   or pid==id_adjust or pid==id_whatsit
229                   or pid==id_penalty) then
230          found_visible_node = true
231          find_first_char = false; last_char = nil
232       end
233       p = node_next(p)
234    end
235    return found_visible_node
236 end
237
238 check_box_high = function (Nx, box_ptr, box_end)
239    first_char = nil;  last_char = nil;  find_first_char = true
240    if check_box(box_ptr, box_end) then
241       local first_char = first_char
242       if first_char then
243          if getid(first_char)==id_glyph then
244             if if_lang_ja(first_char) then
245                set_np_xspc_jachar_hbox(Nx, first_char)
246             else
247                set_np_xspc_alchar(Nx, getchar(first_char),first_char, 1)
248             end
249          else -- math_node
250             set_np_xspc_alchar(Nx, -1,first_char)
251          end
252       end
253    end
254    return last_char
255 end
256 end
257 -------------------- Np の計算と情報取得
258
259 luatexbase.create_callback("luatexja.jfmglue.whatsit_getinfo", "data",
260                            function (Np, lp, Nq)
261                               if Np.nuc then return Np
262                               else
263                                  return Np  -- your code
264                               end
265                            end)
266 luatexbase.create_callback("luatexja.jfmglue.whatsit_after", "data",
267                            function (stat, Nq, Np) return false end)
268 luatexbase.create_callback("luatexja.jfmglue.whatsit_last_minute", "data",
269                            function (stat, Nq, Np) return false end)
270
271 -- calc next Np
272 local calc_np
273 do -- 001 -----------------------------------------------
274
275 local traverse = node.direct.traverse
276 local function check_next_ickern(lp)
277    local lx = Np.nuc
278    while lp and getid(lp) == id_kern and ( getsubtype(lp)==0 or
279      getsubtype(lp)==3 or ITALIC == get_attr_icflag(lp)) do
280      set_attr(lp, attr_icflag, IC_PROCESSED)
281      lx, lp = lp, node_next(lp)
282    end
283    Np.last = lx; return lp
284 end
285
286 local function calc_np_pbox(lp, last)
287    local first, nc = (not Np.first), nil
288    --local lpa = get_attr_icflag(lp)==PACKED and PACKED or KINSOKU -- KINSOKU: dummy
289    local lpa = get_attr_icflag(lp)
290    Np.first = Np.first or lp; Np.id = id_pbox
291    set_attr(lp, attr_icflag, get_attr_icflag(lp))
292    while lp ~=last and (lpa>=PACKED) and (lpa<BOXBDD) do
293       local lpi = getid(lp)
294       if lpa==PACKED then
295          if lpi==id_rule then lp = node_next(lp) end
296          nc, lp = lp, node_next(lp)
297       elseif lpi==id_hlist or lpi==id_vlist then
298          head, lp, nc = ltjd_make_dir_whatsit(head, lp, list_dir, 'jfm pbox')
299          Np.first = first and nc or Np.first
300       else
301          nc, lp = lp, node_next(lp)
302       end
303       first, lpa = false, (lp and get_attr(lp, attr_icflag) or 0)
304      -- get_attr_icflag() ではいけない!
305    end
306    Np.nuc = nc
307    lp = check_next_ickern(lp)
308    Np.last_char = check_box_high(Np, Np.first, lp)
309    return lp
310 end
311
312 local calc_np_aux_glyph_common
313 do -- 002 ---------------------------------------
314    local min, max = math.min, math.max
315    local getwhd = node.direct.getwhd
316    local attr_jchar_class = luatexbase.attributes['ltj@charclass']
317    local attr_jchar_code = luatexbase.attributes['ltj@charcode']
318    local font_getfont = font.getfont
319    local setwhd = node.direct.setwhd
320    local setdir = node.direct.setdir
321    local function calc_np_notdef(lp)
322       if not font_getfont(getfont(lp)).characters[getchar(lp)] then
323          local ln = node_next(lp)
324          if ltju.specified_feature(getfont(lp), 'notdef') and ln and getid(ln)==id_glyph then
325             set_attr(lp, attr_icflag, PROCESSED)
326             set_attr(ln, attr_jchar_code, get_attr(lp, attr_jchar_code) or getchar(lp))
327             set_attr(ln, attr_jchar_class, get_attr(lp, attr_jchar_class) or 0)
328             Np.nuc, lp = ln, ln
329          end
330       end
331       return lp
332    end
333 function calc_np_aux_glyph_common(lp, acc_flag)
334    Np.nuc, Np.first = lp, (Np.first or lp)
335    if if_lang_ja(lp) then -- JAchar
336       Np.id = id_jglyph
337       local m, mc, cls = set_np_xspc_jachar(Np, lp)
338       local npi, npf
339       local w, h, d = getwhd(lp)
340       if w==0 and h==0 and d==0 then lp = calc_np_notdef(lp) end
341       lp, head, npi, npf = capsule_glyph(lp, m, mc[cls], head, tex_dir)
342       Np.first = (Np.first~=Np.nuc) and Np.first or npf or npi
343       Np.nuc = npi
344       return true, check_next_ickern(lp);
345    else --ALchar
346       Np.id = id_glyph
347       set_np_xspc_alchar(Np, getchar(lp), lp, 1)
348       -- loop
349       local first_glyph, last_glyph = lp
350       set_attr(lp, attr_icflag, PROCESSED); Np.last = lp
351       local y_adjust = get_attr(lp,attr_ablshift) or 0
352       local node_depth = getdepth(lp) + min(y_adjust, 0)
353       local adj_depth = (y_adjust>0) and (getdepth(lp) + y_adjust) or 0
354       setfield(lp, 'yoffset', getfield(lp, 'yoffset') - y_adjust); lp = node_next(lp)
355       local lx=lp
356       while lx do
357          local lai = get_attr_icflag(lx)
358          if lx==last or  lai>=PACKED then break
359          else
360             local lid = getid(lx)
361             if lid==id_glyph and not if_lang_ja(lx) then
362                -- 欧文文字
363                last_glyph = lx; set_attr(lx, attr_icflag, PROCESSED); Np.last = lx
364                y_adjust = get_attr(lx,attr_ablshift) or 0
365                node_depth = max(getdepth(lx) + min(y_adjust, 0), node_depth)
366                adj_depth = (y_adjust>0) and max(getdepth(lx) + y_adjust, adj_depth) or adj_depth
367                setfield(lx, 'yoffset', getfield(lx, 'yoffset') - y_adjust); lx = node_next(lx)
368             elseif lid==id_kern then
369                local ls = getsubtype(lx)
370                if ls==2 then -- アクセント用の kern
371                   set_attr(lx, attr_icflag, PROCESSED)
372                   lx = node_next(lx) -- lx: アクセント本体
373                   if getid(lx)==id_glyph then
374                      setfield(lx, 'yoffset', getfield(lx, 'yoffset') - (get_attr(lx,attr_ablshift) or 0))
375                   else -- アクセントは上下にシフトされている
376                      setshift(lx, getshift(lx) + (get_attr(lx,attr_ablshift) or 0))
377                   end
378                   set_attr(lx, attr_icflag, PROCESSED)
379                   lx = node_next(lx); set_attr(lx, attr_icflag, PROCESSED)
380                   lx = node_next(lx); set_attr(lx, attr_icflag, PROCESSED)
381                elseif ls==0  then
382                   Np.last = lx; lx = node_next(lx)
383                elseif (ls==3) or (lai==ITALIC) then
384                   Np.last = lx; set_attr(lx, attr_icflag, IC_PROCESSED); lx = node_next(lx)
385                else break
386                end
387             else break
388             end
389          end
390       end
391       lp=lx
392       local r
393       if adj_depth>node_depth then
394             r = node_new(id_rule,3,first_glyph)
395             setwhd(r, 0, 0, adj_depth); setdir(r, tex_dir)
396             set_attr(r, attr_icflag, PROCESSED)
397       end
398       if last_glyph then
399          Np.last_char = last_glyph
400          if r then insert_after(head, first_glyph, r) end
401       else
402          local npn = Np.nuc
403          Np.last_char = npn
404          if r then
405             local nf, nc = getfont(npn), getchar(npn)
406             local ct = (font_getfont(nf) or font.fonts[nf] ).characters[nc]
407             if not ct then -- variation selector
408                node_free(r)
409             elseif (ct.left_protruding or 0) == 0 then
410                head = insert_before(head, npn, r)
411                Np.first = acc_flag and Np.first or ((Np.first==npn) and r or npn)
412             elseif (ct.right_protruding or 0) == 0 then
413                insert_after(head, npn, r); Np.last, lp = r, r
414             else
415                ltjb.package_warning_no_line(
416                   'luatexja',
417                   'Check depth of glyph node ' .. tostring(npn) .. '(font=' .. nf
418                      .. ', char=' .. nc .. '),    because its \\lpcode is ' .. tostring(ct.left_protruding)
419                      .. ' and its \\rpcode is ' .. tostring(ct.right_protruding)
420                ); node_free(r)
421             end
422          end
423       end
424       return true, lp
425    end
426 end
427 end -- 002 ---------------------------------------
428 local calc_np_auxtable
429 do  -- 002 ---------------------------------------
430 local ltjw_apply_ashift_math = ltjw.apply_ashift_math
431 local ltjw_apply_ashift_disc = ltjw.apply_ashift_disc
432 local node_end_of_math = node.direct.end_of_math
433 local dir_tate = luatexja.dir_table.dir_tate
434 local sid_start_link   = node.subtype 'pdf_start_link'
435 local sid_start_thread = node.subtype 'pdf_start_thread'
436 local sid_end_link     = node.subtype 'pdf_end_link'
437 local sid_end_thread   = node.subtype 'pdf_end_thread'
438 local getvalue = node.direct.getdata
439 calc_np_auxtable = {
440    [id_glyph] = calc_np_aux_glyph_common,
441    [id_hlist] = function(lp)
442       local op, flag
443       head, lp, op, flag = ltjd_make_dir_whatsit(head, lp, list_dir, 'jfm hlist')
444       set_attr(op, attr_icflag, PROCESSED)
445       Np.first = Np.first or op; Np.last = op; Np.nuc = op;
446       if (flag or getshift(op)~=0) then
447          Np.id = id_box_like
448       else
449          Np.id = id_hlist
450          Np.last_char = check_box_high(Np, getlist(op), nil)
451       end
452       return true, lp
453    end,
454    [id_vlist] =  function(lp)
455       local op
456       head, lp, op = ltjd_make_dir_whatsit(head, lp, list_dir, 'jfm:' .. getid(lp))
457       Np.first = Np.first or op; Np.last = op; Np.nuc = op;
458       Np.id = id_box_like;
459       return true, lp
460    end,
461    box_like = function(lp)
462       Np.first = Np.first or lp; Np.last = lp; Np.nuc = lp;
463       Np.id = id_box_like;
464       return true, node_next(lp)
465    end,
466    [id_whatsit] = function(lp)
467       local lps = getsubtype(lp)
468       if lps==sid_user then
469          if getfield(lp, 'user_id')==luatexja.userid_table.IHB then
470             local lq = node_next(lp);
471             head = node_remove(head, lp); node_free(lp); non_ihb_flag = getvalue(lp)~=1
472             return false, lq;
473          elseif getfield(lp, 'user_id')==luatexja.userid_table.JA_AL_BDD then
474             local lq = node_next(lp);
475             head = node_remove(head, lp); node_free(lp)
476             return false, lq;
477          else
478             set_attr(lp, attr_icflag, PROCESSED)
479             call_callback("luatexja.jfmglue.whatsit_getinfo",
480                                      Np, lp, Nq)
481             if Np.nuc then
482                Np.id = id_pbox_w; Np.first = Np.nuc; Np.last = Np.nuc;
483                return true, node_next(lp)
484             else
485                return false, node_next(lp)
486             end
487          end
488       else
489          -- we do special treatment for these whatsit nodes.
490          if lps == sid_start_link or lps == sid_start_thread then
491             Np.first = lp
492          elseif lps == sid_end_link or lps == sid_end_thread then
493             Np.first, Nq.last = nil, lp;
494          end
495          set_attr(lp, attr_icflag, PROCESSED)
496          return false, node_next(lp)
497       end
498    end,
499    [id_math] = function(lp)
500       Np.first, Np.nuc = (Np.first or lp), lp;
501       set_attr(lp, attr_icflag, PROCESSED)
502       set_np_xspc_alchar(Np, -1, lp)
503       local end_math  = node_end_of_math(lp)
504       ltjw_apply_ashift_math(lp, end_math, attr_ablshift)
505       set_attr(end_math, attr_icflag, PROCESSED)
506       Np.last, Np.id = end_math, id_math;
507       return true, node_next(end_math);
508    end,
509    [id_glue] = function(lp)
510       Np.first, Np.nuc, Np.last = (Np.first or lp), lp, lp;
511       Np.id = getid(lp);
512       local f = call_callback("luatexja.jfmglue.special_jaglue", lp)
513       if f then
514          set_attr(lp, attr_icflag, PROCESSED)
515       end
516       return true, node_next(lp)
517    end,
518    [id_disc] = function(lp)
519       Np.first, Np.nuc, Np.last = (Np.first or lp), lp, lp;
520       Np.id = getid(lp); set_attr(lp, attr_icflag, PROCESSED)
521       ltjw_apply_ashift_disc(lp, (list_dir==dir_tate), tex_dir)
522       Np.last_char = check_box_high(Np, getfield(lp, 'replace'), nil)
523       return true, node_next(lp)
524    end,
525    [id_kern] = function(lp)
526       if getsubtype(lp)==2 then
527          Np.first = Np.first or lp
528          set_attr(lp, attr_icflag, PROCESSED); lp = node_next(lp)
529          if getid(lp)==id_glyph then -- アクセント本体
530             setfield(lp, 'yoffset', getfield(lp, 'yoffset') - (get_attr(lp,attr_ablshift) or 0))
531          else -- アクセントは上下にシフトされている
532             setshift(lp, getshift(lp) + (get_attr(lp,attr_ablshift) or 0))
533          end
534          set_attr(lp, attr_icflag, PROCESSED); lp = node_next(lp)
535          set_attr(lp, attr_icflag, PROCESSED); lp = node_next(lp)
536          set_attr(lp, attr_icflag, PROCESSED);
537          return calc_np_aux_glyph_common(lp, true)
538       else
539          Np.first = Np.first or lp
540          Np.id = id_kern; set_attr(lp, attr_icflag, PROCESSED)
541          Np.last = lp; return true, node_next(lp)
542       end
543    end,
544    [id_penalty] = function(lp)
545       Bp[#Bp+1] = lp; set_attr(lp, attr_icflag, PROCESSED)
546       return false, node_next(lp)
547    end,
548 }
549 end -- 002 ---------------------------------------
550 calc_np_auxtable[id_rule]   = calc_np_auxtable.box_like
551 calc_np_auxtable[15]        = calc_np_auxtable.box_like
552
553 local function calc_np_aux_skip (lp)
554    set_attr(lp, attr_icflag, PROCESSED)
555    return false, node_next(lp)
556 end
557
558 function calc_np(last, lp)
559    local k
560    -- We assume lp = node_next(Np.last)
561    if Nq and Nq.id==id_pbox_w then
562       call_callback("luatexja.jfmglue.whatsit_last_minute", false, Nq, Np)
563    end
564    Np, Nq, non_ihb_flag = Nq, Np, true
565    -- We clear `predefined' entries of Np before pairs() loop,
566    -- because using only pairs() loop is slower.
567    Np.post, Np.pre, Np.xspc, Np.gk = nil, nil, nil, nil
568    Np.first, Np.id, Np.last, Np.met, Np.class= nil, nil, nil, nil
569    Np.auto_kspc, Np.auto_xspc, Np.char, Np.nuc = nil, nil, nil, nil
570    -- auto_kspc, auto_xspc: normally true/false,
571    -- but the number 0 when Np is ''the beginning of the box/paragraph''.
572    for k in pairs(Np) do Np[k] = nil end
573
574    for k = 1,#Bp do Bp[k] = nil end
575    while lp ~= last  do
576       local lpa = get_attr(lp, attr_icflag) or 0
577       -- unbox 由来ノードの検出
578       if (lpa>=PACKED) and (lpa%PROCESSED_BEGIN_FLAG<=BOXBDD) then
579          if lpa%PROCESSED_BEGIN_FLAG == BOXBDD then
580             local lq = node_next(lp)
581             head = node_remove(head, lp); node_free(lp); lp = lq
582          else
583             return calc_np_pbox(lp, last)
584          end -- id_pbox
585       else
586          k, lp = (calc_np_auxtable[getid(lp)] or calc_np_aux_skip)(lp)
587          if k then return lp end
588       end
589    end
590    Np=nil
591 end
592 end -- 001 -----------------------------------------------
593
594 -- extract informations from Np
595 -- We think that "Np is a Japanese character" if Np.met~=nil,
596 --            "Np is an alphabetic character" if Np.pre~=nil,
597 --            "Np is not a character" otherwise.
598 local after_hlist = nil -- global
599 local after_alchar, extract_np
600 do
601   local PRE  = luatexja.stack_table_index.PRE
602   local POST = luatexja.stack_table_index.POST
603   local KCAT = luatexja.stack_table_index.KCAT
604   local XSP  = luatexja.stack_table_index.XSP
605   local dir_tate = luatexja.dir_table.dir_tate
606
607 -- 和文文字のデータを取得
608    local has_attr = node.direct.has_attribute
609    local attr_jchar_class = luatexbase.attributes['ltj@charclass']
610    local attr_jchar_code = luatexbase.attributes['ltj@charcode']
611    local attr_autospc = luatexbase.attributes['ltj@autospc']
612    local attr_autoxspc = luatexbase.attributes['ltj@autoxspc']
613    local getcomponents = node.direct.getcomponents
614    --local ltjf_get_vert_glyph = ltjf.get_vert_glyph
615    function set_np_xspc_jachar(Nx, x)
616       local m = ltjf_font_metric_table[getfont(x)]
617       local c, c_glyph = (not getcomponents(x) and ltjs_orig_char_table[x]), getchar(x)
618       if c and c~=c_glyph then set_attr(x, attr_jchar_code, c) end
619       c = c or c_glyph
620       local cls = slow_find_char_class(c, m, c_glyph)
621       Nx.met, Nx.class, Nx.char = m, cls, c;
622       local mc = m.char_type; Nx.char_type = mc
623       if cls~=0 then set_attr(x, attr_jchar_class, cls) end
624       Nx.pre  = table_current_stack[PRE + c]  or 0
625       Nx.post = table_current_stack[POST + c] or 0
626       Nx.xspc = table_current_stack[XSP  + c] or 3
627       Nx.kcat = table_current_stack[KCAT + c] or 0
628       Nx.auto_kspc, Nx.auto_xspc
629        = not has_attr(x, attr_autospc, 0), not has_attr(x, attr_autoxspc, 0)
630       return m, mc, cls
631    end
632    function set_np_xspc_jachar_hbox(Nx, x)
633       local m = ltjf_font_metric_table[getfont(x)]
634       local c = get_attr(x, attr_jchar_code) or getchar(x)
635       Nx.met, Nx.char  = m, c; Nx.class = get_attr(x, attr_jchar_class) or 0;
636       local mc = m.char_type; Nx.char_type = mc
637       Nx.pre  = table_current_stack[PRE + c]  or 0
638       Nx.post = table_current_stack[POST + c] or 0
639       Nx.xspc = table_current_stack[XSP  + c] or 3
640       Nx.kcat = table_current_stack[KCAT + c] or 0
641       Nx.auto_kspc, Nx.auto_xspc
642        = not has_attr(x, attr_autospc, 0), not has_attr(x, attr_autoxspc, 0)
643    end
644
645 -- 欧文文字のデータを取得
646    local floor = math.floor
647    local nullfunc = function(n) return n end
648    function set_np_xspc_alchar(Nx, c,x, lig)
649       if c~=-1 then
650          local f = (lig ==1) and nullfunc or node_tail
651          local xc, xs = getcomponents(x), getsubtype(x)
652          while xc and xs and xs%4>=2 do
653             x = f(xc);
654             if getid(x)==id_disc then x, xc, xs = nil, getfield(x,'replace'), 2
655             else xc, xs = getcomponents(x), getsubtype(x) end
656          end
657          c = x and getchar(x) or c
658          Nx.pre  = table_current_stack[PRE + c]  or 0
659          Nx.post = table_current_stack[POST + c] or 0
660       else
661          Nx.pre, Nx.post = 0, 0
662       end
663       Nx.met = nil
664       Nx.xspc = table_current_stack[XSP  + c] or 3
665       Nx.auto_xspc = not has_attr(x, attr_autoxspc, 0)
666    end
667    local set_np_xspc_alchar = set_np_xspc_alchar
668    -- change the information for the next loop
669    -- (will be done if Nx is an alphabetic character or a hlist)
670    after_hlist = function (Nx)
671       local s = Nx.last_char
672       if s then
673          if getid(s)==id_glyph then
674             if if_lang_ja(s) then
675                set_np_xspc_jachar_hbox(Nx, s)
676             else
677                set_np_xspc_alchar(Nx, getchar(s), s, 2)
678             end
679          else
680             set_np_xspc_alchar(Nx, -1, s)
681          end
682       else
683          Nx.pre, Nx.met = nil, nil
684       end
685    end
686    after_alchar = function (Nx)
687       local x = Nx.last_char
688       return set_np_xspc_alchar(Nx, getchar(x), x, 2)
689    end
690
691 end
692
693 -------------------- 最下層の処理
694
695 luatexbase.create_callback('luatexja.adjust_jfmglue', 'simple', function(n) return n end)
696
697 -- change penalties (or create a new penalty, if needed)
698 local function handle_penalty_normal(post, pre, g)
699    call_callback('luatexja.adjust_jfmglue', head, Nq, Np, Bp)
700    local a = (pre or 0) + (post or 0)
701    if #Bp == 0 then
702       if (a~=0 and not(g and getid(g)==id_kern)) then
703          local p = node_new(id_penalty, nil, Nq.nuc, Np.nuc)
704          if a<-10000 then a = -10000 elseif a>10000 then a = 10000 end
705          setpenalty(p, a); head = insert_before(head, Np.first, p)
706          Bp[1]=p; set_attr(p, attr_icflag, KINSOKU)
707       end
708    else for _, v in pairs(Bp) do add_penalty(v,a) end
709    end
710 end
711
712 local function handle_penalty_always(post, pre, g)
713    call_callback('luatexja.adjust_jfmglue', head, Nq, Np, Bp)
714    local a = (pre or 0) + (post or 0)
715    if #Bp == 0 then
716       if not (g and getid(g)==id_glue) or a~=0 then
717          local p = node_new(id_penalty, nil, Nq.nuc, Np.nuc)
718          if a<-10000 then a = -10000 elseif a>10000 then a = 10000 end
719          setpenalty(p, a); head = insert_before(head, Np.first, p)
720          Bp[1]=p; set_attr(p, attr_icflag, KINSOKU)
721       end
722    else for _, v in pairs(Bp) do add_penalty(v,a) end
723    end
724 end
725
726 local function handle_penalty_suppress(post, pre, g)
727    call_callback('luatexja.adjust_jfmglue', head, Nq, Np, Bp)
728    if #Bp == 0 then
729       if g and getid(g)==id_glue then
730          local p = node_new(id_penalty, nil, Nq.nuc, Np.nuc)
731          setpenalty(p, 10000); head = insert_before(head, Np.first, p)
732          Bp[1]=p; set_attr(p, attr_icflag, KINSOKU)
733       end
734    else
735       local a = (pre or 0) + (post or 0)
736       for _, v in pairs(Bp) do add_penalty(v,a) end
737    end
738 end
739
740 local function handle_penalty_jwp()
741    local a = table_current_stack[luatexja.stack_table_index.JWP]
742    if #widow_Bp == 0 then
743       if a~=0 then
744          local p = node_new(id_penalty, widow_Np.nuc)
745          if a<-10000 then a = -10000 elseif a>10000 then a = 10000 end
746          setpenalty(p, a); head = insert_before(head, widow_Np.first, p)
747          widow_Bp[1]=p; set_attr(p, attr_icflag, KINSOKU)
748       end
749    else for _, v in pairs(widow_Bp) do add_penalty(v,a) end
750    end
751 end
752
753 -- 和文文字間の JFM glue を node 化
754 local function new_jfm_glue(mc, bc, ac)
755 -- bc, ac: char classes
756    local g = mc[bc][ac]
757    if g then
758        if g[1] then
759           local k = node_new(id_kern, 1); setkern(k, g[1])
760           set_attr(k, attr_icflag, FROM_JFM)
761           return k, g.ratio, false, false, false
762        else
763           local f = node_new(id_glue)
764           set_attr(f, attr_icflag, g.priority)
765           setglue(f, g[2], g[3], g[4])
766           return f, g.ratio, g.kanjiskip_natural, g.kanjiskip_stretch, g.kanjiskip_shrink
767       end
768    end
769    return false, 0
770 end
771
772 -- Nq.last (kern w) .... (glue/kern g) Np.first
773 local function real_insert(g)
774    if g then
775       head, Np.first = insert_before(head, Np.first, node_inherit_attr(g, Nq.nuc, Np.nuc))
776       local ngk = Np.gk
777       if not ngk then Np.gk = g
778       elseif type(ngk)=="table" then ngk[#ngk+1]=g
779       else  Np.gk = { ngk, g } end
780    end
781 end
782
783
784 -------------------- 和文文字間空白量の決定
785 local calc_ja_ja_aux
786 do
787    local round = tex.round
788    local bg_ag = 2*id_glue - id_glue
789    local bg_ak = 2*id_glue - id_kern
790    local bk_ag = 2*id_kern - id_glue
791    local bk_ak = 2*id_kern - id_kern
792    local getkern = node.direct.getkern
793
794    local function blend_diffmet(b, a, rb, ra)
795       return round(luatexja.jfmglue.diffmet_rule((1-rb)*b+rb*a, (1-ra)*b+ra*a))
796    end
797    local blend_diffmet_inf
798    do
799       local abs, log, log264, floor = math.abs, math.log, math.log(2)*64, math.floor
800       blend_diffmet_inf = function (b, a, bo, ao, rb, ra)
801          local nb, na = (bo and b*2.0^(64*bo) or 0), (ao and a*2.0^(64*ao) or 0)
802          local r = luatexja.jfmglue.diffmet_rule((1-rb)*nb+rb*na, (1-ra)*nb+ra*na)
803          local ro = (r~=0) and floor(log(abs(r))/log264+0.0625) or 0
804          return round(r/2.^(64*ro)), ro
805       end
806    end
807    calc_ja_ja_aux = function (gb, ga, db, da)
808       if luatexja.jfmglue.diffmet_rule ~= math.two_pleft and diffmet_rule ~= math.two_pright
809           and luatexja.jfmglue.diffmet_rule ~= math.two_paverage then
810          db, da = 0, 1
811       end
812       if not gb then
813          if ga then gb = node_new(id_kern, 1); setkern(gb, 0)
814          else return nil end
815       elseif not ga then
816          ga = node_new(id_kern, 1); setkern(ga, 0)
817       end
818       local gbw, gaw, gbst, gast, gbsto, gasto, gbsh, gash, gbsho, gasho
819       if getid(gb)==id_glue then
820          gbw, gbst, gbsh, gbsto, gbsho = getglue(gb)
821       else
822          gbw = getkern(gb)
823       end
824       if getid(ga)==id_glue then
825          gaw, gast, gash, gasto, gasho = getglue(ga)
826       else
827          gaw = getkern(ga)
828       end
829       if not (gbst or gast) then -- 両方とも kern
830          setkern(gb, blend_diffmet(gbw, gaw, db, da))
831          node_free(ga); return gb
832       else
833          local gr = gb
834          if not gbst then gr = ga; node_free(gb) else node_free(ga) end
835          gbw = blend_diffmet(gbw or 0, gaw or 0, db, da) -- 結果の自然長
836          gbst, gbsto = blend_diffmet_inf(gbst, gast, gbsto, gasto, db, da) -- 伸び
837          gbsh, gbsho = blend_diffmet_inf(-(gbsh or 0), -(gash or 0), gbsho, gasho, db, da) -- -(縮み)
838          setglue(gr, gbw, gbst, -gbsh, gbsto, gbsho)
839          return gr
840       end
841    end
842 end
843
844 local null_skip_table = {0, 0, 0}
845 -- get kanjiskip
846 local get_kanjiskip, kanjiskip_jfm_flag
847 local get_kanjiskip_low
848 local calc_ja_ja_glue
849 do
850    local KANJI_SKIP   = luatexja.icflag_table.KANJI_SKIP
851    local KANJI_SKIP_JFM   = luatexja.icflag_table.KANJI_SKIP_JFM
852
853    get_kanjiskip_low = function(flag, qm, bn, bp, bh)
854    -- flag = false: kanjiskip そのもの(パラメータ or JFM)
855    --               ノード kanji_skip のコピーで良い場合は nil が帰る
856    -- flag = true: JFM グルーに付随する kanjiskip 自然長/伸び/縮み分
857       if qm.with_kanjiskip and (bn or bp or bh) then
858          if kanjiskip_jfm_flag then
859             local g = node_new(id_glue);
860             local bk = qm.kanjiskip or null_skip_table
861             setglue(g, bn and (bn*bk[1]) or 0,
862                        bp and (bp*bk[2]) or 0,
863                        bh and (bh*bk[3]) or 0, 0, 0)
864             set_attr(g, attr_icflag, KANJI_SKIP_JFM)
865             return g
866          elseif flag then
867             local g = node_new(id_glue)
868             local st = bp and (bp*getfield(kanji_skip, 'stretch')) or 0
869             local sh = bh and (bh*getfield(kanji_skip, 'shrink')) or 0
870             setglue(g,
871                bn and (bn*getwidth(kanji_skip)) or 0,
872                st, sh,
873                (st==0) and 0 or getfield(kanji_skip, 'stretch_order'),
874                (sh==0) and 0 or getfield(kanji_skip, 'shrink_order'))
875             set_attr(g, attr_icflag, KANJI_SKIP_JFM)
876             return g
877          end
878       end
879    end
880
881    get_kanjiskip = function()
882       if Np.auto_kspc==0 or Nq.auto_kspc==0 then return nil
883       elseif Np.auto_kspc or Nq.auto_kspc then
884          local pm, qm = Np.met, Nq.met
885          if (pm.char_type==qm.char_type) and (qm.var==pm.var) then
886              return get_kanjiskip_low(false, qm, 1, 1, 1) or node_copy(kanji_skip)
887          else
888             local gb = get_kanjiskip_low(false, qm, 1, 1, 1)
889             if gb then
890                return calc_ja_ja_aux(gb,
891                  get_kanjiskip_low(false, pm, 1, 1, 1) or node_copy(kanji_skip), 0, 1)
892             else
893                local ga = get_kanjiskip_low(false, pm, 1, 1, 1)
894                return (ga and calc_ja_ja_aux(node_copy(kanji_skip), ga, 0, 1))
895                  or node_copy(kanji_skip)
896             end
897          end
898       else
899          local g = node_new(id_glue)
900          set_attr(g, attr_icflag, kanjiskip_jfm_flag and KANJI_SKIP_JFM or KANJI_SKIP)
901          return g
902       end
903    end
904
905    calc_ja_ja_glue = function ()
906       local qm, pm = Nq.met, Np.met
907       local qmc, pmc = qm.char_type, pm.char_type
908       if (qmc==pmc) and (qm.var==pm.var) then
909          local g, _, kn, kp, kh = new_jfm_glue(qmc, Nq.class, Np.class)
910          return g, (Np.auto_kspc or Nq.auto_kspc) and get_kanjiskip_low(true, qm, kn, kp, kh)
911       else
912          local npn, nqn = Np.nuc, Nq.nuc
913          local gb, db, bn, bp, bh
914             = new_jfm_glue(qmc, Nq.class,
915                            slow_find_char_class(Np.char,
916                                                 qm, getchar(npn)))
917          local ga, da, an, ap, ah
918             = new_jfm_glue(pmc,
919                            slow_find_char_class(Nq.char,
920                                                 pm, getchar(nqn)),
921                            Np.class)
922          local g = calc_ja_ja_aux(gb, ga, db, da)
923          local k
924          gb = get_kanjiskip_low(true, qm, bn, bp, bh)
925          ga = get_kanjiskip_low(true, pm, an, ap, ah)
926          k = calc_ja_ja_aux(gb, ga, db, da)
927          return g, k
928       end
929    end
930 end
931
932 -------------------- 和欧文間空白量の決定
933
934 -- get xkanjiskip
935 local get_xkanjiskip, xkanjiskip_jfm_flag
936 local get_xkanjiskip_normal, get_xkanjiskip_jfm
937 local get_xkanjiskip_low
938 do
939    local XKANJI_SKIP   = luatexja.icflag_table.XKANJI_SKIP
940    local XKANJI_SKIP_JFM   = luatexja.icflag_table.XKANJI_SKIP_JFM
941
942    get_xkanjiskip_low = function(flag, qm, bn, bp, bh)
943       if flag or (qm.with_kanjiskip and (bn or bp or bh)) then
944          if xkanjiskip_jfm_flag then
945             local g = node_new(id_glue);
946             local bk = qm.xkanjiskip or null_skip_table
947             setglue(g, bn and bk[1] or 0,
948                        bp and bk[2] or 0,
949                        bh and bk[3] or 0, 0, 0)
950             set_attr(g, attr_icflag, XKANJI_SKIP_JFM)
951             return g
952          elseif flag then
953             return node_copy(xkanji_skip)
954          else
955             local g = node_new(id_glue)
956             local w, st, sh, sto, sho = getglue(xkanji_skip)
957             setglue(g,
958                bn and (bn*w) or 0,
959                bp and (bp*st) or 0,
960                bh and (bh*sh) or 0,
961                bp and sto or 0,
962                bh and sho or 0)
963             set_attr(g, attr_icflag, XKANJI_SKIP_JFM)
964             return g
965          end
966       end
967    end
968
969    get_xkanjiskip = function(Nn)
970       if Np.auto_xspc==0 or Nq.auto_xspc==0 then
971         return nil
972       elseif (Nq.xspc>=2) and (Np.xspc%2==1) and (Nq.auto_xspc or Np.auto_xspc) then
973          return get_xkanjiskip_low(true, Nn.met, 1, 1, 1)
974       else
975          local g = node_new(id_glue)
976          set_attr(g, attr_icflag, xkanjiskip_jfm_flag and XKANJI_SKIP_JFM or XKANJI_SKIP)
977          return g
978       end
979    end
980 end
981
982 -------------------- 隣接した「塊」間の処理
983
984 local function combine_spc(name)
985    return (Np[name] or Nq[name]) and ((Np[name]~=0) and (Nq[name]~=0))
986 end
987
988 -- NA, NB: alchar or math
989 local function get_NA_skip()
990    local pm = Np.met
991    local qclass = fast_find_char_class(
992       (Nq.id == id_math and -1 or (Nq.xspc>=2 and 'alchar' or 'nox_alchar')), pm)
993    local g, _, kn, kp, kh = new_jfm_glue(pm.char_type, qclass, Np.class)
994    local k = g and (Nq.xspc>=2) and (Np.xspc%2==1) and combine_spc 'auto_xspc'
995       and get_kanjiskip_low(true, pm, kn, kp, kh)
996    return g, k
997 end
998 local function get_NB_skip()
999    local qm = Nq.met
1000    local pclass = fast_find_char_class(
1001       (Np.id == id_math and -1 or (Np.xspc%2==1 and 'alchar' or 'nox_alchar')), qm)
1002    local g, _, kn, kp, kh = new_jfm_glue(qm.char_type, Nq.class, pclass)
1003    local k = g and (Nq.xspc>=2) and (Np.xspc%2==1) and combine_spc 'auto_xspc'
1004       and get_kanjiskip_low(true, qm, kn, kp, kh)
1005    return g, k
1006 end
1007
1008 local function get_OA_skip(insert_ksp)
1009    local pm = Np.met
1010    local g, _, kn, kp, kh = new_jfm_glue(
1011       pm.char_type,
1012       fast_find_char_class(
1013         (((Nq.id==id_glue)or(Nq.id==id_kern)) and 'glue' or 'jcharbdd'), pm),
1014       Np.class)
1015    local k
1016    if insert_ksp then
1017       k = (combine_spc 'auto_kspc') and get_kanjiskip_low(true, pm, kn, kp, kh)
1018    end
1019    return g, k
1020 end
1021 local function get_OB_skip(insert_ksp)
1022    local qm = Nq.met
1023    local g, _, kn, kp, kh = new_jfm_glue(
1024       qm.char_type, Nq.class,
1025       fast_find_char_class(
1026         (((Np.id==id_glue)or(Np.id==id_kern)) and 'glue' or 'jcharbdd'), qm))
1027    local k
1028    if insert_ksp then
1029       k = (combine_spc 'auto_kspc') and get_kanjiskip_low(true, qm, kn, kp, kh)
1030    end
1031    return g, k
1032 end
1033
1034 -- (anything) .. jachar
1035 local function handle_np_jachar(mode)
1036    local qid = Nq.id
1037    if qid==id_jglyph or ((qid==id_pbox or qid==id_pbox_w) and Nq.met) then
1038       local g, k
1039       if non_ihb_flag then g, k = calc_ja_ja_glue() end -- M->K
1040       if not g then g = get_kanjiskip() end
1041       handle_penalty_normal(Nq.post, Np.pre, g);
1042       real_insert(g); real_insert(k)
1043    elseif Nq.met then  -- qid==id_hlist
1044       local g, k
1045       if non_ihb_flag then g, k = get_OA_skip(true) end -- O_A->K
1046       if not g then g = get_kanjiskip() end
1047       handle_penalty_normal(0, Np.pre, g); real_insert(g); real_insert(k)
1048    elseif Nq.pre then
1049       local g, k; if non_ihb_flag then g, k = get_NA_skip() end -- N_A->X
1050       if not g then g = get_xkanjiskip(Np) end
1051       handle_penalty_normal((qid==id_hlist and 0 or Nq.post), Np.pre, g);
1052       real_insert(g); real_insert(k)
1053    else
1054       local g = non_ihb_flag and (get_OA_skip()) -- O_A
1055       if qid==id_glue then handle_penalty_normal(0, Np.pre, g)
1056       elseif qid==id_kern then handle_penalty_suppress(0, Np.pre, g)
1057       else handle_penalty_always(0, Np.pre, g)
1058       end
1059       real_insert(g)
1060    end
1061    if mode and Np.kcat%2~=1 then
1062       widow_Np.first, widow_Bp, Bp = Np.first, Bp, widow_Bp
1063    end
1064 end
1065
1066
1067 -- jachar .. (anything)
1068 local function handle_nq_jachar()
1069     if Np.pre then
1070       local g, k; if non_ihb_flag then g, k =  get_NB_skip()end -- N_B->X
1071       if not g then g = get_xkanjiskip(Nq) end
1072       handle_penalty_normal(Nq.post, (Np.id==id_hlist and 0 or Np.pre), g);
1073       real_insert(g); real_insert(k)
1074    else
1075       local g =non_ihb_flag and  (get_OB_skip()) -- O_B
1076       if Np.id==id_glue then handle_penalty_normal(Nq.post, 0, g)
1077       elseif Np.id==id_kern then handle_penalty_suppress(Nq.post, 0, g)
1078       else handle_penalty_always(Nq.post, 0, g)
1079       end
1080       real_insert(g)
1081    end
1082 end
1083
1084 -- (anything) .. (和文文字で始まる hlist)
1085 local function handle_np_ja_hlist()
1086    local qid = Nq.id
1087    if qid==id_jglyph or ((qid==id_pbox or qid == id_pbox_w) and Nq.met) then
1088       local g = non_ihb_flag and get_OB_skip(true) or get_kanjiskip() -- O_B->K
1089       handle_penalty_normal(Nq.post, 0, g); real_insert(g)
1090    elseif Nq.met then  -- Nq.id==id_hlist
1091       local g = get_kanjiskip() -- K
1092       handle_penalty_suppress(0, 0, g); real_insert(g)
1093    elseif Nq.pre then
1094       local g = get_xkanjiskip(Np) -- X
1095       handle_penalty_suppress(0, 0, g); real_insert(g)
1096    end
1097 end
1098
1099 -- (和文文字で終わる hlist) .. (anything)
1100 local function handle_nq_ja_hlist()
1101    if Np.pre then
1102       local g = get_xkanjiskip(Nq) -- X
1103       handle_penalty_suppress(0, 0, g); real_insert(g)
1104    end
1105 end
1106
1107
1108 -- Nq が前側のクラスタとなることによる修正
1109 local adjust_nq
1110 do
1111    local adjust_nq_aux = {
1112       [id_glyph] = function() after_alchar(Nq) end, -- after_alchar(Nq)
1113       [id_hlist] = function() after_hlist(Nq) end,
1114       [id_pbox]  = function() after_hlist(Nq) end,
1115       [id_disc]  = function() after_hlist(Nq) end,
1116       [id_glue]  = function()
1117                       call_callback("luatexja.jfmglue.special_jaglue_after", Nq.nuc)
1118                    end,
1119       [id_pbox_w]= function()
1120                       local hh = call_callback("luatexja.jfmglue.whatsit_after", false, Nq, Np, head)
1121                       -- hh: new head of false (nott processed)
1122                       if hh then head = hh end
1123                    end,
1124    }
1125
1126    adjust_nq = function()
1127       local x = adjust_nq_aux[Nq.id]
1128       if x then x()  end
1129    end
1130 end
1131
1132
1133 -------------------- 開始・終了時の処理
1134 do
1135 local node_prev = node.direct.getprev
1136 -- リスト末尾の処理
1137 local function handle_list_tail(mode, last)
1138    adjust_nq()
1139    if mode then
1140       -- the current list is to be line-breaked.
1141       -- Insert \jcharwidowpenalty
1142       if widow_Np.first then handle_penalty_jwp() end
1143    else
1144       Np = Nq
1145       -- the current list is the contents of a hbox
1146       local npi, pm = Np.id, Np.met
1147       if npi == id_jglyph or (npi==id_pbox and pm) then
1148          local g = new_jfm_glue(pm.char_type, Np.class, fast_find_char_class('boxbdd', pm))
1149          if g then
1150             set_attr(g, attr_icflag, BOXBDD)
1151             head = insert_after(head, Np.last, g)
1152          end
1153       end
1154    end
1155 end
1156
1157 -- リスト先頭の処理
1158 local function handle_list_head(par_indented)
1159    local npi, pm = Np.id, Np.met
1160    if npi == id_jglyph or (npi==id_pbox and pm) then
1161       if non_ihb_flag then
1162          local g = new_jfm_glue(pm.char_type, fast_find_char_class(par_indented, pm), Np.class)
1163          if g then
1164             set_attr(g, attr_icflag, BOXBDD)
1165             if getid(g)==id_glue and #Bp==0 then
1166                local h = node_new(id_penalty, nil, Np.nuc)
1167                setpenalty(h, 10000); set_attr(h, attr_icflag, BOXBDD)
1168             end
1169             head = insert_before(head, Np.first, g)
1170          end
1171       end
1172    end
1173 end
1174
1175 -- initialize
1176 -- return value: (the initial cursor lp), (last node)
1177 local init_var
1178 do
1179    local id_local = node.id 'local_par'
1180    local KANJI_SKIP   = luatexja.icflag_table.KANJI_SKIP
1181    local XKANJI_SKIP   = luatexja.icflag_table.XKANJI_SKIP
1182    local KSK  = luatexja.stack_table_index.KSK
1183    local XSK  = luatexja.stack_table_index.XSK
1184    local dir_yoko = luatexja.dir_table.dir_yoko
1185    local dir_tate = luatexja.dir_table.dir_tate
1186    local attr_yablshift = luatexbase.attributes['ltj@yablshift']
1187    local attr_tablshift = luatexbase.attributes['ltj@tablshift']
1188    local table_pool = {
1189       {}, {}, {first=nil},
1190       { auto_kspc=nil, auto_xspc=nil, char=nil, class=nil,
1191         first=nil, id=nil, last=nil, met=nil, nuc=nil,
1192         post=nil, pre=nil, xspc=nil, gk=nil },
1193       { auto_kspc=nil, auto_xspc=nil, char=nil, class=nil,
1194         first=nil, id=nil, last=nil, met=nil, nuc=nil,
1195         post=nil, pre=nil, xspc=nil, gk=nil },
1196    }
1197    init_var = function (mode,dir)
1198       -- 1073741823: max_dimen
1199       Bp, widow_Bp, widow_Np, Np, Nq
1200          = table_pool[1], table_pool[2], table_pool[3], table_pool[4], table_pool[5]
1201       for i=1,5 do for j,_ in pairs(table_pool[i]) do table_pool[i][j]=nil end end
1202       table_current_stack = ltjs.table_current_stack
1203
1204       list_dir, tex_dir = (ltjs.list_dir or dir_yoko), (dir or 'TLT')
1205       local is_dir_tate = list_dir==dir_tate
1206       capsule_glyph = is_dir_tate and ltjw.capsule_glyph_tate or ltjw.capsule_glyph_yoko
1207       attr_ablshift = is_dir_tate and attr_tablshift or attr_yablshift
1208       local TEMP = node_new(id_glue)
1209       -- TEMP is a dummy node, which will be freed at the end of the callback.
1210       -- Without this node, set_attr(kanji_skip, ...) somehow creates an "orphaned"  attribute list.
1211       do
1212           kanji_skip, kanjiskip_jfm_flag = skip_table_to_glue(KSK)
1213           set_attr(kanji_skip, attr_icflag, KANJI_SKIP)
1214       end
1215       do
1216           xkanji_skip, xkanjiskip_jfm_flag = skip_table_to_glue(XSK)
1217           set_attr(xkanji_skip, attr_icflag, XKANJI_SKIP)
1218       end
1219       if mode then
1220          -- the current list is to be line-breaked:
1221          -- hbox from \parindent is skipped.
1222          local lp, par_indented, lpi, lps  = head, 'boxbdd', getid(head), getsubtype(head)
1223          while lp and
1224             ((lpi==id_whatsit and lps~=sid_user)
1225                or ((lpi==id_hlist) and (lps==3))
1226                or (lpi==id_local)) do
1227             if (lpi==id_hlist) and (lps==3) then
1228                Np.char, par_indented = 'parbdd', 'parbdd'
1229                Np.width = getwidth(lp)
1230             end
1231             lp=node_next(lp); lpi, lps = getid(lp), getsubtype(lp) end
1232          return lp, node_tail(head), par_indented, TEMP
1233       else
1234          return head, nil, 'boxbdd', TEMP
1235       end
1236    end
1237 end
1238
1239 -------------------- 外部から呼ばれる関数
1240
1241 local ensure_tex_attr = ltjb.ensure_tex_attr
1242 local tex_getattr = tex.getattribute
1243 -- main interface
1244 function luatexja.jfmglue.main(ahead, mode, dir)
1245    if not ahead then return ahead end
1246    head = ahead;
1247    local lp, last, par_indented, TEMP = init_var(mode,dir)
1248    lp = calc_np(last, lp)
1249    if Np then
1250       handle_list_head(par_indented)
1251       lp = calc_np(last,lp);
1252       while Np do
1253          adjust_nq();
1254          local pid, pm = Np.id, Np.met
1255          -- 挿入部
1256          if pid == id_jglyph then
1257             handle_np_jachar(mode)
1258          elseif pm then
1259             if pid==id_hlist then handle_np_ja_hlist()
1260             else handle_np_jachar() end
1261          elseif Nq.met then
1262             if Nq.id==id_hlist then handle_nq_ja_hlist()
1263             else handle_nq_jachar() end
1264          end
1265          lp = calc_np(last,lp)
1266       end
1267       handle_list_tail(mode, last)
1268    end
1269    -- adjust attr_icflag for avoiding error
1270    if tex_getattr(attr_icflag)~=0 then ensure_tex_attr(attr_icflag, 0) end
1271    node_free(kanji_skip);
1272    node_free(xkanji_skip); node_free(TEMP)
1273    return head
1274 end
1275 end
1276
1277 do
1278    local IHB  = luatexja.userid_table.IHB
1279    local BPAR = luatexja.userid_table.BPAR
1280    local BOXB = luatexja.userid_table.BOXB
1281    local node_prev = node.direct.getprev
1282    local node_write = node.direct.write
1283    local setvalue = node.direct.setdata
1284
1285    -- \inhibitglue, \disinhibitglue
1286    local function ihb_node(v)
1287       local tn = node_new(id_whatsit, sid_user)
1288       setfield(tn, 'user_id', IHB)
1289       setfield(tn, 'type', 100)
1290       setvalue(tn, v)
1291       node_write(tn)
1292    end
1293    function luatexja.jfmglue.create_inhibitglue_node()
1294       ihb_node(1)
1295    end
1296    function luatexja.jfmglue.create_disinhibitglue_node()
1297       ihb_node(0)
1298    end
1299
1300    -- Node for indicating beginning of a paragraph
1301    -- (for ltjsclasses)
1302    function luatexja.jfmglue.create_beginpar_node()
1303       local tn = node_new(id_whatsit, sid_user)
1304       setfield(tn, 'user_id', BPAR)
1305       setfield(tn, 'type', 100)
1306       setvalue(tn, 1)
1307       node_write(tn)
1308    end
1309
1310    -- Node for indicating a head/end of a box
1311    function luatexja.jfmglue.create_boxbdd_node()
1312       local tn = node_new(id_whatsit, sid_user)
1313       setfield(tn, 'user_id', BOXB)
1314       setfield(tn, 'type', 100)
1315       setvalue(tn, 1)
1316       node_write(tn)
1317    end
1318
1319    local function whatsit_callback(Np, lp, Nq)
1320       if Np and Np.nuc then return Np
1321       elseif Np and getfield(lp, 'user_id') == BPAR then
1322          Np.first = lp; Np.nuc = lp; Np.last = lp
1323          return Np
1324       elseif Np and getfield(lp, 'user_id') == BOXB then
1325          Np.first = lp; Np.nuc = lp; Np.last = lp
1326          if Nq then
1327             if Nq.met then
1328                Np.class = fast_find_char_class('boxbdd', Nq.met)
1329             end
1330             Np.met = Nq.met; Np.pre = 0; Np.post = 0; Np.xspc = 0
1331             Np.auto_xspc, Np.auto_kspc = 0, 0
1332          end
1333          return Np
1334       else
1335          return Np
1336       end
1337    end
1338
1339     local function whatsit_after_callback(s, Nq, Np, head)
1340        if not s and getfield(Nq.nuc, 'user_id') == BPAR then
1341          local x, y = node_prev(Nq.nuc), Nq.nuc
1342          Nq.first, Nq.nuc, Nq.last = x, x, x
1343          if Np then
1344             if Np.met then
1345                Nq.class = fast_find_char_class('parbdd', Np.met)
1346             end
1347             Nq.met = Np.met; Nq.pre = 0; Nq.post = 0; Nq.xspc = 0
1348             Nq.auto_xspc, Nq.auto_kspc = 0, 0
1349          end
1350          s = node_remove(head, y)
1351          node_free(y)
1352        elseif not s and getfield(Nq.nuc, 'user_id') == BOXB then
1353          local x, y = node_prev(Nq.nuc), Nq.nuc
1354          Nq.first, Nq.nuc, Nq.last = x, x, x
1355          if Np then
1356             if Np.met then
1357                Nq.class = fast_find_char_class('boxbdd', Np.met)
1358             end
1359             Nq.met = Np.met; Nq.pre = 0; Nq.post = 0; Nq.xspc = 0
1360             Nq.auto_xspc, Nq.auto_kspc = 0, 0
1361          end
1362          s = node_remove(head, y)
1363          node_free(y)
1364       end
1365       return s
1366    end
1367
1368    luatexbase.add_to_callback("luatexja.jfmglue.whatsit_getinfo", whatsit_callback,
1369                               "luatexja.beginpar.np_info", 1)
1370    luatexbase.add_to_callback("luatexja.jfmglue.whatsit_after", whatsit_after_callback,
1371                               "luatexja.beginpar.np_info_after", 1)
1372 end
1373
1374 do
1375    local node_prev = node.direct.getprev
1376    local node_write = node.direct.write
1377    local XKANJI_SKIP   = luatexja.icflag_table.XKANJI_SKIP
1378    local XKANJI_SKIP_JFM   = luatexja.icflag_table.XKANJI_SKIP_JFM
1379    local KANJI_SKIP   = luatexja.icflag_table.KANJI_SKIP
1380    local KANJI_SKIP_JFM   = luatexja.icflag_table.KANJI_SKIP_JFM
1381    local XSK  = luatexja.stack_table_index.XSK
1382    local KSK  = luatexja.stack_table_index.KSK
1383    local attr_yablshift = luatexbase.attributes['ltj@yablshift']
1384    local attr_tablshift = luatexbase.attributes['ltj@tablshift']
1385    local getcount, abs, scan_keyword = tex.getcount, math.abs, token.scan_keyword
1386    local getnest = tex.getnest
1387    local tex_getattr = tex.getattribute
1388    local get_current_jfont
1389    local cnt_stack = luatexbase.registernumber 'ltj@@stack'
1390    do
1391        local attr_curjfnt = luatexbase.attributes['ltj@curjfnt']
1392        local attr_curtfnt = luatexbase.attributes['ltj@curtfnt']
1393        local dir_tate = luatexja.dir_table.dir_tate
1394        local get_dir_count = ltjd.get_dir_count
1395        function get_current_jfont()
1396            return tex_getattr((get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)
1397        end
1398    end
1399    local get_stack_skip = ltjs.get_stack_skip
1400    -- \insertxkanjiskip
1401    -- SPECIAL_JAGLUE のノード:
1402    -- * (X)KANJI_SKIP(_JFM): その場で値が決まっている
1403    -- * PROCESSED_BEGIN_FLAG + (X)KANJI_SKIP: 段落終了時に決める
1404    local function insert_k_skip_common(ind, name, ica, icb)
1405        if abs(getnest().mode) ~= ltjs.hmode then return end
1406        local g = node_new(id_glue); set_attr(g, attr_icflag, SPECIAL_JAGLUE)
1407        local is_late = scan_keyword 'late'
1408        if not is_late then
1409            local st = get_stack_skip(ind, getcount(cnt_stack))
1410            if st[1]==1073741823 then
1411                local bk = ltjf_font_metric_table[get_current_jfont()][name]
1412                if bk then
1413                    setglue(g, bk[1] or 0, bk[2] or 0, bk[3] or 0, 0, 0)
1414                end
1415                set_attr(g, attr_yablshift, icb); node_write(g); return
1416            end
1417            setglue(g, st[1], st[2], st[3], st[4], st[5])
1418            set_attr(g, attr_yablshift, ica)
1419        else
1420            set_attr(g, attr_yablshift, PROCESSED_BEGIN_FLAG + ica)
1421            set_attr(g, attr_tablshift, get_current_jfont())
1422        end
1423        node_write(g)
1424    end
1425    function luatexja.jfmglue.insert_xk_skip()
1426        insert_k_skip_common(XSK, "xkanjiskip", XKANJI_SKIP, XKANJI_SKIP_JFM)
1427    end
1428    function luatexja.jfmglue.insert_k_skip()
1429        insert_k_skip_common(KSK, "kanjiskip", KANJI_SKIP, KANJI_SKIP_JFM)
1430    end
1431    -- callback
1432    local function special_jaglue(lx)
1433        local lxi = get_attr_icflag(lx)
1434        if lxi==SPECIAL_JAGLUE then
1435            non_ihb_flag = false; return false
1436        else
1437            return lx
1438        end
1439    end
1440    local function special_jaglue_after_inner(lx, lxi, lxi_jfm, kn, bk)
1441        local w, st, sh, sto, sho = getglue(kn)
1442        if w~=1073741823 then
1443            setglue(lx, w, st, sh, sto, sho); set_attr(lx, attr_icflag, lxi)
1444        else
1445            local m = ltjf_font_metric_table[get_attr(lx, attr_tablshift)]
1446            setglue(lx, bk[1], bk[2], bk[3], 0, 0)
1447            set_attr(lx, attr_icflag, lxi_jfm)
1448        end
1449    end
1450    local function special_jaglue_after(lx)
1451        if get_attr_icflag(lx)==SPECIAL_JAGLUE then
1452            lxi=get_attr(lx, attr_yablshift)
1453            if lxi>=PROCESSED_BEGIN_FLAG then
1454                lxi = lxi%PROCESSED_BEGIN_FLAG
1455                if lxi == KANJI_SKIP then
1456                    special_jaglue_after_inner(lx, lxi, KANJI_SKIP_JFM, kanji_skip,
1457                      ltjf_font_metric_table[get_attr(lx, attr_tablshift)].kanjiskip or null_skip_table)
1458                else --  lxi == XKANJI_SKIP
1459                    special_jaglue_after_inner(lx, lxi, XKANJI_SKIP_JFM, xkanji_skip,
1460                      ltjf_font_metric_table[get_attr(lx, attr_tablshift)].xkanjiskip or null_skip_table)
1461                end
1462            else
1463                set_attr(lx, attr_icflag, lxi)
1464            end
1465            Np.first = lx
1466            if node_prev(lx) then
1467                local lxp = node_prev(lx)
1468                if lxp and getid(lxp)==id_penalty and get_attr_icflag(lxp)==KINSOKU then
1469                    Bp[#Bp+1]=lxp
1470                end
1471            end
1472            non_ihb_flag = false; return false
1473        end
1474        return true
1475    end
1476    luatexbase.create_callback("luatexja.jfmglue.special_jaglue", "list",
1477                               special_jaglue)
1478    luatexbase.create_callback("luatexja.jfmglue.special_jaglue_after", "list",
1479                               special_jaglue_after)
1480 end
1481
1482
1483 luatexja.jfmglue.after_hlist = after_hlist
1484 luatexja.jfmglue.check_box_high = check_box_high