OSDN Git Service

use node.direct.{g/s}etdata
[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-18',
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 = luatexja.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 = luatexja.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    local getglue = luatexja.getglue
808    calc_ja_ja_aux = function (gb, ga, db, da)
809       if luatexja.jfmglue.diffmet_rule ~= math.two_pleft and diffmet_rule ~= math.two_pright
810           and luatexja.jfmglue.diffmet_rule ~= math.two_paverage then
811          db, da = 0, 1
812       end
813       if not gb then
814          if ga then gb = node_new(id_kern, 1); setkern(gb, 0)
815          else return nil end
816       elseif not ga then
817          ga = node_new(id_kern, 1); setkern(ga, 0)
818       end
819       local gbw, gaw, gbst, gast, gbsto, gasto, gbsh, gash, gbsho, gasho
820       if getid(gb)==id_glue then
821          gbw, gbst, gbsh, gbsto, gbsho = getglue(gb)
822       else
823          gbw = getkern(gb)
824       end
825       if getid(ga)==id_glue then
826          gaw, gast, gash, gasto, gasho = getglue(ga)
827       else
828          gaw = getkern(ga)
829       end
830       if not (gbst or gast) then -- 両方とも kern
831          setkern(gb, blend_diffmet(gbw, gaw, db, da))
832          node_free(ga); return gb
833       else
834          local gr = gb
835          if not gbst then gr = ga; node_free(gb) else node_free(ga) end
836          gbw = blend_diffmet(gbw or 0, gaw or 0, db, da) -- 結果の自然長
837          gbst, gbsto = blend_diffmet_inf(gbst, gast, gbsto, gasto, db, da) -- 伸び
838          gbsh, gbsho = blend_diffmet_inf(-(gbsh or 0), -(gash or 0), gbsho, gasho, db, da) -- -(縮み)
839          setglue(gr, gbw, gbst, -gbsh, gbsto, gbsho)
840          return gr
841       end
842    end
843 end
844
845 local null_skip_table = {0, 0, 0}
846 -- get kanjiskip
847 local get_kanjiskip, kanjiskip_jfm_flag
848 local get_kanjiskip_low
849 local calc_ja_ja_glue
850 do
851    local KANJI_SKIP   = luatexja.icflag_table.KANJI_SKIP
852    local KANJI_SKIP_JFM   = luatexja.icflag_table.KANJI_SKIP_JFM
853
854    get_kanjiskip_low = function(flag, qm, bn, bp, bh)
855    -- flag = false: kanjiskip そのもの(パラメータ or JFM)
856    --               ノード kanji_skip のコピーで良い場合は nil が帰る
857    -- flag = true: JFM グルーに付随する kanjiskip 自然長/伸び/縮み分
858       if qm.with_kanjiskip and (bn or bp or bh) then
859          if kanjiskip_jfm_flag then
860             local g = node_new(id_glue);
861             local bk = qm.kanjiskip or null_skip_table
862             setglue(g, bn and (bn*bk[1]) or 0,
863                        bp and (bp*bk[2]) or 0,
864                        bh and (bh*bk[3]) or 0, 0, 0)
865             set_attr(g, attr_icflag, KANJI_SKIP_JFM)
866             return g
867          elseif flag then
868             local g = node_new(id_glue)
869             local st = bp and (bp*getfield(kanji_skip, 'stretch')) or 0
870             local sh = bh and (bh*getfield(kanji_skip, 'shrink')) or 0
871             setglue(g,
872                bn and (bn*getwidth(kanji_skip)) or 0,
873                st, sh,
874                (st==0) and 0 or getfield(kanji_skip, 'stretch_order'),
875                (sh==0) and 0 or getfield(kanji_skip, 'shrink_order'))
876             set_attr(g, attr_icflag, KANJI_SKIP_JFM)
877             return g
878          end
879       end
880    end
881
882    get_kanjiskip = function()
883       if Np.auto_kspc==0 or Nq.auto_kspc==0 then return nil
884       elseif Np.auto_kspc or Nq.auto_kspc then
885          local pm, qm = Np.met, Nq.met
886          if (pm.char_type==qm.char_type) and (qm.var==pm.var) then
887              return get_kanjiskip_low(false, qm, 1, 1, 1) or node_copy(kanji_skip)
888          else
889             local gb = get_kanjiskip_low(false, qm, 1, 1, 1)
890             if gb then
891                return calc_ja_ja_aux(gb,
892                  get_kanjiskip_low(false, pm, 1, 1, 1) or node_copy(kanji_skip), 0, 1)
893             else
894                local ga = get_kanjiskip_low(false, pm, 1, 1, 1)
895                return (ga and calc_ja_ja_aux(node_copy(kanji_skip), ga, 0, 1))
896                  or node_copy(kanji_skip)
897             end
898          end
899       else
900          local g = node_new(id_glue)
901          set_attr(g, attr_icflag, kanjiskip_jfm_flag and KANJI_SKIP_JFM or KANJI_SKIP)
902          return g
903       end
904    end
905
906    calc_ja_ja_glue = function ()
907       local qm, pm = Nq.met, Np.met
908       local qmc, pmc = qm.char_type, pm.char_type
909       if (qmc==pmc) and (qm.var==pm.var) then
910          local g, _, kn, kp, kh = new_jfm_glue(qmc, Nq.class, Np.class)
911          return g, (Np.auto_kspc or Nq.auto_kspc) and get_kanjiskip_low(true, qm, kn, kp, kh)
912       else
913          local npn, nqn = Np.nuc, Nq.nuc
914          local gb, db, bn, bp, bh
915             = new_jfm_glue(qmc, Nq.class,
916                            slow_find_char_class(Np.char,
917                                                 qm, getchar(npn)))
918          local ga, da, an, ap, ah
919             = new_jfm_glue(pmc,
920                            slow_find_char_class(Nq.char,
921                                                 pm, getchar(nqn)),
922                            Np.class)
923          local g = calc_ja_ja_aux(gb, ga, db, da)
924          local k
925          gb = get_kanjiskip_low(true, qm, bn, bp, bh)
926          ga = get_kanjiskip_low(true, pm, an, ap, ah)
927          k = calc_ja_ja_aux(gb, ga, db, da)
928          return g, k
929       end
930    end
931 end
932
933 -------------------- 和欧文間空白量の決定
934
935 -- get xkanjiskip
936 local get_xkanjiskip, xkanjiskip_jfm_flag
937 local get_xkanjiskip_normal, get_xkanjiskip_jfm
938 local get_xkanjiskip_low
939 do
940    local XKANJI_SKIP   = luatexja.icflag_table.XKANJI_SKIP
941    local XKANJI_SKIP_JFM   = luatexja.icflag_table.XKANJI_SKIP_JFM
942
943    get_xkanjiskip_low = function(flag, qm, bn, bp, bh)
944       if flag or (qm.with_kanjiskip and (bn or bp or bh)) then
945          if xkanjiskip_jfm_flag then
946             local g = node_new(id_glue);
947             local bk = qm.xkanjiskip or null_skip_table
948             setglue(g, bn and bk[1] or 0,
949                        bp and bk[2] or 0,
950                        bh and bk[3] or 0, 0, 0)
951             set_attr(g, attr_icflag, XKANJI_SKIP_JFM)
952             return g
953          elseif flag then
954             return node_copy(xkanji_skip)
955          else
956             local g = node_new(id_glue)
957             local w, st, sh, sto, sho = getglue(xkanji_skip)
958             setglue(g,
959                bn and (bn*w) or 0,
960                bp and (bp*st) or 0,
961                bh and (bh*sh) or 0,
962                bp and sto or 0,
963                bh and sho or 0)
964             set_attr(g, attr_icflag, XKANJI_SKIP_JFM)
965             return g
966          end
967       end
968    end
969
970    get_xkanjiskip = function(Nn)
971       if Np.auto_xspc==0 or Nq.auto_xspc==0 then
972         return nil
973       elseif (Nq.xspc>=2) and (Np.xspc%2==1) and (Nq.auto_xspc or Np.auto_xspc) then
974          return get_xkanjiskip_low(true, Nn.met, 1, 1, 1)
975       else
976          local g = node_new(id_glue)
977          set_attr(g, attr_icflag, xkanjiskip_jfm_flag and XKANJI_SKIP_JFM or XKANJI_SKIP)
978          return g
979       end
980    end
981 end
982
983 -------------------- 隣接した「塊」間の処理
984
985 local function combine_spc(name)
986    return (Np[name] or Nq[name]) and ((Np[name]~=0) and (Nq[name]~=0))
987 end
988
989 -- NA, NB: alchar or math
990 local function get_NA_skip()
991    local pm = Np.met
992    local qclass = fast_find_char_class(
993       (Nq.id == id_math and -1 or (Nq.xspc>=2 and 'alchar' or 'nox_alchar')), pm)
994    local g, _, kn, kp, kh = new_jfm_glue(pm.char_type, qclass, Np.class)
995    local k = g and (Nq.xspc>=2) and (Np.xspc%2==1) and combine_spc 'auto_xspc'
996       and get_kanjiskip_low(true, pm, kn, kp, kh)
997    return g, k
998 end
999 local function get_NB_skip()
1000    local qm = Nq.met
1001    local pclass = fast_find_char_class(
1002       (Np.id == id_math and -1 or (Np.xspc%2==1 and 'alchar' or 'nox_alchar')), qm)
1003    local g, _, kn, kp, kh = new_jfm_glue(qm.char_type, Nq.class, pclass)
1004    local k = g and (Nq.xspc>=2) and (Np.xspc%2==1) and combine_spc 'auto_xspc'
1005       and get_kanjiskip_low(true, qm, kn, kp, kh)
1006    return g, k
1007 end
1008
1009 local function get_OA_skip(insert_ksp)
1010    local pm = Np.met
1011    local g, _, kn, kp, kh = new_jfm_glue(
1012       pm.char_type,
1013       fast_find_char_class(
1014         (((Nq.id==id_glue)or(Nq.id==id_kern)) and 'glue' or 'jcharbdd'), pm),
1015       Np.class)
1016    local k
1017    if insert_ksp then
1018       k = (combine_spc 'auto_kspc') and get_kanjiskip_low(true, pm, kn, kp, kh)
1019    end
1020    return g, k
1021 end
1022 local function get_OB_skip(insert_ksp)
1023    local qm = Nq.met
1024    local g, _, kn, kp, kh = new_jfm_glue(
1025       qm.char_type, Nq.class,
1026       fast_find_char_class(
1027         (((Np.id==id_glue)or(Np.id==id_kern)) and 'glue' or 'jcharbdd'), qm))
1028    local k
1029    if insert_ksp then
1030       k = (combine_spc 'auto_kspc') and get_kanjiskip_low(true, qm, kn, kp, kh)
1031    end
1032    return g, k
1033 end
1034
1035 -- (anything) .. jachar
1036 local function handle_np_jachar(mode)
1037    local qid = Nq.id
1038    if qid==id_jglyph or ((qid==id_pbox or qid==id_pbox_w) and Nq.met) then
1039       local g, k
1040       if non_ihb_flag then g, k = calc_ja_ja_glue() end -- M->K
1041       if not g then g = get_kanjiskip() end
1042       handle_penalty_normal(Nq.post, Np.pre, g);
1043       real_insert(g); real_insert(k)
1044    elseif Nq.met then  -- qid==id_hlist
1045       local g, k
1046       if non_ihb_flag then g, k = get_OA_skip(true) end -- O_A->K
1047       if not g then g = get_kanjiskip() end
1048       handle_penalty_normal(0, Np.pre, g); real_insert(g); real_insert(k)
1049    elseif Nq.pre then
1050       local g, k; if non_ihb_flag then g, k = get_NA_skip() end -- N_A->X
1051       if not g then g = get_xkanjiskip(Np) end
1052       handle_penalty_normal((qid==id_hlist and 0 or Nq.post), Np.pre, g);
1053       real_insert(g); real_insert(k)
1054    else
1055       local g = non_ihb_flag and (get_OA_skip()) -- O_A
1056       if qid==id_glue then handle_penalty_normal(0, Np.pre, g)
1057       elseif qid==id_kern then handle_penalty_suppress(0, Np.pre, g)
1058       else handle_penalty_always(0, Np.pre, g)
1059       end
1060       real_insert(g)
1061    end
1062    if mode and Np.kcat%2~=1 then
1063       widow_Np.first, widow_Bp, Bp = Np.first, Bp, widow_Bp
1064    end
1065 end
1066
1067
1068 -- jachar .. (anything)
1069 local function handle_nq_jachar()
1070     if Np.pre then
1071       local g, k; if non_ihb_flag then g, k =  get_NB_skip()end -- N_B->X
1072       if not g then g = get_xkanjiskip(Nq) end
1073       handle_penalty_normal(Nq.post, (Np.id==id_hlist and 0 or Np.pre), g);
1074       real_insert(g); real_insert(k)
1075    else
1076       local g =non_ihb_flag and  (get_OB_skip()) -- O_B
1077       if Np.id==id_glue then handle_penalty_normal(Nq.post, 0, g)
1078       elseif Np.id==id_kern then handle_penalty_suppress(Nq.post, 0, g)
1079       else handle_penalty_always(Nq.post, 0, g)
1080       end
1081       real_insert(g)
1082    end
1083 end
1084
1085 -- (anything) .. (和文文字で始まる hlist)
1086 local function handle_np_ja_hlist()
1087    local qid = Nq.id
1088    if qid==id_jglyph or ((qid==id_pbox or qid == id_pbox_w) and Nq.met) then
1089       local g = non_ihb_flag and get_OB_skip(true) or get_kanjiskip() -- O_B->K
1090       handle_penalty_normal(Nq.post, 0, g); real_insert(g)
1091    elseif Nq.met then  -- Nq.id==id_hlist
1092       local g = get_kanjiskip() -- K
1093       handle_penalty_suppress(0, 0, g); real_insert(g)
1094    elseif Nq.pre then
1095       local g = get_xkanjiskip(Np) -- X
1096       handle_penalty_suppress(0, 0, g); real_insert(g)
1097    end
1098 end
1099
1100 -- (和文文字で終わる hlist) .. (anything)
1101 local function handle_nq_ja_hlist()
1102    if Np.pre then
1103       local g = get_xkanjiskip(Nq) -- X
1104       handle_penalty_suppress(0, 0, g); real_insert(g)
1105    end
1106 end
1107
1108
1109 -- Nq が前側のクラスタとなることによる修正
1110 local adjust_nq
1111 do
1112    local adjust_nq_aux = {
1113       [id_glyph] = function() after_alchar(Nq) end, -- after_alchar(Nq)
1114       [id_hlist] = function() after_hlist(Nq) end,
1115       [id_pbox]  = function() after_hlist(Nq) end,
1116       [id_disc]  = function() after_hlist(Nq) end,
1117       [id_glue]  = function()
1118                       call_callback("luatexja.jfmglue.special_jaglue_after", Nq.nuc)
1119                    end,
1120       [id_pbox_w]= function()
1121                       local hh = call_callback("luatexja.jfmglue.whatsit_after", false, Nq, Np, head)
1122                       -- hh: new head of false (nott processed)
1123                       if hh then head = hh end
1124                    end,
1125    }
1126
1127    adjust_nq = function()
1128       local x = adjust_nq_aux[Nq.id]
1129       if x then x()  end
1130    end
1131 end
1132
1133
1134 -------------------- 開始・終了時の処理
1135 do
1136 local node_prev = node.direct.getprev
1137 -- リスト末尾の処理
1138 local function handle_list_tail(mode, last)
1139    adjust_nq()
1140    if mode then
1141       -- the current list is to be line-breaked.
1142       -- Insert \jcharwidowpenalty
1143       if widow_Np.first then handle_penalty_jwp() end
1144    else
1145       Np = Nq
1146       -- the current list is the contents of a hbox
1147       local npi, pm = Np.id, Np.met
1148       if npi == id_jglyph or (npi==id_pbox and pm) then
1149          local g = new_jfm_glue(pm.char_type, Np.class, fast_find_char_class('boxbdd', pm))
1150          if g then
1151             set_attr(g, attr_icflag, BOXBDD)
1152             head = insert_after(head, Np.last, g)
1153          end
1154       end
1155    end
1156 end
1157
1158 -- リスト先頭の処理
1159 local function handle_list_head(par_indented)
1160    local npi, pm = Np.id, Np.met
1161    if npi == id_jglyph or (npi==id_pbox and pm) then
1162       if non_ihb_flag then
1163          local g = new_jfm_glue(pm.char_type, fast_find_char_class(par_indented, pm), Np.class)
1164          if g then
1165             set_attr(g, attr_icflag, BOXBDD)
1166             if getid(g)==id_glue and #Bp==0 then
1167                local h = node_new(id_penalty, nil, Np.nuc)
1168                setpenalty(h, 10000); set_attr(h, attr_icflag, BOXBDD)
1169             end
1170             head = insert_before(head, Np.first, g)
1171          end
1172       end
1173    end
1174 end
1175
1176 -- initialize
1177 -- return value: (the initial cursor lp), (last node)
1178 local init_var
1179 do
1180    local id_local = node.id 'local_par'
1181    local KANJI_SKIP   = luatexja.icflag_table.KANJI_SKIP
1182    local XKANJI_SKIP   = luatexja.icflag_table.XKANJI_SKIP
1183    local KSK  = luatexja.stack_table_index.KSK
1184    local XSK  = luatexja.stack_table_index.XSK
1185    local dir_yoko = luatexja.dir_table.dir_yoko
1186    local dir_tate = luatexja.dir_table.dir_tate
1187    local attr_yablshift = luatexbase.attributes['ltj@yablshift']
1188    local attr_tablshift = luatexbase.attributes['ltj@tablshift']
1189    local table_pool = {
1190       {}, {}, {first=nil},
1191       { auto_kspc=nil, auto_xspc=nil, char=nil, class=nil,
1192         first=nil, id=nil, last=nil, met=nil, nuc=nil,
1193         post=nil, pre=nil, xspc=nil, gk=nil },
1194       { auto_kspc=nil, auto_xspc=nil, char=nil, class=nil,
1195         first=nil, id=nil, last=nil, met=nil, nuc=nil,
1196         post=nil, pre=nil, xspc=nil, gk=nil },
1197    }
1198    init_var = function (mode,dir)
1199       -- 1073741823: max_dimen
1200       Bp, widow_Bp, widow_Np, Np, Nq
1201          = table_pool[1], table_pool[2], table_pool[3], table_pool[4], table_pool[5]
1202       for i=1,5 do for j,_ in pairs(table_pool[i]) do table_pool[i][j]=nil end end
1203       table_current_stack = ltjs.table_current_stack
1204
1205       list_dir, tex_dir = (ltjs.list_dir or dir_yoko), (dir or 'TLT')
1206       local is_dir_tate = list_dir==dir_tate
1207       capsule_glyph = is_dir_tate and ltjw.capsule_glyph_tate or ltjw.capsule_glyph_yoko
1208       attr_ablshift = is_dir_tate and attr_tablshift or attr_yablshift
1209       local TEMP = node_new(id_glue)
1210       -- TEMP is a dummy node, which will be freed at the end of the callback.
1211       -- Without this node, set_attr(kanji_skip, ...) somehow creates an "orphaned"  attribute list.
1212       do
1213           kanji_skip, kanjiskip_jfm_flag = skip_table_to_glue(KSK)
1214           set_attr(kanji_skip, attr_icflag, KANJI_SKIP)
1215       end
1216       do
1217           xkanji_skip, xkanjiskip_jfm_flag = skip_table_to_glue(XSK)
1218           set_attr(xkanji_skip, attr_icflag, XKANJI_SKIP)
1219       end
1220       if mode then
1221          -- the current list is to be line-breaked:
1222          -- hbox from \parindent is skipped.
1223          local lp, par_indented, lpi, lps  = head, 'boxbdd', getid(head), getsubtype(head)
1224          while lp and
1225             ((lpi==id_whatsit and lps~=sid_user)
1226                or ((lpi==id_hlist) and (lps==3))
1227                or (lpi==id_local)) do
1228             if (lpi==id_hlist) and (lps==3) then
1229                Np.char, par_indented = 'parbdd', 'parbdd'
1230                Np.width = getwidth(lp)
1231             end
1232             lp=node_next(lp); lpi, lps = getid(lp), getsubtype(lp) end
1233          return lp, node_tail(head), par_indented, TEMP
1234       else
1235          return head, nil, 'boxbdd', TEMP
1236       end
1237    end
1238 end
1239
1240 -------------------- 外部から呼ばれる関数
1241
1242 local ensure_tex_attr = ltjb.ensure_tex_attr
1243 local tex_getattr = tex.getattribute
1244 -- main interface
1245 function luatexja.jfmglue.main(ahead, mode, dir)
1246    if not ahead then return ahead end
1247    head = ahead;
1248    local lp, last, par_indented, TEMP = init_var(mode,dir)
1249    lp = calc_np(last, lp)
1250    if Np then
1251       handle_list_head(par_indented)
1252       lp = calc_np(last,lp);
1253       while Np do
1254          adjust_nq();
1255          local pid, pm = Np.id, Np.met
1256          -- 挿入部
1257          if pid == id_jglyph then
1258             handle_np_jachar(mode)
1259          elseif pm then
1260             if pid==id_hlist then handle_np_ja_hlist()
1261             else handle_np_jachar() end
1262          elseif Nq.met then
1263             if Nq.id==id_hlist then handle_nq_ja_hlist()
1264             else handle_nq_jachar() end
1265          end
1266          lp = calc_np(last,lp)
1267       end
1268       handle_list_tail(mode, last)
1269    end
1270    -- adjust attr_icflag for avoiding error
1271    if tex_getattr(attr_icflag)~=0 then ensure_tex_attr(attr_icflag, 0) end
1272    node_free(kanji_skip);
1273    node_free(xkanji_skip); node_free(TEMP)
1274    return head
1275 end
1276 end
1277
1278 do
1279    local IHB  = luatexja.userid_table.IHB
1280    local BPAR = luatexja.userid_table.BPAR
1281    local BOXB = luatexja.userid_table.BOXB
1282    local node_prev = node.direct.getprev
1283    local node_write = node.direct.write
1284    local setvalue = node.direct.setdata
1285
1286    -- \inhibitglue, \disinhibitglue
1287    local function ihb_node(v)
1288       local tn = node_new(id_whatsit, sid_user)
1289       setfield(tn, 'user_id', IHB)
1290       setfield(tn, 'type', 100)
1291       setvalue(tn, v)
1292       node_write(tn)
1293    end
1294    function luatexja.jfmglue.create_inhibitglue_node()
1295       ihb_node(1)
1296    end
1297    function luatexja.jfmglue.create_disinhibitglue_node()
1298       ihb_node(0)
1299    end
1300
1301    -- Node for indicating beginning of a paragraph
1302    -- (for ltjsclasses)
1303    function luatexja.jfmglue.create_beginpar_node()
1304       local tn = node_new(id_whatsit, sid_user)
1305       setfield(tn, 'user_id', BPAR)
1306       setfield(tn, 'type', 100)
1307       setvalue(tn, 1)
1308       node_write(tn)
1309    end
1310
1311    -- Node for indicating a head/end of a box
1312    function luatexja.jfmglue.create_boxbdd_node()
1313       local tn = node_new(id_whatsit, sid_user)
1314       setfield(tn, 'user_id', BOXB)
1315       setfield(tn, 'type', 100)
1316       setvalue(tn, 1)
1317       node_write(tn)
1318    end
1319
1320    local function whatsit_callback(Np, lp, Nq)
1321       if Np and Np.nuc then return Np
1322       elseif Np and getfield(lp, 'user_id') == BPAR then
1323          Np.first = lp; Np.nuc = lp; Np.last = lp
1324          return Np
1325       elseif Np and getfield(lp, 'user_id') == BOXB then
1326          Np.first = lp; Np.nuc = lp; Np.last = lp
1327          if Nq then
1328             if Nq.met then
1329                Np.class = fast_find_char_class('boxbdd', Nq.met)
1330             end
1331             Np.met = Nq.met; Np.pre = 0; Np.post = 0; Np.xspc = 0
1332             Np.auto_xspc, Np.auto_kspc = 0, 0
1333          end
1334          return Np
1335       else
1336          return Np
1337       end
1338    end
1339
1340     local function whatsit_after_callback(s, Nq, Np, head)
1341        if not s and getfield(Nq.nuc, 'user_id') == BPAR then
1342          local x, y = node_prev(Nq.nuc), Nq.nuc
1343          Nq.first, Nq.nuc, Nq.last = x, x, x
1344          if Np then
1345             if Np.met then
1346                Nq.class = fast_find_char_class('parbdd', Np.met)
1347             end
1348             Nq.met = Np.met; Nq.pre = 0; Nq.post = 0; Nq.xspc = 0
1349             Nq.auto_xspc, Nq.auto_kspc = 0, 0
1350          end
1351          s = node_remove(head, y)
1352          node_free(y)
1353        elseif not s and getfield(Nq.nuc, 'user_id') == BOXB then
1354          local x, y = node_prev(Nq.nuc), Nq.nuc
1355          Nq.first, Nq.nuc, Nq.last = x, x, x
1356          if Np then
1357             if Np.met then
1358                Nq.class = fast_find_char_class('boxbdd', Np.met)
1359             end
1360             Nq.met = Np.met; Nq.pre = 0; Nq.post = 0; Nq.xspc = 0
1361             Nq.auto_xspc, Nq.auto_kspc = 0, 0
1362          end
1363          s = node_remove(head, y)
1364          node_free(y)
1365       end
1366       return s
1367    end
1368
1369    luatexbase.add_to_callback("luatexja.jfmglue.whatsit_getinfo", whatsit_callback,
1370                               "luatexja.beginpar.np_info", 1)
1371    luatexbase.add_to_callback("luatexja.jfmglue.whatsit_after", whatsit_after_callback,
1372                               "luatexja.beginpar.np_info_after", 1)
1373 end
1374
1375 do
1376    local node_prev = node.direct.getprev
1377    local node_write = node.direct.write
1378    local XKANJI_SKIP   = luatexja.icflag_table.XKANJI_SKIP
1379    local XKANJI_SKIP_JFM   = luatexja.icflag_table.XKANJI_SKIP_JFM
1380    local KANJI_SKIP   = luatexja.icflag_table.KANJI_SKIP
1381    local KANJI_SKIP_JFM   = luatexja.icflag_table.KANJI_SKIP_JFM
1382    local XSK  = luatexja.stack_table_index.XSK
1383    local KSK  = luatexja.stack_table_index.KSK
1384    local attr_yablshift = luatexbase.attributes['ltj@yablshift']
1385    local attr_tablshift = luatexbase.attributes['ltj@tablshift']
1386    local getcount, abs, scan_keyword = tex.getcount, math.abs, token.scan_keyword
1387    local getnest = tex.getnest
1388    local tex_getattr = tex.getattribute
1389    local get_current_jfont
1390    local cnt_stack = luatexbase.registernumber 'ltj@@stack'
1391    do
1392        local attr_curjfnt = luatexbase.attributes['ltj@curjfnt']
1393        local attr_curtfnt = luatexbase.attributes['ltj@curtfnt']
1394        local dir_tate = luatexja.dir_table.dir_tate
1395        local get_dir_count = ltjd.get_dir_count
1396        function get_current_jfont()
1397            return tex_getattr((get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)
1398        end
1399    end
1400    local get_stack_skip = ltjs.get_stack_skip
1401    -- \insertxkanjiskip
1402    -- SPECIAL_JAGLUE のノード:
1403    -- * (X)KANJI_SKIP(_JFM): その場で値が決まっている
1404    -- * PROCESSED_BEGIN_FLAG + (X)KANJI_SKIP: 段落終了時に決める
1405    local function insert_k_skip_common(ind, name, ica, icb)
1406        if abs(getnest().mode) ~= ltjs.hmode then return end
1407        local g = node_new(id_glue); set_attr(g, attr_icflag, SPECIAL_JAGLUE)
1408        local is_late = scan_keyword 'late'
1409        if not is_late then
1410            local st = get_stack_skip(ind, getcount(cnt_stack))
1411            if st[1]==1073741823 then
1412                local bk = ltjf_font_metric_table[get_current_jfont()][name]
1413                if bk then
1414                    setglue(g, bk[1] or 0, bk[2] or 0, bk[3] or 0, 0, 0)
1415                end
1416                set_attr(g, attr_yablshift, icb); node_write(g); return
1417            end
1418            setglue(g, st[1], st[2], st[3], st[4], st[5])
1419            set_attr(g, attr_yablshift, ica)
1420        else
1421            set_attr(g, attr_yablshift, PROCESSED_BEGIN_FLAG + ica)
1422            set_attr(g, attr_tablshift, get_current_jfont())
1423        end
1424        node_write(g)
1425    end
1426    function luatexja.jfmglue.insert_xk_skip()
1427        insert_k_skip_common(XSK, "xkanjiskip", XKANJI_SKIP, XKANJI_SKIP_JFM)
1428    end
1429    function luatexja.jfmglue.insert_k_skip()
1430        insert_k_skip_common(KSK, "kanjiskip", KANJI_SKIP, KANJI_SKIP_JFM)
1431    end
1432    -- callback
1433    local function special_jaglue(lx)
1434        local lxi = get_attr_icflag(lx)
1435        if lxi==SPECIAL_JAGLUE then
1436            non_ihb_flag = false; return false
1437        else
1438            return lx
1439        end
1440    end
1441    local function special_jaglue_after_inner(lx, lxi, lxi_jfm, kn, bk)
1442        local w, st, sh, sto, sho = getglue(kn)
1443        if w~=1073741823 then
1444            setglue(lx, w, st, sh, sto, sho); set_attr(lx, attr_icflag, lxi)
1445        else
1446            local m = ltjf_font_metric_table[get_attr(lx, attr_tablshift)]
1447            setglue(lx, bk[1], bk[2], bk[3], 0, 0)
1448            set_attr(lx, attr_icflag, lxi_jfm)
1449        end
1450    end
1451    local function special_jaglue_after(lx)
1452        if get_attr_icflag(lx)==SPECIAL_JAGLUE then
1453            lxi=get_attr(lx, attr_yablshift)
1454            if lxi>=PROCESSED_BEGIN_FLAG then
1455                lxi = lxi%PROCESSED_BEGIN_FLAG
1456                if lxi == KANJI_SKIP then
1457                    special_jaglue_after_inner(lx, lxi, KANJI_SKIP_JFM, kanji_skip,
1458                      ltjf_font_metric_table[get_attr(lx, attr_tablshift)].kanjiskip or null_skip_table)
1459                else --  lxi == XKANJI_SKIP
1460                    special_jaglue_after_inner(lx, lxi, XKANJI_SKIP_JFM, xkanji_skip,
1461                      ltjf_font_metric_table[get_attr(lx, attr_tablshift)].xkanjiskip or null_skip_table)
1462                end
1463            else
1464                set_attr(lx, attr_icflag, lxi)
1465            end
1466            Np.first = lx
1467            if node_prev(lx) then
1468                local lxp = node_prev(lx)
1469                if lxp and getid(lxp)==id_penalty and get_attr_icflag(lxp)==KINSOKU then
1470                    Bp[#Bp+1]=lxp
1471                end
1472            end
1473            non_ihb_flag = false; return false
1474        end
1475        return true
1476    end
1477    luatexbase.create_callback("luatexja.jfmglue.special_jaglue", "list",
1478                               special_jaglue)
1479    luatexbase.create_callback("luatexja.jfmglue.special_jaglue_after", "list",
1480                               special_jaglue_after)
1481 end
1482
1483
1484 luatexja.jfmglue.after_hlist = after_hlist
1485 luatexja.jfmglue.check_box_high = check_box_high