OSDN Git Service

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