OSDN Git Service

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