OSDN Git Service

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