OSDN Git Service

ltj-ruby.lua: argument
[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       if cache_handle then 
133          cache_handle:write('local lrob=luatexja.ruby.old_break_info\n')
134       end
135    end
136 end
137 local make_uniq_id
138 do
139    local exec_count = 0
140    make_uniq_id = function (w)
141       exec_count = exec_count + 1
142       return exec_count
143    end
144 end
145
146 -- concatenation of boxes: reusing nodes
147 -- ルビ組版が行われている段落/hboxでの設定が使われる.
148 -- ルビ文字を格納しているボックスでの設定ではない!
149 local function get_attr_icflag(p)
150     return (has_attr(p, attr_icflag) or 0) % PROCESSED_BEGIN_FLAG
151 end
152 local concat
153 do
154    local node_prev = node.direct.getprev
155    function concat(f, b)
156       if f then
157          if b then
158             local h, nh = getlist(f), getlist(b)
159             if getid(nh)==id_whatsit and getsubtype(nh)==sid_user then
160                nh=node_next(nh); node_free(node_prev(nh))
161             end
162             set_attr(nh, attr_icflag,
163               get_attr_icflag(nh) + PROCESSED_BEGIN_FLAG)
164             setfield(node_tail(h), 'next', nh)
165             setfield(f, 'head', nil); node_free(f)
166             setfield(b, 'head', nil); node_free(b)
167             local g = luatexja.jfmglue.main(h,false)
168             return node.direct.hpack(g)
169          else
170             return f
171          end
172       elseif b then
173          return b
174       else
175          local h = node_new(id_hlist)
176          setfield(h, 'subtype', 0)
177          setfield(h, 'width', 0)
178          setfield(h, 'height', 0)
179          setfield(h, 'depth', 0)
180          setfield(h, 'glue_set', 0)
181          setfield(h, 'glue_order', 0)
182          setfield(h, 'head', nil)
183          return h
184       end
185    end
186 end
187
188 local function expand_3bits(num)
189    local t = {}; local a = num
190    for i = 1, 10 do
191       t[i] = a%8; a = floor(a/8)
192    end
193    return t
194 end
195 ----------------------------------------------------------------
196 -- 補助関数群 2
197 ----------------------------------------------------------------
198
199 -- box の中身のノードは再利用される
200 local enlarge
201 do
202    local FROM_JFM       = luatexja.icflag_table.FROM_JFM
203    local PROCESSED      = luatexja.icflag_table.PROCESSED
204    local KANJI_SKIP     = luatexja.icflag_table.KANJI_SKIP
205    local KANJI_SKIP_JFM = luatexja.icflag_table.KANJI_SKIP_JFM
206    local XKANJI_SKIP    = luatexja.icflag_table.XKANJI_SKIP
207    local XKANJI_SKIP_JFM= luatexja.icflag_table.XKANJI_SKIP_JFM
208    enlarge = function (box, new_width, pre, middle, post, prenw, postnw)
209       -- pre, middle, post: 伸縮比率
210       -- prenw, postnw: 前後の自然長 (sp)
211       local h = getlist(box);
212       local hh, hd = getfield(box, 'height'), getfield(box, 'depth')
213       local hx = h
214       while hx do
215          local hic = has_attr(hx, attr_icflag) or 0
216          if (hic == KANJI_SKIP) or (hic == KANJI_SKIP_JFM)
217             or (hic == XKANJI_SKIP) or (hic == XKANJI_SKIP_JFM)
218             or ((hic<=FROM_JFM+63) and (hic>=FROM_JFM)) then
219             -- この 5 種類の空白をのばす
220                if getid(hx) == id_kern then
221                   local k = node_new(id_glue)
222                   setglue(k, getfield(hx, 'kern'), round(middle*65536), 0,
223                              2, 0)
224                   setfield(k, 'subtype', 0);
225                   h = insert_after(h, hx, k);
226                   h = node_remove(h, hx); node_free(hx); hx = k
227                else -- glue
228                   setglue(hx, getfield(hx, 'width'), round(middle*65536), 0,
229                              2, 0)
230                end
231          end
232          hx = node_next(hx)
233       end
234       -- 先頭の空白を挿入
235       local k = node_new(id_glue);
236       setglue(k, prenw, round(pre*65536), 0, 2, 0)
237       h = insert_before(h, h, k);
238       -- 末尾の空白を挿入
239       local k = node_new(id_glue);
240       setglue(k, postnw, round(post*65536), 0, 2, 0)
241       insert_after(h, node_tail(h), k);
242       -- hpack
243       setfield(box, 'head', nil); node_free(box)
244       box = node.direct.hpack(h, new_width, 'exactly')
245       setfield(box, 'height', hh)
246       setfield(box, 'depth', hd)
247       return box
248    end
249 end
250
251
252 ----------------------------------------------------------------
253 -- TeX interface
254 ----------------------------------------------------------------
255
256 -- rtlr: ルビ部分のボックスたち r1, r2, ...
257 -- rtlp: 親文字 のボックスたち p1, p2, ...
258 local function texiface_low(rst, rtlr, rtlp)
259    local w = node_new(id_whatsit, sid_user)
260    setfield(w, 'type', 110); setfield(w, 'user_id', RUBY_PRE)
261    local wv = node_new(id_whatsit, sid_user)
262    setfield(w, 'value', to_node(wv))
263    setfield(wv, 'type', 100)
264    setfield(wv, 'value', floor(#rtlr))
265    setfield(wv, 'user_id', RUBY_PRE) -- dummy
266    set_attr(wv, attr_ruby, rst.rubyzw)
267    set_attr(wv, attr_ruby_maxmargin, rst.maxmargin)
268    set_attr(wv, attr_ruby_maxprep, rst.pre)
269    set_attr(wv, attr_ruby_maxpostp, rst.post)
270    set_attr(wv, attr_ruby_intergap, rst.intergap)
271    set_attr(wv, attr_ruby_baseheight, rst.baseheight)
272    set_attr(wv, attr_ruby_stretch, rst.stretch)
273    set_attr(wv, attr_ruby_mode, rst.mode)
274    local n = wv
275    for i = 1, #rtlr do
276       _, n = insert_after(wv, n, rtlr[i])
277       _, n = insert_after(wv, n, rtlp[i])
278    end
279    -- w.value: (whatsit) .. r1 .. p1 .. r2 .. p2
280    node.direct.write(w); return w,wv
281 end
282
283 -- rst: table
284 function luatexja.ruby.texiface(rst, rtlr, rtlp)
285    if #rtlr ~= #rtlp then
286       for i=1, #rtlr do node_free(rtlr[i]) end
287       for i=1, #rtlp do node_free(rtlp[i]) end
288       ltjb.package_error('luatexja-ruby',
289                          'Group count mismatch between the ruby and\n' ..
290                          'the body (' .. #rtlr .. ' != ' .. #rtlp .. ').',
291                          '')
292    else
293       local f = true
294       for i = 1,#rtlr do
295          if getfield(rtlr[i], 'width') > getfield(rtlp[i], 'width') then
296             f = false; break
297          end
298       end
299       if f then -- モノルビ * n
300          local r,p = {true}, {true}
301          for i = 1,#rtlr do
302             r[1] = rtlr[i]; p[1] = rtlp[i]; texiface_low(rst, r, p)
303          end
304       else
305          local w, wv = texiface_low(rst, rtlr, rtlp)
306          local id = make_uniq_id(w)
307          set_attr(wv, attr_ruby_id, id)
308       end
309    end
310 end
311
312 ----------------------------------------------------------------
313 -- pre_line_break
314 ----------------------------------------------------------------
315
316 -- r, p の中身のノードは再利用される
317 local function enlarge_parent(r, p, tmp_tbl, intmode)
318    -- r: ルビ部分の格納された box,p: 同,親文字
319    local rwidth = getfield(r, 'width')
320    local sumprot = rwidth - getfield(p, 'width') -- >0
321    local pre_intrusion, post_intrusion
322    local ppre, pmid, ppost = tmp_tbl.ppre, tmp_tbl.pmid, tmp_tbl.ppost
323    local mapre, mapost = tmp_tbl.mapre, tmp_tbl.mapost
324    if intmode == 0 then --  とりあえず組んでから決める
325       p = enlarge(p, rwidth, ppre, pmid, ppost, 0, 0)
326       pre_intrusion  = min(mapre, round(ppre*getfield(p, 'glue_set')*65536))
327       post_intrusion = min(mapost, round(ppost*getfield(p, 'glue_set')*65536))
328    elseif intmode == 1 then
329       pre_intrusion = min(mapre, sumprot);
330       post_intrusion = min(mapost, max(sumprot-pre_intrusion, 0))
331       p = enlarge(p, rwidth, ppre, pmid, ppost, pre_intrusion, post_intrusion)
332    elseif intmode == 2 then
333       post_intrusion = min(mapost, sumprot);
334       pre_intrusion = min(mapre, max(sumprot-post_intrusion, 0))
335       p = enlarge(p, rwidth, ppre, pmid, ppost, pre_intrusion, post_intrusion)
336    else --  intmode == 3
337       local n = min(mapre, mapost)*2
338       if n < sumprot then
339          pre_intrusion = n/2; post_intrusion = n/2
340       else
341          pre_intrusion = floor(sumprot/2); post_intrusion = sumprot - pre_intrusion
342       end
343       p = enlarge(p, rwidth, ppre, pmid, ppost, pre_intrusion, post_intrusion)
344       pre_intrusion = min(mapre, pre_intrusion + round(ppre*getfield(p, 'glue_set')*65536))
345       post_intrusion = min(mapost, post_intrusion + round(ppost*getfield(p, 'glue_set')*65536))
346    end
347    setfield(r, 'shift', -pre_intrusion)
348    local rwidth = rwidth - pre_intrusion - post_intrusion
349    setfield(r, 'width', rwidth)
350    setfield(p, 'width', rwidth)
351    local ps = getlist(p)
352    setfield(ps, 'width', getfield(ps, 'width') - pre_intrusion)
353    return r, p, post_intrusion
354 end
355
356 -- ルビボックスの生成(単一グループ)
357 -- returned value: <new box>, <ruby width>, <post_intrusion>
358 local max_margin
359 local function new_ruby_box(r, p, tmp_tbl)
360    local post_intrusion = 0
361    local imode = tmp_tbl.imode
362    local ppre, pmid, ppost = tmp_tbl.ppre, tmp_tbl.pmid, tmp_tbl.ppost
363    local mapre, mapost = tmp_tbl.mapre, tmp_tbl.mapost
364    local rpre, rmid, rpost, rsmash
365    imode = floor(imode/262144); rsmash = (imode%2 ==1)
366    imode = floor(imode/2); rpost = imode%8;
367    imode = (imode-rpost)/8;  rmid  = imode%8;
368    imode = (imode-rmid)/8;   rpre  = imode%8
369    if getfield(r, 'width') > getfield(p, 'width') then  -- change the width of p
370       r, p, post_intrusion  = enlarge_parent(r, p, tmp_tbl, imode%4)
371    elseif getfield(r, 'width') < getfield(p, 'width') then -- change the width of r
372       r = enlarge(r, getfield(p, 'width'), rpre, rmid, rpost, 0, 0)
373       post_intrusion = 0
374       local need_repack = false
375       -- margin が大きくなりすぎた時の処理
376       if round(rpre*getfield(r, 'glue_set')*65536) > max_margin then
377          local ps = getlist(r); need_repack = true
378          setfield(ps, 'width', max_margin)
379          setfield(ps, 'stretch', 1) -- 全く伸縮しないのも困る
380       end
381       if round(rpost*getfield(r, 'glue_set')*65536) > max_margin then
382          local ps = node_tail(getlist(r)); need_repack = true
383          setfield(ps, 'width', max_margin)
384          setfield(ps, 'stretch', 1) -- 全く伸縮しないのも困る
385       end
386       if need_repack then
387          local rt = r
388          r = node.direct.hpack(getlist(r), getfield(r, 'width'), 'exactly')
389          setfield(rt, 'head', nil); node_free(rt);
390       end
391    end
392    local a, k = node_new(id_rule), node_new(id_kern, 1)
393    setfield(a, 'width', 0); setfield(a, 'height', 0)
394    setfield(a, 'depth', 0); setfield(k, 'kern', tmp_tbl.rgap)
395    insert_after(r, r, a); insert_after(r, a, k);
396    insert_after(r, k, p); setfield(p, 'next', nil)
397    if tmp_tbl.bheight > 0 then setfield(p, 'height', tmp_tbl.bheight) end
398    a = node.direct.vpack(r); setfield(a, 'shift', 0)
399    set_attr(a, attr_ruby, post_intrusion)
400    if rsmash or getfield(a, 'height')<getfield(p, 'height') then
401       local k = node_new(id_kern, 1)
402       setfield(k, 'kern', -getfield(a, 'height')+getfield(p, 'height'))
403       setfield(a, 'head', k); insert_before(r, r, k)
404       setfield(a, 'height', getfield(p, 'height'))
405    end
406
407    return a, getfield(r, 'width'), post_intrusion
408 end
409
410
411 -- High-level routine in pre_linebreak_filter
412 local post_intrusion_backup
413 local max_allow_pre, max_allow_post
414
415
416 -- 中付き熟語ルビ,cmp containers
417 -- 「文字の構成を考えた」やつはどうしよう
418 local pre_low_cal_box
419 do
420 local tmp_tbl = {}
421 pre_low_cal_box = function (w, cmp)
422    local rb = {}
423    local pb = {}
424    local kf = {}
425    -- kf[i] : container 1--i からなる行末形
426    -- kf[cmp+i] : container i--cmp からなる行頭形
427    -- kf[2cmp+1] : 行中形
428    local wv = getfield(w, 'value')
429    local mdt -- nt*: node temp
430    local coef = {} -- 連立一次方程式の拡大係数行列
431    local rtb = expand_3bits(has_attr(wv, attr_ruby_stretch))
432    tmp_tbl.rgap = has_attr(wv, attr_ruby_intergap)
433    tmp_tbl.imode = floor(has_attr(wv, attr_ruby_mode)/4)
434    tmp_tbl.bheight = has_attr(wv, attr_ruby_baseheight)
435
436    -- node list 展開・行末形の計算
437    local nt, nta, ntb = wv, nil, nil -- nt*: node temp
438    tmp_tbl.ppre, tmp_tbl.pmid, tmp_tbl.ppost = rtb[6], rtb[5], rtb[4]
439    tmp_tbl.mapre, tmp_tbl.mapost = max_allow_pre, 0
440    for i = 1, cmp do
441       nt = node_next(nt); rb[i] = nt; nta = concat(nta, node_copy(nt))
442       nt = node_next(nt); pb[i] = nt; ntb = concat(ntb, node_copy(nt))
443       coef[i] = {}
444       for j = 1, 2*i do coef[i][j] = 1 end
445       for j = 2*i+1, 2*cmp+1 do coef[i][j] = 0 end
446       kf[i], coef[i][2*cmp+2]
447          = new_ruby_box(node_copy(nta), node_copy(ntb), tmp_tbl)
448    end
449    node_free(nta); node_free(ntb)
450
451    -- 行頭形の計算
452    local nta, ntb = nil, nil
453    tmp_tbl.ppre, tmp_tbl.pmid, tmp_tbl.ppost = rtb[9], rtb[8], rtb[7]
454    tmp_tbl.mapre, tmp_tbl.mapost = 0, max_allow_post
455    for i = cmp,1,-1 do
456       coef[cmp+i] = {}
457       for j = 1, 2*i-1 do coef[cmp+i][j] = 0 end
458       for j = 2*i, 2*cmp+1 do coef[cmp+i][j] = 1 end
459       nta = concat(node_copy(rb[i]), nta); ntb = concat(node_copy(pb[i]), ntb)
460       kf[cmp+i], coef[cmp+i][2*cmp+2]
461          = new_ruby_box(node_copy(nta), node_copy(ntb), tmp_tbl)
462    end
463
464    -- ここで,nta, ntb には全 container を連結した box が入っているので
465    -- それを使って行中形を計算する.
466    coef[2*cmp+1] = {}
467    for j = 1, 2*cmp+1 do coef[2*cmp+1][j] = 1 end
468    tmp_tbl.ppre, tmp_tbl.pmid, tmp_tbl.ppost = rtb[3], rtb[2], rtb[1]
469    tmp_tbl.mapre, tmp_tbl.mapost = max_allow_pre, max_allow_post
470    kf[2*cmp+1], coef[2*cmp+1][2*cmp+2], post_intrusion_backup
471       = new_ruby_box(nta, ntb, tmp_tbl)
472
473    -- w.value の node list 更新.
474    local nt = wv
475    node.direct.flush_list(node_next(wv))
476    for i = 1, 2*cmp+1 do setfield(nt, 'next', kf[i]); nt = kf[i]  end
477
478    if cmp==1 then     solve_1(coef)
479    elseif cmp==2 then solve_2(coef)
480    else
481       gauss(coef) -- 掃きだし法で連立方程式形 coef を解く
482    end
483    return coef
484 end
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 get_around_skip
531 do
532 local KANJI_SKIP      = luatexja.icflag_table.KANJI_SKIP
533 local XKANJI_SKIP_JFM = luatexja.icflag_table.XKANJI_SKIP_JFM
534 local getprev = node.direct.getprev
535 local getnext = node.direct.getnext
536 get_around_skip = function(head, n)
537     local p = getprev(n)
538     luatexja.ext_show_node(node.direct.tonode(p), 'B> ', print)
539     if getid(p)==id_glue then
540         local pi = get_attr_icflag(p)
541         if pi>=KANJI_SKIP and pi<=XKANJI_SKIP_JFM then
542             print(n, 'before ' .. luatexja.print_scaled(getfield(p, 'width')))
543         end
544     end
545     p = getnext(n)
546     luatexja.ext_show_node(node.direct.tonode(p), 'A> ', print)
547     if getid(p)==id_glue then
548         local pi = get_attr_icflag(p)
549         if pi>=KANJI_SKIP and pi<=XKANJI_SKIP_JFM then
550             print(n, 'after  ' .. luatexja.print_scaled(getfield(p, 'width')))
551         end
552     end
553 end
554 end
555
556 local function pre_high(ahead)
557    if not ahead then return ahead end
558    local head = to_direct(ahead)
559    post_intrusion_backup = 0
560    local n = first_whatsit(head)
561    while n do
562       if getsubtype(n) == sid_user and getfield(n, 'user_id') == RUBY_PRE then
563         local around_skip = get_around_skip(head, n) 
564         local nv = getfield(n, 'value')
565          max_allow_pre = has_attr(nv, attr_ruby_maxprep) or 0
566          local atr = has_attr(n, attr_ruby) or 0
567          if max_allow_pre < 0 then
568             if atr>0 then
569                -- 直前のルビで intrusion がおこる可能性あり.
570                -- 前 run のデータが残っていればそれを使用,
571                -- そうでなければ行中形のデータを利用する
572                local op = old_break_info[atr] or post_intrusion_backup
573                max_allow_pre = max(0, -max_allow_pre - op)
574             else
575                max_allow_pre = -max_allow_pre
576             end
577          end
578          post_intrusion_backup = 0
579          max_allow_post = has_attr(nv, attr_ruby_maxpostp) or 0
580          max_margin = has_attr(nv, attr_ruby_maxmargin) or 0
581          local coef = pre_low_cal_box(n, getfield(nv, 'value'))
582          local s = node_tail(nv) --ルビ文字
583          head, n = pre_low_app_node(
584             head, n, getfield(nv, 'value'), coef,
585             getfield(s, 'height'), getfield(s, 'depth')
586          )
587       else
588          n = first_whatsit(node_next(n))
589       end
590    end
591    return to_node(head)
592 end
593 luatexbase.add_to_callback('pre_linebreak_filter', pre_high, 'ltj.ruby.pre', 100)
594 luatexbase.add_to_callback('hpack_filter', pre_high, 'ltj.ruby.pre', 100)
595
596 ----------------------------------------------------------------
597 -- post_line_break
598 ----------------------------------------------------------------
599 local post_lown
600 do
601    local function write_aux(wv, num)
602       local id = has_attr(wv, attr_ruby_id)
603       if id>0 and cache_handle then
604          cache_handle:write(
605             'lrob[' .. tostring(id) .. ']=' .. num .. '\n')
606       end
607    end
608
609    post_lown = function (rs, rw, cmp, ch)
610       -- ch: the head of `current' hlist
611       if #rs ==0 or not rw then return ch end
612       local hn = has_attr(rs[1], attr_ruby)
613       local fn = has_attr(rs[#rs], attr_ruby)
614       local wv = getfield(rw, 'value')
615       if hn==1 then
616          if fn==2*cmp+2 then
617             local hn = node_tail(wv)
618             node_remove(wv, hn)
619             insert_after(ch, rs[1], hn)
620             set_attr(hn, attr_icflag,  PROCESSED)
621             write_aux(wv, has_attr(hn, attr_ruby))-- 行中形
622          else
623             local deg, hn = (fn-1)/2, wv
624             for i = 1, deg do hn = node_next(hn) end;
625             node_remove(wv, hn)
626             setfield(hn, 'next', nil)
627             insert_after(ch, rs[1], hn)
628             set_attr(hn, attr_icflag,  PROCESSED)
629             write_aux(wv, has_attr(hn, attr_ruby))
630          end
631       else
632          local deg, hn = max((hn-1)/2,2), wv
633          for i = 1, cmp+deg-1 do hn = node_next(hn) end
634          -- -1 is needed except the case hn = 3,
635          --   because a ending-line form is removed already from the list
636          node_remove(wv, hn); setfield(hn, 'next', nil)
637          insert_after(ch, rs[1], hn)
638          set_attr(hn, attr_icflag,  PROCESSED)
639          if fn == 2*cmp-1 then
640             write_aux(wv, has_attr(hn, attr_ruby))
641          end
642       end
643       for i = 1,#rs do
644          local ri = rs[i]
645          ch = node_remove(ch, ri); node_free(ri);
646       end
647       -- cleanup
648       if fn >= 2*cmp+1 then node_free(rw) end
649       return ch;
650    end
651 end
652
653 local function post_high_break(head)
654    local rs = {}   -- rs: sequence of ruby_nodes,
655    local rw = nil  -- rw: main whatsit
656    local cmp = -2  -- dummy
657    for h in node.direct.traverse_id(id_hlist, to_direct(head)) do
658       for i = 1, #rs do rs[i] = nil end
659       local ha = getlist(h)
660       while ha do
661          local hai = getid(ha)
662          local i = ((hai == id_glue and getsubtype(ha)==0)
663                        or (hai == id_rule and getsubtype(ha)==0)
664                        or (hai == id_whatsit and getsubtype(ha)==sid_user
665                               and getfield(ha, 'user_id', RUBY_POST)))
666             and has_attr(ha, attr_ruby) or 0
667          if i==0 then
668             ha = node_next(ha)
669          elseif i==1 then
670             setfield(h, 'head', post_lown(rs, rw, cmp, getlist(h)))
671             for i = 2, #rs do rs[i] = nil end -- rs[1] is set by the next statement
672             rs[1], rw = ha, nil; ha = node_next(ha)
673          elseif i==2 then
674             rw = ha
675             cmp = getfield(getfield(rw, 'value'), 'value')
676             local hb, hc =  node_remove(getlist(h), rw)
677             setfield(h, 'head', hb); ha = hc
678          else -- i>=3
679             rs[#rs+1] = ha; ha = node_next(ha)
680          end
681       end
682       setfield(h, 'head', post_lown(rs, rw, cmp, getlist(h)))
683    end
684    return head
685 end
686
687 local function post_high_hbox(ahead)
688    local ha = to_direct(ahead); local head = ha
689    local rs = {};  -- rs: sequence of ruby_nodes,
690    local rw = nil; -- rw: main whatsit
691    local cmp
692    while ha do
693       local hai = getid(ha)
694       local i = ((hai == id_glue and getsubtype(ha)==0)
695                     or (hai == id_rule and getsubtype(ha)==0)
696                     or (hai == id_whatsit and getsubtype(ha)==sid_user
697                            and getfield(ha, 'user_id', RUBY_POST)))
698          and has_attr(ha, attr_ruby) or 0
699       if i==0 then
700          ha = node_next(ha)
701       elseif i==1 then
702          head = post_lown(rs, rw, cmp, head)
703          for i = 2, #rs do rs[i] = nil end -- rs[1] is set by the next statement
704          rs[1], rw = ha, nil; ha = node_next(ha)
705       elseif i==2 then
706          rw = ha
707          cmp = getfield(getfield(rw, 'value'), 'value')
708          head, ha = node_remove(head, rw)
709       else -- i >= 3
710          rs[#rs+1] = ha; ha = node_next(ha)
711       end
712    end
713    return to_node(post_lown(rs, rw, cmp, head))
714 end
715
716 luatexbase.add_to_callback('post_linebreak_filter', post_high_break, 'ltj.ruby.post_break', 100)
717 luatexbase.add_to_callback('hpack_filter', post_high_hbox, 'ltj.ruby.post_hbox', 101)
718
719
720 ----------------------------------------------------------------
721 -- for jfmglue callbacks
722 ----------------------------------------------------------------
723 do
724    local RIPRE  = luatexja.stack_table_index.RIPRE
725    local function whatsit_callback(Np, lp, Nq)
726       if Np.nuc then return Np
727       elseif  getfield(lp, 'user_id') == RUBY_PRE then
728          Np.first, Np.nuc, Np.last = lp, lp, lp
729          local lpv = getfield(lp, 'value')
730          local x = node_next(node_next(lpv))
731          Np.last_char = luatexja.jfmglue.check_box_high(Np, getlist(x), nil)
732          if Nq.id ~=id_pbox_w then
733             if type(Nq.char)=='number' then
734                -- Nq is a JAchar
735                if has_attr(lpv, attr_ruby_maxprep) < 0 then -- auto
736                   local p = round((ltjs.table_current_stack[RIPRE + Nq.char] or 0)
737                                      *has_attr(lpv, attr_ruby))
738                   if has_attr(lpv, attr_ruby_mode)%2 == 0 then -- intrusion 無効
739                      p = 0
740                   end
741                   set_attr(lpv, attr_ruby_maxprep, -p)
742                end
743                if Nq.prev_ruby then
744                   set_attr(lp, attr_ruby, Nq.prev_ruby)
745                end
746             elseif has_attr(lpv, attr_ruby_maxprep) < 0 then -- auto
747                if Nq.char == 'parbdd' then
748                   local p = round((ltjs.table_current_stack[RIPRE-1] or 0)
749                                      *has_attr(lpv, attr_ruby))
750                   p = min(p, Nq.width)
751                  if has_attr(lpv, attr_ruby_mode)%2 == 0 then -- intrusion 無効
752                      p = 0
753                   end
754                   set_attr(lpv, attr_ruby_maxprep, p)
755                else
756                   set_attr(lpv, attr_ruby_maxprep, 0)
757                end
758             end
759          elseif has_attr(lpv, attr_ruby_maxprep) < 0 then -- auto
760             set_attr(lpv, attr_ruby_maxprep, 0)
761          end
762          return Np
763       else
764         return Np
765       end
766    end
767    luatexbase.add_to_callback("luatexja.jfmglue.whatsit_getinfo", whatsit_callback,
768                               "luatexja.ruby.np_info", 1)
769 end
770
771 do
772    local RIPOST = luatexja.stack_table_index.RIPOST
773    local function whatsit_after_callback(s, Nq, Np)
774       if not s and  getfield(Nq.nuc, 'user_id') == RUBY_PRE then
775          if Np then
776             local last_glue = node_new(id_glue)
777             set_attr(last_glue, attr_icflag, 0)
778             insert_before(Nq.nuc, Np.first, last_glue)
779             Np.first = last_glue
780             next_cluster_array[Nq.nuc] = last_glue -- ルビ処理用のグルー
781          end
782          local nqnv = getfield(Nq.nuc, 'value')
783          local x =  node_next(node_next(nqnv))
784          for i = 2, getfield(nqnv, 'value') do x = node_next(node_next(x)) end
785          Nq.last_char = luatexja.jfmglue.check_box_high(Nq, getlist(x), nil)
786          luatexja.jfmglue.after_hlist(Nq)
787          if Np and Np.id ~=id_pbox_w and type(Np.char)=='number' then
788             -- Np is a JAchar
789             local rm = has_attr(nqnv, attr_ruby_mode)
790             if has_attr(nqnv, attr_ruby_maxpostp) < 0 then -- auto
791                local p = round((ltjs.table_current_stack[RIPOST + Np.char] or 0)
792                                   *has_attr(nqnv, attr_ruby))
793                if rm%2 == 0 then -- intrusion 無効
794                   p = 0
795                end
796                if rm%4 >= 2 then
797                   local q = has_attr(nqnv, attr_ruby_maxprep)
798                   if q < p then p = q
799                   elseif q > p then
800                      set_attr(nqnv, attr_ruby_maxprep, p)
801                   end
802                end
803                set_attr(nqnv, attr_ruby_maxpostp, p)
804             end
805             Np.prev_ruby = has_attr(getfield(Nq.nuc, 'value'), attr_ruby_id)
806             -- 前のクラスタがルビであったことのフラグ
807          else -- 直前が文字以外
808             local nqnv = getfield(Nq.nuc, 'value')
809             if has_attr(nqnv, attr_ruby_maxpostp) < 0 then -- auto
810                set_attr(nqnv, attr_ruby_maxpostp, 0)
811                if has_attr(nqnv, attr_ruby_mode)%4 >= 2 then
812                   set_attr(nqnv, attr_ruby_maxprep, 0)
813                end
814             end
815          end
816          return true
817       else
818          return s
819       end
820    end
821    luatexbase.add_to_callback("luatexja.jfmglue.whatsit_after", whatsit_after_callback,
822                               "luatexja.ruby.np_info_after", 1)
823 end
824