OSDN Git Service

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