OSDN Git Service

change the argument of getcount to the register number
[luatex-ja/luatexja.git] / src / ltj-ruby.lua
1 --
2 -- ltj-ruby.lua
3 --
4 luatexbase.provides_module({
5   name = 'luatexja.ruby',
6   date = '2022-08-14',
7   description = 'Ruby annotation',
8 })
9 luatexja.ruby = {}
10 luatexja.load_module 'stack';     local ltjs = luatexja.stack
11 luatexja.load_module 'base';      local ltjb = luatexja.base
12
13 local to_node =  node.direct.tonode
14 local to_direct =  node.direct.todirect
15
16 local getfield =  node.direct.getfield
17 local getid =  node.direct.getid
18 local getfont =  node.direct.getfont
19 local getlist =  node.direct.getlist
20 local getchar =  node.direct.getchar
21 local getsubtype =  node.direct.getsubtype
22 local getkern = node.direct.getkern
23 local getwidth =  node.direct.getwidth
24 local getheight = node.direct.getheight
25 local getdepth = node.direct.getdepth
26 local getwhd = node.direct.getwhd
27 local setfield =  node.direct.setfield
28 local setglue = luatexja.setglue
29 local setkern = node.direct.setkern
30 local setnext = node.direct.setnext
31 local setshift = node.direct.setshift
32 local setwidth = node.direct.setwidth
33 local setheight = node.direct.setheight
34 local setdepth = node.direct.setdepth
35 local setwhd = node.direct.setwhd
36 local setlist = node.direct.setlist
37
38 local node_new = node.direct.new
39 local node_remove = node.direct.remove
40 local node_next =  node.direct.getnext
41 local node_copy, node_tail = node.direct.copy, node.direct.tail
42 local node_free = node.direct.flush_node or node.direct.free
43 local get_attr, set_attr = node.direct.get_attribute, node.direct.set_attribute
44 local insert_before, insert_after = node.direct.insert_before, node.direct.insert_after
45 local hpack = node.direct.hpack
46
47 local id_hlist  = node.id 'hlist'
48 local id_vlist  = node.id 'vlist'
49 local id_rule   = node.id 'rule'
50 local id_whatsit= node.id 'whatsit'
51 local id_glue   = node.id 'glue'
52 local id_kern   = node.id 'kern'
53 local id_penalty= node.id 'penalty'
54 local sid_user  = node.subtype 'user_defined'
55 local ltjs_get_stack_table = luatexja.stack.get_stack_table
56 local id_pbox_w = 258 -- cluster which consists of a whatsit
57
58 local attr_icflag = luatexbase.attributes['ltj@icflag']
59 -- ルビ処理用の attribute は他のやつの流用なので注意!
60 -- 進入許容量 (sp)
61 local attr_ruby_id = luatexbase.attributes['ltj@kcat4'] -- uniq id
62 local attr_ruby = luatexbase.attributes['ltj@rubyattr']
63 -- ルビ内部処理用,以下のようにノードによって使われ方が異なる
64 -- * (whatsit) では JAglue 処理時に,
65 --     「2つ前のクラスタもルビ」 ==> そのルビクラスタの id
66 --   otherwise ==> unset
67 -- * (whatsit).value node ではルビ全角の値(sp単位)
68 -- * 行分割で whatsit の前後に並ぶノードでは,「何番目のルビ関連ノード」か
69 -- * (whatsit).value に続く整形済み vbox たちでは post_intrusion の値
70 local attr_ruby_post_jfmgk = luatexbase.attributes['ltj@kcat3']
71 -- JAglue 処理時に,2つ前のクラスタもルビであれば,そのルビが直後の和文処理グルーへ
72 -- 正の進入をしたか否か(した:1,しなかった:0)
73 local cat_lp = luatexbase.catcodetables['latex-package']
74
75 local round, floor = tex.round, math.floor
76 local min, max = math.min, math.max
77
78 luatexja.userid_table.RUBY_PRE = luatexbase.newuserwhatsitid('ruby_pre',  'luatexja')
79 luatexja.userid_table.RUBY_POST = luatexbase.newuserwhatsitid('ruby_post',  'luatexja')
80 local RUBY_PRE  = luatexja.userid_table.RUBY_PRE
81 local RUBY_POST = luatexja.userid_table.RUBY_POST
82 local PROCESSED_BEGIN_FLAG = luatexja.icflag_table.PROCESSED_BEGIN_FLAG
83
84 ----------------------------------------------------------------
85 -- TeX interface 0
86 ----------------------------------------------------------------
87 do
88    local getbox = node.direct.getbox
89    function luatexja.ruby.cpbox() return node_copy(getbox(0)) end
90 end
91
92 ----------------------------------------------------------------
93 -- 補助関数群 1
94 ----------------------------------------------------------------
95
96 local function gauss(coef)
97    -- #coef 式,#coef 変数の連立1次方程式系を掃きだし法で解く.
98    local deg = #coef
99    for i = 1, deg do
100       if coef[i][i]==0 then
101          for j = i+1, deg do
102             if coef[j][i]~=0 then
103                coef[i], coef[j] = coef[j], coef[i]; break
104             end
105          end
106       end
107       for j = 1,deg do
108          local d = coef[i][i];
109          if j~=i then
110             local e = coef[j][i]
111             for k = 1, deg+1 do coef[j][k] = coef[j][k] - e*coef[i][k]/d end
112          else
113             for k = 1, deg+1 do coef[i][k] = coef[i][k]/d end
114          end
115       end
116    end
117 end
118
119 local function solve_1(coef)
120    local a, b, c = coef[1][4], coef[2][4], coef[3][4]
121    coef[1][4], coef[2][4], coef[3][4] = c-b, a+b-c, c-a
122    return coef
123 end
124
125 local function solve_2(coef)
126    local a, b, c, d, e = coef[1][6], coef[2][6], coef[3][6], coef[4][6], coef[5][6]
127    coef[1][6], coef[2][6], coef[3][6], coef[4][6], coef[5][6]
128       = e-c, a+c-e, e-a-d, b+d-e, e-b
129    return coef
130 end
131
132
133 -- 実行回数 + ルビ中身 から uniq_id を作る関数
134 luatexja.ruby.old_break_info = {} -- public, 前 run 時の分割情報
135 local old_break_info = luatexja.ruby.old_break_info
136 local cache_handle
137 function luatexja.ruby.read_old_break_info()
138    if  tex.jobname then
139       local fname = tex.jobname .. '.ltjruby'
140       local real_file = kpse.find_file(fname)
141       if real_file then dofile(real_file) end
142       cache_handle = io.open(fname, 'w')
143       if cache_handle then
144          cache_handle:write('local lrob=luatexja.ruby.old_break_info\n')
145       end
146    end
147 end
148 local make_uniq_id
149 do
150    local exec_count = 0
151    make_uniq_id = function (w)
152       exec_count = exec_count + 1
153       return exec_count
154    end
155 end
156
157 -- concatenation of boxes: reusing nodes
158 -- ルビ組版が行われている段落/hboxでの設定が使われる.
159 -- ルビ文字を格納しているボックスでの設定ではない!
160 local function get_attr_icflag(p)
161     return (get_attr(p, attr_icflag) or 0) % PROCESSED_BEGIN_FLAG
162 end
163 local concat
164 do
165    local node_prev = node.direct.getprev
166    function concat(f, b)
167       if f then
168          if b then
169             local h, nh = getlist(f), getlist(b)
170             if getid(nh)==id_whatsit and getsubtype(nh)==sid_user then
171                nh=node_next(nh); node_free(node_prev(nh))
172             end
173             set_attr(nh, attr_icflag,
174               get_attr_icflag(nh) + PROCESSED_BEGIN_FLAG)
175             setnext(node_tail(h), nh)
176             setlist(f, nil); node_free(f)
177             setlist(b, nil); node_free(b)
178             local g = luatexja.jfmglue.main(h,false)
179             return hpack(g)
180          else
181             return f
182          end
183       elseif b then
184          return b
185       else
186          local h = node_new(id_hlist, 0)
187          setwhd(h, 0, 0, 0)
188          setfield(h, 'glue_set', 0)
189          setfield(h, 'glue_order', 0)
190          setlist(h, nil)
191          return h
192       end
193    end
194 end
195
196 local function expand_3bits(num)
197    local t = {}; local a = num
198    for i = 1, 10 do t[i], a = a%8, a//8 end
199    return t
200 end
201 ----------------------------------------------------------------
202 -- 補助関数群 2
203 ----------------------------------------------------------------
204
205 -- box の中身のノードは再利用される
206 local enlarge
207 do
208    local FROM_JFM       = luatexja.icflag_table.FROM_JFM
209    local PROCESSED      = luatexja.icflag_table.PROCESSED
210    local KANJI_SKIP     = luatexja.icflag_table.KANJI_SKIP
211    local KANJI_SKIP_JFM = luatexja.icflag_table.KANJI_SKIP_JFM
212    local XKANJI_SKIP    = luatexja.icflag_table.XKANJI_SKIP
213    local XKANJI_SKIP_JFM= luatexja.icflag_table.XKANJI_SKIP_JFM
214    enlarge = function (box, new_width, pre, middle, post, prenw, postnw)
215       -- pre, middle, post: 伸縮比率
216       -- prenw, postnw: 前後の自然長 (sp)
217       local h = getlist(box);
218       local _, hh, hd = getwhd(box)
219       local hx = h
220       while hx do
221          local hic = get_attr(hx, attr_icflag) or 0
222          if (hic == KANJI_SKIP) or (hic == KANJI_SKIP_JFM)
223             or (hic == XKANJI_SKIP) or (hic == XKANJI_SKIP_JFM)
224             or ((hic<=FROM_JFM+63) and (hic>=FROM_JFM)) then
225             -- この 5 種類の空白をのばす
226                if getid(hx) == id_kern then
227                   local k = node_new(id_glue, 0)
228                   setglue(k, getkern(hx), round(middle*65536), 0,
229                              2, 0)
230                   h = insert_after(h, hx, k);
231                   h = node_remove(h, hx); node_free(hx); hx = k
232                else -- glue
233                   setglue(hx, getwidth(hx), round(middle*65536), 0,
234                              2, 0)
235                end
236          end
237          hx = node_next(hx)
238       end
239       -- 先頭の空白を挿入
240       local k = node_new(id_glue);
241       setglue(k, prenw, round(pre*65536), 0, 2, 0)
242       h = insert_before(h, h, k);
243       -- 末尾の空白を挿入
244       local k = node_new(id_glue);
245       setglue(k, postnw, round(post*65536), 0, 2, 0)
246       insert_after(h, node_tail(h), k);
247       -- hpack
248       setlist(box, nil); node_free(box)
249       box = hpack(h, new_width, 'exactly')
250       setheight(box, hh); setdepth(box, hd)
251       return box
252    end
253 end
254
255
256 ----------------------------------------------------------------
257 -- TeX interface
258 ----------------------------------------------------------------
259
260 -- rtlr: ルビ部分のボックスたち r1, r2, ...
261 -- rtlp: 親文字 のボックスたち p1, p2, ...
262 local function texiface_low(rst, rtlr, rtlp)
263    local w = node_new(id_whatsit, sid_user)
264    setfield(w, 'type', 110); setfield(w, 'user_id', RUBY_PRE)
265    local wv = node_new(id_whatsit, sid_user)
266    setfield(w, 'value', to_node(wv))
267    setfield(wv, 'type', 108)
268    setfield(wv, 'value', rst); rst.count = #rtlr
269    setfield(wv, 'user_id', RUBY_PRE) -- dummy
270    local n = wv
271    for i = 1, #rtlr do
272       _, n = insert_after(wv, n, rtlr[i])
273       _, n = insert_after(wv, n, rtlp[i])
274    end
275    -- w.value: (whatsit) .. r1 .. p1 .. r2 .. p2
276    node.direct.write(w); return w,wv
277 end
278
279 -- rst: table
280 function luatexja.ruby.texiface(rst, rtlr, rtlp)
281    if #rtlr ~= #rtlp then
282       for i=1, #rtlr do node_free(rtlr[i]) end
283       for i=1, #rtlp do node_free(rtlp[i]) end
284       ltjb.package_error('luatexja-ruby',
285                          'Group count mismatch between the ruby and\n' ..
286                          'the body (' .. #rtlr .. ' != ' .. #rtlp .. ').',
287                          '')
288    else
289       local f, eps = true, rst.eps
290       for i = 1,#rtlr do
291          if getwidth(rtlr[i]) > getwidth(rtlp[i]) + eps then
292             f = false; break
293          end
294       end
295       if f then -- モノルビ * n
296          local r,p = {true}, {true}
297          for i = 1,#rtlr do
298             r[1] = rtlr[i]; p[1] = rtlp[i]; texiface_low(rst, r, p)
299          end
300       else
301          local w, wv = texiface_low(rst, rtlr, rtlp)
302          local id = make_uniq_id(w)
303          set_attr(wv, attr_ruby_id, id)
304       end
305    end
306 end
307
308 ----------------------------------------------------------------
309 -- pre_line_break
310 ----------------------------------------------------------------
311
312 -- r, p の中身のノードは再利用される
313 local function enlarge_parent(r, p, tmp_tbl, no_begin, no_end)
314    -- r: ルビ部分の格納された box,p: 同,親文字
315    local rwidth = getwidth(r)
316    local sumprot = rwidth - getwidth(p) -- >0
317    local pre_intrusion, post_intrusion
318    local ppre, pmid, ppost = tmp_tbl.ppre, tmp_tbl.pmid, tmp_tbl.ppost
319    local mapre, mapost = tmp_tbl.mapre, tmp_tbl.mapost
320    local intmode = (tmp_tbl.mode//4)%4
321    if no_begin then mapre  = mapre + tmp_tbl.before_jfmgk end
322    if no_end   then mapost = mapost + tmp_tbl.after_jfmgk end
323    if (tmp_tbl.mode%4 >=2) and (tmp_tbl.pre<0) and (tmp_tbl.post<0) then
324        mapre = min(mapre,mapost); mapost = mapre
325    end
326    if intmode == 0 then --  とりあえず組んでから決める
327       p = enlarge(p, rwidth, ppre, pmid, ppost, 0, 0)
328       pre_intrusion  = min(mapre, round(ppre*getfield(p, 'glue_set')*65536))
329       post_intrusion = min(mapost, round(ppost*getfield(p, 'glue_set')*65536))
330    elseif intmode == 1 then
331       pre_intrusion = min(mapre, sumprot);
332       post_intrusion = min(mapost, max(sumprot-pre_intrusion, 0))
333       p = enlarge(p, rwidth, ppre, pmid, ppost, pre_intrusion, post_intrusion)
334    elseif intmode == 2 then
335       post_intrusion = min(mapost, sumprot);
336       pre_intrusion = min(mapre, max(sumprot-post_intrusion, 0))
337       p = enlarge(p, rwidth, ppre, pmid, ppost, pre_intrusion, post_intrusion)
338    else --  intmode == 3
339       local n = min(mapre, mapost)*2
340       if n < sumprot then
341          pre_intrusion = n/2; post_intrusion = n/2
342       else
343          pre_intrusion = sumprot//2; post_intrusion = sumprot - pre_intrusion
344       end
345       p = enlarge(p, rwidth, ppre, pmid, ppost, pre_intrusion, post_intrusion)
346       pre_intrusion = min(mapre, pre_intrusion + round(ppre*getfield(p, 'glue_set')*65536))
347       post_intrusion = min(mapost, post_intrusion + round(ppost*getfield(p, 'glue_set')*65536))
348    end
349    setshift(r, -pre_intrusion)
350    local rwidth = rwidth - pre_intrusion - post_intrusion
351    setwidth(r, rwidth); setwidth(p, rwidth)
352    local ps = getlist(p)
353    setwidth(ps, getwidth(ps) - pre_intrusion)
354    local orig_post_intrusion, post_jfmgk = post_intrusion, false
355    if no_end then
356        if orig_post_intrusion > tmp_tbl.after_jfmgk then
357            orig_post_intrusion = orig_post_intrusion - tmp_tbl.after_jfmgk
358            post_jfmgk = (tmp_tbl.after_jfmgk > 0)
359        else
360            orig_post_intrusion = 0
361            post_jfmgk = (post_intrusion > 0)
362        end
363     end
364    return r, p, orig_post_intrusion, post_jfmgk
365 end
366
367 -- ルビボックスの生成(単一グループ)
368 -- returned value: <new box>, <ruby width>, <post_intrusion>
369 local max_margin
370 local function new_ruby_box(r, p, tmp_tbl, no_begin, no_end)
371    local post_intrusion, post_jfmgk = 0, false
372    local imode
373    local ppre, pmid, ppost = tmp_tbl.ppre, tmp_tbl.pmid, tmp_tbl.ppost
374    local mapre, mapost = tmp_tbl.mapre, tmp_tbl.mapost
375    local rpre, rmid, rpost, rsmash
376    imode = tmp_tbl.mode//0x100000; rsmash = (imode%2 ==1)
377    imode = imode//2; rpost = imode%8;
378    imode = (imode-rpost)/8;  rmid  = imode%8;
379    imode = (imode-rmid)/8;   rpre  = imode%8
380    if getwidth(r) > getwidth(p) then  -- change the width of p
381       r, p, post_intrusion, post_jfmgk = enlarge_parent(r, p, tmp_tbl, no_begin, no_end)
382    elseif getwidth(r) < getwidth(p) then -- change the width of r
383       r = enlarge(r, getwidth(p), rpre, rmid, rpost, 0, 0)
384       post_intrusion = 0
385       local need_repack = false
386       -- margin が大きくなりすぎた時の処理
387       if round(rpre*getfield(r, 'glue_set')*65536) > max_margin then
388          local ps = getlist(r); need_repack = true
389          setwidth(ps, max_margin)
390          setfield(ps, 'stretch', 1) -- 全く伸縮しないのも困る
391       end
392       if round(rpost*getfield(r, 'glue_set')*65536) > max_margin then
393          local ps = node_tail(getlist(r)); need_repack = true
394          setwidth(ps, max_margin)
395          setfield(ps, 'stretch', 1) -- 全く伸縮しないのも困る
396       end
397       if need_repack then
398          local rt = r
399          r = hpack(getlist(r), getwidth(r), 'exactly')
400          setlist(rt, nil); node_free(rt);
401       end
402    end
403    local a, k = node_new(id_rule), node_new(id_kern, 1)
404    setwhd(a, 0, 0, 0); setkern(k, tmp_tbl.intergap)
405    insert_after(r, r, a); insert_after(r, a, k);
406    insert_after(r, k, p); setnext(p, nil)
407    if tmp_tbl.rubydepth >= 0 then setdepth(r, tmp_tbl.rubydepth) end
408    if tmp_tbl.baseheight >= 0 then setheight(p, tmp_tbl.baseheight) end
409    a = node.direct.vpack(r); setshift(a, 0)
410    set_attr(a, attr_ruby, post_intrusion)
411    set_attr(a, attr_ruby_post_jfmgk, post_jfmgk and 1 or 0)
412    if rsmash or getheight(a)<getheight(p) then
413       local k = node_new(id_kern, 1)
414       setkern(k, -getheight(a)+getheight(p))
415       setlist(a, k); insert_before(r, r, k)
416       setheight(a, getheight(p))
417    end
418
419    return a, getwidth(r), post_intrusion, post_jfmgk
420 end
421
422
423 -- High-level routine in pre_linebreak_filter
424 local post_intrusion_backup, post_jfmgk_backup
425 local max_allow_pre, max_allow_post
426
427 local flush_list = node.direct.flush_list
428 -- 中付き熟語ルビ,cmp containers
429 -- 「文字の構成を考えた」やつはどうしよう
430 local function pre_low_cal_box(w, cmp)
431    local rb = {}
432    local pb = {}
433    local kf = {}
434    -- kf[i] : container 1--i からなる行末形
435    -- kf[cmp+i] : container i--cmp からなる行頭形
436    -- kf[2cmp+1] : 行中形
437    local wv = getfield(w, 'value')
438    local rst = getfield(wv, 'value')
439    local mdt -- nt*: node temp
440    local coef = {} -- 連立一次方程式の拡大係数行列
441    local rtb = expand_3bits(rst.stretch)
442
443    -- node list 展開・行末形の計算
444    local nt, nta, ntb = wv, nil, nil -- nt*: node temp
445    rst.ppre, rst.pmid, rst.ppost = rtb[6], rtb[5], rtb[4]
446    rst.mapre, rst.mapost = max_allow_pre, 0
447   for i = 1, cmp do
448       nt = node_next(nt); rb[i] = nt; nta = concat(nta, node_copy(nt))
449       nt = node_next(nt); pb[i] = nt; ntb = concat(ntb, node_copy(nt))
450       coef[i] = {}
451       for j = 1, 2*i do coef[i][j] = 1 end
452       for j = 2*i+1, 2*cmp+1 do coef[i][j] = 0 end
453       kf[i], coef[i][2*cmp+2]
454          = new_ruby_box(node_copy(nta), node_copy(ntb), rst, true, false)
455    end
456    node_free(nta); node_free(ntb)
457
458    -- 行頭形の計算
459    local nta, ntb = nil, nil
460    rst.ppre, rst.pmid, rst.ppost = rtb[9], rtb[8], rtb[7]
461    rst.mapre, rst.mapost = 0, max_allow_post
462    for i = cmp,1,-1 do
463       coef[cmp+i] = {}
464       for j = 1, 2*i-1 do coef[cmp+i][j] = 0 end
465       for j = 2*i, 2*cmp+1 do coef[cmp+i][j] = 1 end
466       nta = concat(node_copy(rb[i]), nta); ntb = concat(node_copy(pb[i]), ntb)
467       kf[cmp+i], coef[cmp+i][2*cmp+2]
468          = new_ruby_box(node_copy(nta), node_copy(ntb), rst, false, true)
469    end
470
471    -- ここで,nta, ntb には全 container を連結した box が入っているので
472    -- それを使って行中形を計算する.
473    coef[2*cmp+1] = {}
474    for j = 1, 2*cmp+1 do coef[2*cmp+1][j] = 1 end
475    rst.ppre, rst.pmid, rst.ppost = rtb[3], rtb[2], rtb[1]
476    rst.mapre, rst.mapost = max_allow_pre, max_allow_post
477    kf[2*cmp+1], coef[2*cmp+1][2*cmp+2], post_intrusion_backup, post_jfmgk_backup
478       = new_ruby_box(nta, ntb, rst, true, true)
479
480    -- w.value の node list 更新.
481    local nt = wv
482    flush_list(node_next(wv))
483    for i = 1, 2*cmp+1 do setnext(nt, kf[i]); nt = kf[i]  end
484
485    if cmp==1 then     solve_1(coef)
486    elseif cmp==2 then solve_2(coef)
487    else
488       gauss(coef) -- 掃きだし法で連立方程式形 coef を解く
489    end
490    return coef
491 end
492
493 local first_whatsit
494 do
495    local traverse_id = node.direct.traverse_id
496    function first_whatsit(n) -- n 以後で最初の whatsit
497       for h in traverse_id(id_whatsit, n) do
498          return h
499       end
500       return nil
501    end
502 end
503
504 local next_cluster_array = {}
505 -- ノード追加
506 local function pre_low_app_node(head, w, cmp, coef, ht, dp)
507    -- メインの node list 更新
508    local nt = node_new(id_glue)
509    setglue(nt, coef[1][2*cmp+2], 0, 0, 0, 0)
510    set_attr(nt, attr_ruby, 1); set_attr(w, attr_ruby, 2)
511    head = insert_before(head, w, nt)
512    nt = w
513    for i = 1, cmp do
514       -- rule
515       local nta = node_new(id_rule, 0);
516       setwhd(nta, coef[i*2][2*cmp+2], ht, dp)
517       insert_after(head, nt, nta)
518       set_attr(nta, attr_ruby, 2*i+1)
519       -- glue
520       if i~=cmp or not next_cluster_array[w] then
521          nt = node_new(id_glue); insert_after(head, nta, nt)
522       else
523          nt = next_cluster_array[w]
524       end
525       setglue(nt, coef[i*2+1][2*cmp+2], 0, 0, 0, 0)
526       set_attr(nt, attr_ruby, 2*i+2)
527    end
528    tex.setattribute('global', attr_ruby, -0x7FFFFFFF)
529    setfield(w, 'user_id', RUBY_POST)
530    next_cluster_array[w]=nil
531    return head, first_whatsit(node_next(nt))
532 end
533
534 local function pre_high(ahead)
535    if not ahead then return ahead end
536    local head = to_direct(ahead)
537    post_intrusion_backup, post_jfmgk_backup = 0, false
538    local n = first_whatsit(head)
539    while n do
540       if getsubtype(n) == sid_user and getfield(n, 'user_id') == RUBY_PRE then
541          local nv = getfield(n, 'value')
542          local rst = getfield(nv, 'value')
543          max_allow_pre = rst.pre or 0
544          local atr = get_attr(n, attr_ruby) or 0
545          if max_allow_pre < 0 then
546              -- 直前のルビで intrusion がおこる可能性あり.
547              -- 前 run のデータが残っていればそれを使用,
548              -- そうでなければ行中形のデータを利用する
549              local op = (atr>0) and (old_break_info[atr] or post_intrusion_backup) or 0
550              max_allow_pre = max(0, -max_allow_pre - op)
551          end
552          if rst.exclude_pre_from_prev_ruby  and atr>0 and old_break_info[-atr]
553            and (old_break_info[-atr]>0 or post_jfmgk_backup) then
554             -- 「直前のルビが JFM グルーに進入→現在のルビの前文字進入はなし」という状況
555             max_allow_pre = 0; rst.exclude_pre_from_prev_ruby=false
556          end
557          if rst.exclude_pre_jfmgk_from_prev_ruby
558             and atr>0 and ((old_break_info[atr]  or post_intrusion_backup) > 0) then
559             -- 「直前のルビが文字に進入→現在のルビの和文処理グルーへの進入はなし」という状況
560             rst.before_jfmgk = 0
561          end
562          post_intrusion_backup, post_jfmgk_backup = 0, false
563          max_allow_post = rst.post or 0
564          max_margin = rst.maxmargin or 0
565          local coef = pre_low_cal_box(n, rst.count)
566          local s = node_tail(nv) --ルビ文字
567          head, n = pre_low_app_node(
568             head, n, rst.count, coef, getheight(s), getdepth(s)
569          )
570       else
571          n = first_whatsit(node_next(n))
572       end
573    end
574    return to_node(head)
575 end
576 luatexbase.add_to_callback('pre_linebreak_filter', pre_high, 'ltj.ruby.pre', 100)
577 luatexbase.add_to_callback('hpack_filter', pre_high, 'ltj.ruby.pre', 100)
578
579 ----------------------------------------------------------------
580 -- post_line_break
581 ----------------------------------------------------------------
582 local post_lown
583 do
584    local function write_aux(wv, num, bool)
585       local id = get_attr(wv, attr_ruby_id) or 0
586       if id>0 and cache_handle then
587          cache_handle:write(
588             'lrob[' .. tostring(id) .. ']=' .. num .. '\nlrob[' .. tostring(-id) .. ']=' .. tostring(bool) .. '\n')
589       end
590    end
591
592    post_lown = function (rs, rw, cmp, ch)
593       -- ch: the head of `current' hlist
594       if #rs ==0 or not rw then return ch end
595       local hn = get_attr(rs[1], attr_ruby)
596       local fn = get_attr(rs[#rs], attr_ruby)
597       local wv = getfield(rw, 'value')
598       if hn==1 then
599          if fn==2*cmp+2 then
600             local hn = node_tail(wv)
601             node_remove(wv, hn)
602             insert_after(ch, rs[1], hn)
603             set_attr(hn, attr_icflag,  PROCESSED)
604             write_aux(wv, get_attr(hn, attr_ruby), get_attr(hn, attr_ruby_post_jfmgk))-- 行中形
605          else
606             local deg, hn = (fn-1)/2, wv
607             for i = 1, deg do hn = node_next(hn) end;
608             node_remove(wv, hn)
609             setnext(hn, nil)
610             insert_after(ch, rs[1], hn)
611             set_attr(hn, attr_icflag,  PROCESSED)
612             write_aux(wv, get_attr(hn, attr_ruby), get_attr(hn, attr_ruby_post_jfmgk))
613          end
614       else
615          local deg, hn = max((hn-1)/2,2), wv
616          for i = 1, cmp+deg-1 do hn = node_next(hn) end
617          -- -1 is needed except the case hn = 3,
618          --   because a ending-line form is removed already from the list
619          node_remove(wv, hn); setnext(hn, nil)
620          insert_after(ch, rs[1], hn)
621          set_attr(hn, attr_icflag,  PROCESSED)
622          if fn == 2*cmp-1 then
623             write_aux(wv, get_attr(hn, attr_ruby), get_attr(hn, attr_ruby_post_jfmgk))
624          end
625       end
626       for i = 1,#rs do
627          local ri = rs[i]
628          ch = node_remove(ch, ri); node_free(ri);
629       end
630       -- cleanup
631       if fn >= 2*cmp+1 then node_free(rw) end
632       return ch;
633    end
634 end
635
636 local traverse_id = node.direct.traverse_id
637 local function post_high_break(head)
638    local rs = {}   -- rs: sequence of ruby_nodes,
639    local rw = nil  -- rw: main whatsit
640    local cmp = -2  -- dummy
641    for h in traverse_id(id_hlist, to_direct(head)) do
642       for i = 1, #rs do rs[i] = nil end
643       local ha = getlist(h)
644       while ha do
645          local hai = getid(ha)
646          local i = ((hai == id_glue and getsubtype(ha)==0)
647                        or (hai == id_rule and getsubtype(ha)==0)
648                        or (hai == id_whatsit and getsubtype(ha)==sid_user
649                               and getfield(ha, 'user_id', RUBY_POST)))
650             and get_attr(ha, attr_ruby) or 0
651          if i==0 then
652             ha = node_next(ha)
653          elseif i==1 then
654             setlist(h, post_lown(rs, rw, cmp, getlist(h)))
655             for i = 2, #rs do rs[i] = nil end -- rs[1] is set by the next statement
656             rs[1], rw = ha, nil; ha = node_next(ha)
657          elseif i==2 then
658             rw = ha
659             cmp = getfield(getfield(rw, 'value'), 'value').count
660             local hb, hc =  node_remove(getlist(h), rw)
661             setlist(h, hb); ha = hc
662          else -- i>=3
663             rs[#rs+1] = ha; ha = node_next(ha)
664          end
665       end
666       setlist(h, post_lown(rs, rw, cmp, getlist(h)))
667    end
668    return head
669 end
670
671 local function post_high_hbox(ahead)
672    local ha = to_direct(ahead); local head = ha
673    local rs = {};  -- rs: sequence of ruby_nodes,
674    local rw = nil; -- rw: main whatsit
675    local cmp
676    while ha do
677       local hai = getid(ha)
678       local i = ((hai == id_glue and getsubtype(ha)==0)
679                     or (hai == id_rule and getsubtype(ha)==0)
680                     or (hai == id_whatsit and getsubtype(ha)==sid_user
681                            and getfield(ha, 'user_id', RUBY_POST)))
682          and get_attr(ha, attr_ruby) or 0
683       if i==0 then
684          ha = node_next(ha)
685       elseif i==1 then
686          head = post_lown(rs, rw, cmp, head)
687          for i = 2, #rs do rs[i] = nil end -- rs[1] is set by the next statement
688          rs[1], rw = ha, nil; ha = node_next(ha)
689       elseif i==2 then
690          rw = ha
691          cmp = getfield(getfield(rw, 'value'), 'value').count
692          head, ha = node_remove(head, rw)
693       else -- i >= 3
694          rs[#rs+1] = ha; ha = node_next(ha)
695       end
696    end
697    return to_node(post_lown(rs, rw, cmp, head))
698 end
699
700 luatexbase.add_to_callback('post_linebreak_filter', post_high_break, 'ltj.ruby.post_break', 100)
701 luatexbase.add_to_callback('hpack_filter', post_high_hbox, 'ltj.ruby.post_hbox', 101)
702
703
704 ----------------------------------------------------------------
705 -- for jfmglue callbacks
706 ----------------------------------------------------------------
707 do
708    local RIPRE  = luatexja.stack_table_index.RIPRE
709    local RIPOST = luatexja.stack_table_index.RIPOST
710    local abs = math.abs
711    local function whatsit_callback(Np, lp, Nq)
712       if Np.nuc then return Np
713       elseif  getfield(lp, 'user_id') == RUBY_PRE then
714          Np.first, Np.nuc, Np.last = lp, lp, lp
715          local lpv = getfield(lp, 'value')
716          local rst = getfield(lpv, 'value')
717          local x = node_next(node_next(lpv))
718          Np.last_char = luatexja.jfmglue.check_box_high(Np, getlist(x), nil)
719          if Nq.id ~=id_pbox_w then
720             if type(Nq.char)=='number' then
721                -- Nq is a JAchar
722                if rst.pre < 0 then -- auto
723                   local s = ltjs.table_current_stack[RIPRE + Nq.char] or 0
724                   local p = round(abs(s)*rst.rubyzw)
725                   if rst.mode%2 == 0 then -- intrusion 無効
726                      p = 0
727                   end
728                   rst.pre = -p; rst.exclude_pre_from_prev_ruby = (s<0);
729                    rst.exclude_pre_jfmgk_from_prev_ruby = (ltjs.table_current_stack[RIPOST +Nq.char] or 0)<0;
730                end
731                if Nq.prev_ruby then
732                   set_attr(lp, attr_ruby, Nq.prev_ruby)
733                end
734             elseif rst.pre < 0 then -- auto
735                if Nq.char == 'parbdd' then
736                   local s = ltjs.table_current_stack[RIPRE - 1] or 0
737                   local p = round(abs(s)*rst.rubyzw)
738                   p = min(p, Nq.width)
739                   if rst.mode%2 == 0 then -- intrusion 無効
740                      p = 0
741                   end
742                   rst.pre = p; rst.exclude_pre_from_prev_ruby = (s<0);
743                   rst.exclude_pre_jfmgk_from_prev_ruby = (ltjs.table_current_stack[RIPOST -1] or 0)<0;
744                else
745                   rst.pre = 0
746                end
747             end
748          elseif rst.pre < 0 then -- auto
749             rst.pre = 0
750          end
751          return Np
752       else
753         return Np
754       end
755    end
756    luatexbase.add_to_callback("luatexja.jfmglue.whatsit_getinfo", whatsit_callback,
757                               "luatexja.ruby.np_info", 1)
758 end
759
760 do
761    local FROM_JFM = luatexja.icflag_table.FROM_JFM
762    local KANJI_SKIP = luatexja.icflag_table.KANJI_SKIP
763    local function add_gk(t, index, p)
764       local ic = get_attr_icflag(p)
765       if ic and (ic>FROM_JFM) and (ic<KANJI_SKIP) then ic = FROM_JFM end
766       if t.intrude_jfmgk[ic] then
767           if getid(p)==id_kern then t[index] = t[index] + getkern(p)
768           else t[index] = t[index] + getwidth(p) end
769       end
770    end
771    local RIPOST = luatexja.stack_table_index.RIPOST
772    local abs = math.abs
773    local function whatsit_after_callback(s, Nq, Np, head)
774       if not s and  getfield(Nq.nuc, 'user_id') == RUBY_PRE then
775          if Np then
776             local last_glue = node_new(id_glue)
777             set_attr(last_glue, attr_icflag, 0)
778             insert_before(Nq.nuc, Np.first, last_glue)
779             Np.first = last_glue
780             next_cluster_array[Nq.nuc] = last_glue -- ルビ処理用のグルー
781          end
782          local nqnv = getfield(Nq.nuc, 'value')
783          local rst = getfield(nqnv, 'value')
784          if Nq.gk then
785             if type(Nq.gk)=="table" then
786                for _,v in ipairs(Nq.gk) do add_gk(rst, 'before_jfmgk', v) end
787             else add_gk(rst, 'before_jfmgk', Nq.gk) end
788          end
789          local x =  node_next(node_next(nqnv))
790          for i = 2, rst.count do x = node_next(node_next(x)) end
791          Nq.last_char = luatexja.jfmglue.check_box_high(Nq, getlist(x), nil)
792          luatexja.jfmglue.after_hlist(Nq)
793          if Np and Np.id ~=id_pbox_w and type(Np.char)=='number' then
794             -- Np is a JAchar
795             if rst.post < 0 then -- auto
796                local p = round(abs(ltjs.table_current_stack[RIPOST + Np.char] or 0)*rst.rubyzw)
797                if rst.mode%2 == 0 then -- intrusion 無効
798                   p = 0
799                end
800                rst.post = p
801             end
802             Np.prev_ruby = get_attr(getfield(Nq.nuc, 'value'), attr_ruby_id)
803             -- 前のクラスタがルビであったことのフラグ
804          else -- 直前が文字以外
805             local nqnv = getfield(Nq.nuc, 'value')
806             local rst = getfield(nqnv, 'value')
807             if rst.post < 0 then -- auto
808                rst.post = 0
809             end
810          end
811          return head
812       else
813          return s
814       end
815    end
816    luatexbase.add_to_callback("luatexja.jfmglue.whatsit_after", whatsit_after_callback,
817                               "luatexja.ruby.np_info_after", 1)
818    local function w (s, Nq, Np)
819       if not s and  getfield(Nq.nuc, 'user_id') == RUBY_PRE then
820          local rst = getfield(getfield(Nq.nuc, 'value'), 'value')
821          if Np.gk then
822             if type(Np.gk)=="table" then
823                for _,v in ipairs(Np.gk) do add_gk(rst, 'after_jfmgk', v) end
824             else add_gk(rst, 'after_jfmgk', Np.gk) end
825          end
826       end
827    end
828    luatexbase.add_to_callback("luatexja.jfmglue.whatsit_last_minute", w,
829                               "luatexja.ruby.np_info_last_minute", 1)
830 end