OSDN Git Service

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