OSDN Git Service

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