OSDN Git Service

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