OSDN Git Service

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