OSDN Git Service

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