OSDN Git Service

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