OSDN Git Service

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