OSDN Git Service

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