OSDN Git Service

Updated ltj[s]classes.pdf etc.
[luatex-ja/luatexja.git] / src / ltj-direction.lua
1 --
2 -- src/ltj-direction.lua
3 --
4
5 luatexja.load_module('base');      local ltjb = luatexja.base
6 luatexja.load_module('stack');     local ltjs = luatexja.stack
7 luatexja.load_module('rmlgbm');    local ltjr = luatexja.rmlgbm
8 luatexja.direction = {}
9
10 local attr_dir = luatexbase.attributes['ltj@dir']
11 local attr_icflag = luatexbase.attributes['ltj@icflag']
12
13 local cat_lp = luatexbase.catcodetables['latex-package']
14 local Dnode = node.direct or node
15 local nullfunc = function (n) return n end
16 local to_node = (Dnode ~= node) and Dnode.tonode or nullfunc
17 local to_direct = (Dnode ~= node) and Dnode.todirect or nullfunc
18 local has_attr = Dnode.has_attribute
19 local set_attr = Dnode.set_attribute
20 local insert_before = Dnode.insert_before
21 local insert_after = Dnode.insert_after
22 local getid = (Dnode ~= node) and Dnode.getid or function(n) return n.id end
23 local getsubtype = (Dnode ~= node) and Dnode.getsubtype or function(n) return n.subtype end
24 local getlist = (Dnode ~= node) and Dnode.getlist or function(n) return n.head end
25 local setfield = (Dnode ~= node) and Dnode.setfield or function(n, i, c) n[i] = c end
26 local getfield = (Dnode ~= node) and Dnode.getfield or function(n, i) return n[i] end
27 local node_new = Dnode.new
28 local node_tail = Dnode.tail
29 local node_free = Dnode.free
30 local node_remove = Dnode.remove
31 local node_next = (Dnode ~= node) and Dnode.getnext or node.next
32 local traverse = Dnode.traverse
33 local traverse_id = Dnode.traverse_id
34 local start_time_measure, stop_time_measure 
35    = ltjb.start_time_measure, ltjb.stop_time_measure
36
37 local id_kern = node.id('kern')
38 local id_hlist = node.id('hlist')
39 local id_vlist = node.id('vlist')
40 local id_whatsit = node.id('whatsit')
41 local sid_save = node.subtype('pdf_save')
42 local sid_restore = node.subtype('pdf_restore')
43 local sid_matrix = node.subtype('pdf_setmatrix')
44 local sid_user = node.subtype('user_defined')
45
46 local tex_nest = tex.nest
47 local tex_getcount = tex.getcount
48 local tex_set_attr = tex.setattribute
49 local PROCESSED    = luatexja.icflag_table.PROCESSED
50 local PROCESSED_BEGIN_FLAG = luatexja.icflag_table.PROCESSED_BEGIN_FLAG
51 local PACKED       = luatexja.icflag_table.PACKED
52 local STCK = luatexja.userid_table.STCK
53 local DIR  = luatexja.userid_table.DIR
54 local dir_tate = luatexja.dir_table.dir_tate
55 local dir_yoko = luatexja.dir_table.dir_yoko
56 local dir_dtou = luatexja.dir_table.dir_dtou
57 local dir_node_auto   = luatexja.dir_table.dir_node_auto
58 local dir_node_manual = luatexja.dir_table.dir_node_manual
59
60 local page_direction
61 --
62 local function adjust_badness(hd)
63    if not node_next(hd) and getid(hd)==id_whatsit and getsubtype(hd)==sid_user
64    and getfield(hd, 'user_id')==DIR then
65       -- avoid double whatsit
66       luatexja.global_temp=tex.globaldefs; tex.globaldefs=0
67       luatexja.hbadness_temp=tex.hbadness; tex.hbadness=10000
68       luatexja.vbadness_temp=tex.vbadness; tex.vbadness=10000
69    else
70       luatexja.global_temp = nil
71       luatexja.hbadness_temp=nil
72       luatexja.vbadness_temp=nil
73    end
74 end
75
76 local get_dir_count, get_adjust_dir_count
77 do
78    local function get_dir_count_inner(h)
79       if h then
80          if h.id==id_whatsit and h.subtype==sid_user and h.user_id==DIR then
81                local ic = node.has_attribute(h, attr_icflag)
82                return (ic<PROCESSED_BEGIN_FLAG) 
83                   and (node.has_attribute(h,attr_dir)%dir_node_auto) or 0
84          else
85             return 0
86          end
87       else
88          return 0
89       end
90    end
91    function get_dir_count()
92       for i=tex_nest.ptr, 1, -1 do
93          local h = tex_nest[i].head.next
94          --luatexja.ext_show_node_list(h, 'GDR'..  i .. '> ', print)
95          if h then
96             local t = get_dir_count_inner(h)
97             if t~=0 then return t end
98          end
99       end
100       return page_direction
101    end
102    local abs = math.abs
103    function get_adjust_dir_count()
104       for i=tex_nest.ptr, 1, -1 do
105          local v = tex_nest[i]
106          local h, m = v.head.next, v.mode
107          if abs(m)== ltjs.vmode and h then
108             local t = get_dir_count_inner(h)
109             if t~=0 then return t end
110          end
111       end
112       return page_direction
113    end
114    luatexja.direction.get_dir_count = get_dir_count
115    luatexja.direction.get_adjust_dir_count = get_adjust_dir_count
116 end
117
118
119 -- \tate, \yoko
120 do
121    local node_next = node.next
122    local node_set_attr = node.set_attribute
123    local function set_list_direction(v, name)
124       local lv, w = tex_nest.ptr, tex.lists.page_head
125       if not v then 
126          v,name  = get_dir_count(), nil 
127       elseif v=='adj' then
128          v,name = get_adjust_dir_count(), nil
129       end
130       if tex.currentgrouptype==6 then
131          ltjb.package_error(
132                  'luatexja',
133                  "You can't use `\\" .. name .. "' in an align",
134                  "To change direction in an align, \n"
135                     .. "you shold use \\hbox or \\vbox.")
136       else
137          local w = (lv==0) and tex.lists.page_head or tex_nest[lv].head.next
138          if w then
139             if (not w.next) and 
140                w.id==id_whatsit and w.subtype==sid_user and w.user_id==DIR then
141                node_set_attr(w, attr_dir, v)
142                if lv==0 then page_direction = v end
143             elseif lv==0 and not page_direction then
144                page_direction = v -- for first call of \yoko (in luatexja-core.sty)
145             else
146               ltjb.package_error(
147                  'luatexja',
148                  "Use `\\" .. name .. "' at top of list",
149                  'Direction change command by LuaTeX-ja is available\n'
150                     .. 'only when the current list is null.')
151             end
152          else
153             local w = node_new(id_whatsit, sid_user)
154             setfield(w, 'next', nil)
155             setfield(w, 'user_id', DIR)
156             setfield(w, 'type', 110)
157             set_attr(w, attr_dir, v)
158             Dnode.write(w)
159             if lv==0 then page_direction = v end
160          end
161          tex_set_attr('global', attr_icflag, 0)
162       end
163       tex_set_attr('global', attr_dir, 0)
164    end
165    luatexja.direction.set_list_direction = set_list_direction
166 end
167
168 -- ボックスに dir whatsit を追加
169 local function create_dir_whatsit(hd, gc, new_dir)
170    if getid(hd)==id_whatsit and 
171             getsubtype(hd)==sid_user and getfield(hd, 'user_id')==DIR then
172       set_attr(hd, attr_icflag, 
173                (has_attr(hd, attr_icflag) or 0)%PROCESSED_BEGIN_FLAG 
174                   + PROCESSED_BEGIN_FLAG)
175       tex_set_attr('global', attr_icflag, 0)
176       return hd
177    else
178       local w = node_new(id_whatsit, sid_user)
179       setfield(w, 'next', hd)
180       setfield(w, 'user_id', DIR)
181       setfield(w, 'type', 110)
182       set_attr(w, attr_dir, new_dir)
183       set_attr(w, attr_icflag, PROCESSED_BEGIN_FLAG)
184       set_attr(hd, attr_icflag, 
185                (has_attr(hd, attr_icflag) or 0)%PROCESSED_BEGIN_FLAG 
186                   + PROCESSED_BEGIN_FLAG)
187       tex_set_attr('global', attr_dir, 0)
188       tex_set_attr('global', attr_icflag, 0)
189       return w
190    end
191 end
192
193 -- hpack_filter, vpack_filter, post_line_break_filter
194 -- の結果を組方向を明示するため,先頭に dir_node を設置
195 do
196    local function create_dir_whatsit_hpack(h, gc)
197       local hd = to_direct(h)
198       if gc=='fin_row' or gc == 'preamble'  then
199          if hd  then
200             set_attr(hd, attr_icflag, PROCESSED_BEGIN_FLAG)
201             tex_set_attr('global', attr_icflag, 0)
202          end
203          return h
204       else
205          adjust_badness(hd)
206          return to_node(create_dir_whatsit(hd, gc, ltjs.list_dir))
207       end
208    end
209
210    luatexbase.add_to_callback('hpack_filter', 
211                               create_dir_whatsit_hpack, 'ltj.create_dir_whatsit', 10000)
212 end
213
214 do
215    local function create_dir_whatsit_parbox(h, gc)
216       stop_time_measure('tex_linebreak')
217       -- start 側は ltj-debug.lua に
218       local new_dir, hd = ltjs.list_dir, to_direct(h)
219       for line in traverse_id(id_hlist, hd) do
220          local nh = getlist(line)
221          setfield(line, 'head', create_dir_whatsit(nh, gc, new_dir) )
222          set_attr(line, attr_dir, new_dir)
223       end
224       tex_set_attr('global', attr_dir, 0)
225       return h 
226    end
227    luatexbase.add_to_callback('post_linebreak_filter', 
228                               create_dir_whatsit_parbox, 'ltj.create_dir_whatsit', 10000)
229 end
230
231 local create_dir_whatsit_vbox
232 do
233    local wh = {}
234    local id_glue, sid_parskip = node.id('glue'), 3
235    create_dir_whatsit_vbox = function (hd, gc)
236       ltjs.list_dir = get_dir_count()
237       -- remove dir whatsit
238       for x in traverse_id(id_whatsit, hd) do
239          if getsubtype(x)==sid_user and getfield(x, 'user_id')==DIR then
240             wh[#wh+1]=x
241          end
242       end
243       if hd==wh[1] then
244          ltjs.list_dir =has_attr(hd,attr_dir)
245          local x = node_next(hd)
246          if getid(x)==id_glue and getsubtype(x)==sid_parskip then
247             node_remove(hd,x); node_free(x)
248          end
249       end
250       for i=1,#wh do  
251          hd = node_remove(hd, wh[i]); node_free(wh[i]); wh[i] = nil 
252       end
253       if gc=='fin_row' or gc == 'preamble'  then
254          if hd  then
255             set_attr(hd, attr_icflag, PROCESSED_BEGIN_FLAG)
256             tex_set_attr('global', attr_icflag, 0)
257          end
258          return hd
259       else
260          local n =node_next(hd)
261          if gc=='vtop' then
262             local w = create_dir_whatsit(hd, gc, ltjs.list_dir)
263             -- move  dir whatsit after hd
264             setfield(hd, 'next', w); setfield(w, 'next', n)
265             return hd
266          else
267             hd = create_dir_whatsit(hd, gc, ltjs.list_dir)
268             return hd
269          end
270       end
271    end
272 end
273
274 -- dir_node に包む方法を書いたテーブル
275 local dir_node_aux
276 do
277    local get_h =function (w,h,d) return h end
278    local get_d =function (w,h,d) return d end
279    local get_h_d =function (w,h,d) return h+d end
280    local get_h_d_neg =function (w,h,d) return -h-d end
281    local get_h_neg =function (w,h,d) return -h end
282    local get_d_neg =function (w,h,d) return -d end
283    local get_w_half =function (w,h,d) return 0.5*w end
284    local get_w_neg_half =function (w,h,d) return -0.5*w end
285    local get_w_neg =function (w,h,d) return -w end
286    local get_w =function (w,h,d) return w end
287    local zero = function() return 0 end
288    dir_node_aux = {
289       [dir_yoko] = { -- yoko を 
290          [dir_tate] = { -- tate 中で組む
291             width  = get_h_d,
292             height = get_w_half,
293             depth  = get_w_half,
294             [id_hlist] = {
295                { 'whatsit', sid_save },
296                { 'rotate', '0 1 -1 0' },
297                { 'kern', get_w_neg_half },
298                { 'box' , get_h },
299                { 'kern', get_w_neg_half },
300                { 'whatsit', sid_restore },
301             },
302             [id_vlist] = {
303                { 'whatsit', sid_save },
304                { 'rotate', '0 1 -1 0' },
305                { 'kern' , zero },
306                { 'box' , get_w_neg },
307                { 'kern', get_h_d_neg},
308                { 'whatsit', sid_restore },
309             },
310          },
311          [dir_dtou] = { -- dtou 中で組む
312             width  = get_h_d,
313             height = get_w,
314             depth  = zero,
315             [id_hlist] = {
316                { 'whatsit', sid_save },
317                { 'rotate', '0 -1 1 0' },
318                { 'kern', get_w_neg },
319                { 'box', get_d_neg },
320                { 'whatsit', sid_restore },
321             },
322             [id_vlist] = {
323                { 'whatsit', sid_save },
324                { 'rotate', '0 -1 1 0' },
325                { 'kern', get_h_d_neg },
326                { 'box', zero },
327                { 'whatsit', sid_restore },
328             },
329          },
330       },
331       [dir_tate] = { -- tate を
332          [dir_yoko] = { -- yoko 中で組む
333             width  = get_h_d,
334             height = get_w,
335             depth  = zero,
336             [id_hlist] = {
337                { 'whatsit', sid_save },
338                { 'rotate', '0 -1 1 0' },
339                { 'kern', get_w_neg },
340                { 'box' , get_d_neg },
341                { 'whatsit', sid_restore },
342             },
343             [id_vlist] = {
344                { 'whatsit', sid_save },
345                { 'rotate', '0 -1 1 0' },
346                { 'kern', get_h_d_neg },
347                { 'box', zero },
348                { 'whatsit', sid_restore },
349             },
350          },
351          [dir_dtou] = { -- dtou 中で組む
352             width  = get_w,
353             height = get_d,
354             depth  = get_h,
355             [id_hlist] = {
356                { 'whatsit', sid_save },
357                { 'rotate', '-1 0 0 -1' },
358                { 'kern', get_w_neg },
359                { 'box', zero },
360                { 'whatsit', sid_restore },
361             },
362             [id_vlist] = {
363                { 'whatsit', sid_save },
364                { 'rotate', '-1 0 0 -1' },
365                { 'kern', get_h_d_neg },
366                { 'box', get_w_neg },
367                { 'whatsit', sid_restore },
368             },
369          },
370       },
371       [dir_dtou] = { -- dtou を
372          [dir_yoko] = { -- yoko 中で組む
373             width  = get_h_d,
374             height = get_w, 
375             depth  = zero,
376             [id_hlist] = {
377                { 'whatsit', sid_save },
378                { 'rotate', '0 1 -1 0' },
379                { 'kern', zero },
380                { 'box', get_h },
381                { 'kern', get_w_neg },
382                { 'whatsit', sid_restore },
383             },
384             [id_vlist] = {
385                { 'kern', zero },
386                { 'whatsit', sid_save },
387                { 'rotate', '0 1 -1 0' },
388                { 'box', get_w_neg },
389                { 'kern', get_h_d_neg },
390                { 'whatsit', sid_restore },
391             },
392          },
393          [dir_tate] = { -- tate 中で組む
394             width  = get_w,
395             height = get_d,
396             depth  = get_h,
397             [id_hlist] = {
398                { 'whatsit', sid_save },
399                { 'rotate', '-1 0 0 -1' },
400                { 'kern', get_w_neg },
401                { 'box', zero },
402                { 'whatsit', sid_restore },
403             },
404             [id_vlist] = {
405                { 'whatsit', sid_save },
406                { 'rotate', ' -1 0 0 -1' },
407                { 'kern', get_h_d_neg }, 
408                { 'box', get_w_neg },
409                { 'whatsit', sid_restore },
410             },
411          },
412       },
413    }
414 end
415
416 -- 1st ret val: b の組方向
417 -- 2nd ret val はその DIR whatsit
418 local function get_box_dir(b, default)
419    start_time_measure('get_box_dir')
420    local dir = has_attr(b, attr_dir) or 0
421    local bh = getfield(b,'head') 
422    -- b は insert node となりうるので getlist() は使えない
423    local c
424    for i=1,2 do
425       if bh and getid(bh)==id_whatsit
426       and getsubtype(bh)==sid_user and getfield(bh, 'user_id')==DIR then
427          c = bh
428          dir = (dir==0) and has_attr(bh, attr_dir) or dir
429       end
430       bh = node_next(bh)
431    end
432    stop_time_measure('get_box_dir')
433    return (dir==0 and default or dir), c
434 end
435
436 do
437    local getbox = tex.getbox
438    local function check_dir(reg_num)
439       start_time_measure('box_primitive_hook')
440       local list_dir = get_dir_count()
441       local b = tex.getbox(tex_getcount('ltj@tempcnta'))
442       if b then
443          local box_dir = get_box_dir(to_direct(b), dir_yoko)
444          if box_dir%dir_node_auto ~= list_dir%dir_node_auto then
445             print('NEST', tex_nest.ptr, tex_getcount('ltj@tempcnta'))
446             luatexja.ext_show_node_list(
447                (tex_nest.ptr==0) and tex.lists.page_head or tex_nest[tex_nest.ptr].head,
448                'LIST' .. tostring(list_dir) .. '> ', print)
449             luatexja.ext_show_node_list(b, 'BOX' .. tostring(box_dir) .. '> ', print)
450             ltjb.package_error(
451                'luatexja',
452                "Incompatible direction list can't be unboxed",
453                'I refuse to unbox a box in differrent direction.')
454          end
455       end
456       tex.globaldefs = luatexja.global_temp
457       stop_time_measure('box_primitive_hook')
458    end
459    luatexja.direction.check_dir = check_dir
460 end
461
462 -- dir_node に包まれている「本来の中身」を取り出し,
463 -- dir_node を全部消去
464 local function unwrap_dir_node(b, head, box_dir)
465    -- b: dir_node, head: the head of list, box_dir: 
466    -- return values are (new head), (next of b), (contents), (dir of contents)
467    local bh = getlist(b)
468    local bc = node_next(node_next(node_next(bh)))
469    local nh, nb
470    node_remove(bh, bc); 
471    Dnode.flush_list(bh)
472    if head then
473       nh = insert_before(head, b, bc)
474       nh, nb = node_remove(nh, b)
475       setfield(b, 'next', nil)
476       setfield(b, 'head', nil)
477       node_free(b)
478    end
479    local shift_old, b_dir, wh = nil, get_box_dir(bc, 0)
480    if wh then
481       Dnode.flush_list(getfield(wh, 'value'))
482       setfield(wh, 'value', nil)
483    end
484    -- recalc. info
485    local info = dir_node_aux[b_dir][box_dir%dir_node_auto][getid(bc)]
486    for _,v in ipairs(info) do 
487       if v[1]=='box' then
488          shift_old = v[2](
489             getfield(bc,'width'), getfield(bc, 'height'), getfield(bc, 'depth'))
490          break
491       end
492    end
493    setfield(bc, 'shift', getfield(bc, 'shift') - shift_old)
494    return nh, nb, bc, b_dir
495 end
496
497 -- is_manual: 寸法変更に伴うものか?
498 local function create_dir_node(b, b_dir, new_dir, is_manual)
499    --print('create new node', b_dir, new_dir)
500    local info = dir_node_aux[b_dir][new_dir]
501    local w = getfield(b, 'width')
502    local h = getfield(b, 'height')
503    local d = getfield(b, 'depth')
504    local db = node_new(getid(b)) -- dir_node
505    set_attr(db, attr_dir, 
506             new_dir + (is_manual and dir_node_manual or dir_node_auto))
507    set_attr(db, attr_icflag, PROCESSED)
508    set_attr(b, attr_icflag, PROCESSED)
509    tex_set_attr('global', attr_dir, 0)
510    tex_set_attr('global', attr_icflag, 0)
511    setfield(db, 'dir', getfield(b, 'dir'))
512    setfield(db, 'shift', 0)
513    setfield(db, 'width',  info.width(w,h,d))
514    setfield(db, 'height', info.height(w,h,d))
515    setfield(db, 'depth',  info.depth(w,h,d))
516    return db
517 end
518
519 -- 異方向のボックスの処理
520 local make_dir_whatsit, process_dir_node
521 do
522    make_dir_whatsit = function (head, b, new_dir, origin)
523       -- head: list head, b: box
524       -- origin: コール元 (for debug)
525       -- return value: (new head), (next of b), (new b), (is_b_dir_node)
526       -- (new b): b か dir_node に被せられた b
527       local bh = getlist(b)
528       local box_dir, dn =  get_box_dir(b, ltjs.list_dir)
529       -- 既に b の中身にあるwhatsit
530
531       if box_dir==new_dir then
532          -- 組方向が一緒のボックスなので,何もしなくて良い
533          return head, node_next(b), b, false
534       elseif  box_dir%dir_node_auto == new_dir  then
535          -- dir_node としてカプセル化されている
536          local bc = node_next(node_next(node_next(bh)))
537          local _, dnc = get_box_dir(b, 0)
538          if dnc then -- free all other dir_node
539             Dnode.flush_list(getfield(dnc, 'value'))
540             setfield(dnc, 'value', nil)
541          end
542          set_attr(b, attr_dir, box_dir%dir_node_auto + dir_node_auto)
543          return head, node_next(b), b, true
544       else
545          --luatexja.ext_show_node_list(to_node(b), 'mkd> ', print)
546          -- 組方向を合わせる必要あり
547          local nh, nb, ret, flag
548          if box_dir>= dir_node_auto then -- unwrap
549             local b_dir
550             head, nb, b, b_dir = unwrap_dir_node(b, head, box_dir)
551             bh = getlist(b)
552             if b_dir==new_dir then
553                -- dir_node の中身が周囲の組方向とあっている
554                return head, nb, b, false 
555             else box_dir = b_dir end
556          end
557             local db
558             local dnh = getfield(dn, 'value')
559             for x in traverse(dnh) do
560                if has_attr(x, attr_dir)%dir_node_auto == new_dir then
561                   setfield(dn, 'value', to_node(node_remove(dnh, x)))
562                   db=x; break
563                end
564             end
565             Dnode.flush_list(dnh)
566             db = db or create_dir_node(b, box_dir, new_dir, false)
567             local w = getfield(b, 'width')
568             local h = getfield(b, 'height')
569             local d = getfield(b, 'depth')
570             nh, nb =  insert_before(head, b, db), nil
571             nh, nb = node_remove(nh, b)
572             local db_head, db_tail  = nil
573             for _,v in ipairs(dir_node_aux[box_dir][new_dir][getid(b)]) do
574                local cmd, arg, nn = v[1], v[2]
575                if cmd=='kern' then
576                   nn = node_new(id_kern)
577                   setfield(nn, 'kern', arg(w, h, d))
578                elseif cmd=='whatsit' then
579                   nn = node_new(id_whatsit, arg)
580                elseif cmd=='rotate' then
581                   nn = node_new(id_whatsit, sid_matrix)
582                   setfield(nn, 'data', arg)
583                elseif cmd=='box' then
584                   nn = b; setfield(b, 'next', nil)
585                   setfield(nn, 'shift', getfield(nn, 'shift') + arg(w,h,d))
586                end
587                if db_head then
588                   insert_after(db_head, db_tail, nn)
589                   db_tail = nn
590                else
591                   db_head, db_tail = nn, nn
592                end
593                setfield(db, 'head', db_head)
594                ret, flag = db, true
595          end
596          return nh, nb, ret, flag
597       end
598    end
599    process_dir_node = function (hd, gc)
600       local x, new_dir = hd, ltjs.list_dir or dir_yoko
601       while x do
602          local xid = getid(x)
603          if (xid==id_hlist and has_attr(x, attr_icflag)%PROCESSED_BEGIN_FLAG~=PACKED) 
604          or xid==id_vlist then
605             hd, x = make_dir_whatsit(hd, x, new_dir, 'process_dir_node:' .. gc)
606          else
607             x = node_next(x)
608          end
609       end
610       return hd
611    end
612
613    -- lastbox
614    local node_prev = (Dnode~=node) and Dnode.getprev or node.prev
615    local function lastbox_hook()
616       start_time_measure('box_primitive_hook')
617       local bn = tex_nest[tex_nest.ptr].tail
618       if bn then
619          local b, head = to_direct(bn), to_direct(tex_nest[tex_nest.ptr].head)
620          local bid = getid(b)
621          if bid==id_hlist or bid==id_vlist then
622             local box_dir =  get_box_dir(b, 0)
623             if box_dir>= dir_node_auto then -- unwrap dir_node
624                local p = node_prev(b)
625                local dummy1, dummy2, nb = unwrap_dir_node(b, nil, box_dir)
626                setfield(p, 'next', nb);  tex_nest[tex_nest.ptr].tail = to_node(nb)
627                setfield(b, 'next', nil); setfield(b, 'head', nil)
628                node_free(b); b = nb
629             end
630             local _, wh =  get_box_dir(b, 0) -- clean dir_node attached to the box
631             if wh then
632                Dnode.flush_list(getfield('value', wh))
633                setfield(wh, 'value', nil)
634             end
635          end
636       end
637       stop_time_measure('box_primitive_hook')
638    end
639
640    luatexja.direction.make_dir_whatsit = make_dir_whatsit
641    luatexja.direction.lastbox_hook = lastbox_hook
642 end
643
644 -- \wd, \ht, \dp の代わり
645 do
646    local getbox, setdimen = tex.getbox, tex.setdimen
647    local function get_box_dim_common(key, s, l_dir)
648       local s_dir, wh = get_box_dir(s, dir_yoko)
649       if s_dir ~= l_dir then
650          local not_found = true
651          for x in traverse(getfield(wh, 'value')) do
652             if l_dir == has_attr(x, attr_dir)%dir_node_auto then
653                setdimen('ltj@tempdima', getfield(x, key))
654                not_found = false; break
655             end
656          end
657          if not_found then
658             local w = getfield(s, 'width')
659             local h = getfield(s, 'height')
660             local d = getfield(s, 'depth')
661             setdimen('ltj@tempdima', 
662                          dir_node_aux[s_dir][l_dir][key](w,h,d))
663          end
664       else
665          setdimen('ltj@tempdima', getfield(s, key))
666       end
667    end
668    local function get_box_dim(key, n)
669       local gt = tex.globaldefs; tex.globaldefs = 0
670       local s = getbox(n)
671       if s then
672          local l_dir = get_dir_count()
673          s = to_direct(s)
674          local b_dir = get_box_dir(s,dir_yoko)
675          if b_dir<dir_node_auto then
676             get_box_dim_common(key, s, l_dir)
677          elseif b_dir%dir_node_auto==l_dir then
678             setdimen('ltj@tempdima', getfield(s, key))
679          else
680             get_box_dim_common(key, 
681                                node_next(node_next(node_next(getlist(s)))), l_dir)
682          end
683       else
684          setdimen('ltj@tempdima', 0)
685       end
686       tex.globaldefs = gt
687    end
688    luatexja.direction.get_box_dim = get_box_dim
689
690    -- return value: (changed dimen of box itself?)
691    local function set_box_dim_common(key, s, l_dir)
692       local s_dir, wh = get_box_dir(s, dir_yoko)
693       if s_dir ~= l_dir then
694          if not wh then
695             wh = create_dir_whatsit(getlist(s), 'set_box_dim', s_dir)
696             setfield(s, 'head', wh)
697          end
698          local db
699          local dnh = getfield(wh, 'value')
700          for x in traverse(dnh) do
701             if has_attr(x, attr_dir)%dir_node_auto==l_dir then
702                db = x; break
703             end
704          end
705          if not db then
706             db = create_dir_node(s, s_dir, l_dir, true)
707             setfield(db, 'next', dnh)
708             setfield(wh, 'value',to_node(db))
709          end
710          setfield(db, key, tex.getdimen('ltj@tempdima'))
711          return false
712       else
713          setfield(s, key, tex.getdimen('ltj@tempdima'))
714          if wh then
715             -- change dimension of dir_nodes which are created "automatically"
716                local bw, bh, bd 
717                   = getfield(s,'width'), getfield(s, 'height'), getfield(s, 'depth')
718             for x in traverse(getfield(wh, 'value')) do
719                local x_dir = has_attr(x, attr_dir)
720                if x_dir<dir_node_manual then
721                   local info = dir_node_aux[s_dir][x_dir%dir_node_auto]
722                   setfield(x, 'width',  info.width(bw,bh,bd))
723                   setfield(x, 'height', info.height(bw,bh,bd))
724                   setfield(x, 'depth',  info.depth(bw,bh,bd))
725                end
726             end
727          end
728          return true
729       end
730    end
731    local function set_box_dim(key)
732       local n = tex_getcount('ltj@tempcnta')
733       local s = getbox(n)
734       if s then
735          local l_dir = get_dir_count()
736          s = to_direct(s)
737          local b_dir = get_box_dir(s,dir_yoko)
738          if b_dir<dir_node_auto then
739             set_box_dim_common(key, s, l_dir)
740          elseif b_dir%dir_node_auto == l_dir then
741             -- s is dir_node
742             setfield(s, key, tex.getdimen('ltj@tempdima'))
743             if b_dir<dir_node_manual then
744                set_attr(s, attr_dir, b_dir%dir_node_auto + dir_node_manual)
745             end
746          else
747             local sid, sl = getid(s), getlist(s)
748             local b = node_next(node_next(node_next(sl)))
749             local info = dir_node_aux[get_box_dir(b,dir_yoko)][b_dir%dir_node_auto]
750             local shift_old
751             for _,v in ipairs(info[sid]) do 
752                if v[1]=='box' then
753                   shift_old = v[2](
754                      getfield(b,'width'), getfield(b, 'height'), getfield(b, 'depth'))
755                   break
756                end
757             end
758            if set_box_dim_common(key, b, l_dir) then
759                local bw, bh, bd 
760                   = getfield(b,'width'), getfield(b, 'height'), getfield(b, 'depth')
761                -- re-calculate shift
762                for i,v in ipairs(info[sid]) do 
763                   if getid(sl)==id_kern then
764                      setfield(sl, 'kern', v[2](bw,bh,bd) )
765                   elseif getid(sl)==sid then
766                      local d = getfield(sl, 'shift')
767                      setfield(sl, 'shift', 
768                               getfield(sl, 'shift') - shift_old + v[2](bw,bh,bd) )
769                   end
770                   sl = node_next(sl)
771                end
772                -- re-calculate dimension of s, if s is created "automatically"
773                if b_dir<dir_node_manual then
774                   setfield(s, 'width',  info.width(bw,bh,bd))
775                   setfield(s, 'height', info.height(bw,bh,bd))
776                   setfield(s, 'depth',  info.depth(bw,bh,bd))
777                end
778             end
779          end
780       end
781    end
782    luatexja.direction.set_box_dim = set_box_dim
783 end
784
785 do
786    local getbox = tex.getbox
787    local function get_register_dir(n)
788       local s = getbox(n)
789       if s then
790          s = to_direct(s)
791          local b_dir = get_box_dir(s, dir_yoko)
792          if b_dir<dir_node_auto then
793             return b_dir
794          else
795             local b_dir = get_box_dir(
796                node_next(node_next(node_next(getlist(s)))), dir_yoko)
797             return b_dir
798          end
799       else
800          return 0
801       end
802    end
803    luatexja.direction.get_register_dir = get_register_dir
804 end
805
806 -- 縦書き用字形への変換テーブル
807 local font_vert_table = {} -- key: fontnumber
808 do
809    local font_vert_basename = {} -- key: basename
810    local function add_feature_table(tname, src, dest)
811       for i,v in pairs(src) do
812          if type(v.slookups)=='table' then
813             local s = v.slookups[tname]
814             if s and not dest[i] then
815                dest[i] = s
816             end
817          end
818       end
819    end
820
821    local function prepare_vert_data(n, id)
822       -- test if already loaded
823       if type(id)=='number' then -- sometimes id is an integer
824          font_vert_table[n] = font_vert_table[id]; return
825       elseif (not id) or font_vert_table[n]  then return
826       end
827       local fname = id.filename
828       local bname = file.basename(fname)
829       if not fname then
830          font_vert_table[n] = {}; return
831       elseif font_vert_basename[bname] then
832          font_vert_table[n] = font_vert_basename[bname]; return
833       end
834       local vtable = {}
835       local a = id.resources.sequences
836       if a then
837          local s = id.shared.rawdata.descriptions
838          for i,v in pairs(a) do
839             if v.features.vert or v.features.vrt2 then
840                add_feature_table(v.subtables[1], s, vtable)
841             end
842          end
843       end
844       font_vert_basename[bname] = vtable
845       font_vert_table[n] = vtable
846    end
847    -- 縦書き用字形への変換
848    function luatexja.direction.get_vert_glyph(n, chr)
849       local fn = font_vert_table[n]
850       return fn and fn[chr] or chr
851    end
852    luatexbase.add_to_callback('luatexja.define_font',
853                               function (res, name, size, id)
854                                  prepare_vert_data(id, res)
855                               end,
856                               'prepare_vert_data', 1)
857
858    local function a (n, dat) font_vert_table[n] = dat end
859    luatexja.rmlgbm.vert_addfunc = a
860
861 end
862
863 -- PACKED の hbox から文字を取り出す
864 -- luatexja.jfmglue.check_box などで使用
865 do
866    local function glyph_from_packed(h)
867       local b = getlist(h)
868       return (getid(b)==id_kern) 
869          and node_next(node_next(node_next(node_next(b)))) or b
870    end
871    luatexja.direction.glyph_from_packed = glyph_from_packed
872 end
873
874 -- adjust and insertion
875 local id_adjust = node.id('adjust')
876 function luatexja.direction.check_adjust_direction()
877    start_time_measure('box_primitive_hook')
878    local list_dir = get_adjust_dir_count()
879    local a = tex_nest[tex_nest.ptr].tail
880    local ad = to_direct(a)
881    if a and getid(ad)==id_adjust then
882       local adj_dir = get_box_dir(ad)
883       if list_dir~=adj_dir then
884          ltjb.package_error(
885                  'luatexja',
886                  'Direction Incompatible',
887                  "\\vadjust's argument and outer vlist must have same direction.")
888          Dnode.last_node()
889       end
890    end
891    stop_time_measure('box_primitive_hook')
892 end
893
894 -- vsplit
895 do
896    local split_dir_whatsit
897    local function dir_adjust_vpack(h, gc)
898       start_time_measure('direction_vpack')
899       local hd = to_direct(h)
900       if gc=='split_keep' then
901          -- supply dir_whatsit
902          hd = create_dir_whatsit_vbox(hd, gc)
903          split_dir_whatsit = hd
904       elseif gc=='split_off'  then
905          local bh=hd
906          for i=1,2 do
907             if bh and getid(bh)==id_whatsit
908             and getsubtype(bh)==sid_user and getfield(bh, 'user_id')==DIR then
909                ltjs.list_dir  = has_attr(bh, attr_dir); break
910             end
911             bh = node_next(bh)
912          end
913          if split_dir_whatsit then
914             -- adjust direction of 'split_keep'
915             set_attr(split_dir_whatsit, attr_dir, ltjs.list_dir)
916          end
917          split_dir_whatsit=nil
918       elseif gc=='preamble' then
919          split_dir_whatsit=nil
920       else
921          adjust_badness(hd)
922          hd = process_dir_node(create_dir_whatsit_vbox(hd, gc), gc)
923          split_dir_whatsit=nil
924       end
925       stop_time_measure('direction_vpack')
926       return to_node(hd)
927    end
928    luatexbase.add_to_callback('vpack_filter',
929                               dir_adjust_vpack,
930                               'ltj.direction', 10000)
931 end
932
933 do
934    -- supply direction whatsit to the main vertical list "of the next page"
935    local function dir_adjust_pre_output(h, gc)
936       return to_node(create_dir_whatsit_vbox(to_direct(h), gc))
937    end
938    luatexbase.add_to_callback('pre_output_filter',
939                               dir_adjust_pre_output,
940                               'ltj.direction', 10000)
941
942    function luatexja.direction.remove_end_whatsit()
943       local h=tex.lists.page_head
944       if (not h.next) and
945          h.id==id_whatsit and h.subtype==sid_user and
946          h.user_id == DIR then
947             tex.lists.page_head = nil
948             node.free(h)
949       end
950    end
951 end
952
953 -- 
954 do
955    local function dir_adjust_buildpage(info)
956       if info=='box' then
957          local head = to_direct(tex.lists.contrib_head)
958          local nb
959          if head then
960             head, _, nb
961                = make_dir_whatsit(head, 
962                                   node_tail(head),
963                                   get_dir_count(), 
964                                   'buildpage')
965             tex.lists.contrib_head = to_node(head)
966          end
967       end
968    end
969    luatexbase.add_to_callback('buildpage_filter',
970                               dir_adjust_buildpage,
971                               'ltj.direction', 10000)
972 end