OSDN Git Service

Fix \raise, \lower, \moveleft, \moveright.
[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 = 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 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       if luatexja.global_temp and tex.globaldefs~=luatexja.global_temp then 
457          tex.globaldefs = luatexja.global_temp
458       end
459       stop_time_measure('box_primitive_hook')
460    end
461    luatexja.direction.check_dir = check_dir
462 end
463
464 -- dir_node に包まれている「本来の中身」を取り出し,
465 -- dir_node を全部消去
466 local function unwrap_dir_node(b, head, box_dir)
467    -- b: dir_node, head: the head of list, box_dir: 
468    -- return values are (new head), (next of b), (contents), (dir of contents)
469    local bh = getlist(b)
470    local bc = node_next(node_next(node_next(bh)))
471    local nh, nb
472    node_remove(bh, bc); 
473    Dnode.flush_list(bh)
474    if head then
475       nh = insert_before(head, b, bc)
476       nh, nb = node_remove(nh, b)
477       setfield(b, 'next', nil)
478       setfield(b, 'head', nil)
479       node_free(b)
480    end
481    local shift_old, b_dir, wh = nil, get_box_dir(bc, 0)
482    if wh then
483       Dnode.flush_list(getfield(wh, 'value'))
484       setfield(wh, 'value', nil)
485    end
486    -- recalc. info
487    local info = dir_node_aux[b_dir][box_dir%dir_node_auto][getid(bc)]
488    for _,v in ipairs(info) do 
489       if v[1]=='box' then
490          shift_old = v[2](
491             getfield(bc,'width'), getfield(bc, 'height'), getfield(bc, 'depth'))
492          break
493       end
494    end
495    setfield(bc, 'shift', getfield(bc, 'shift') - shift_old)
496    return nh, nb, bc, b_dir
497 end
498
499 -- is_manual: 寸法変更に伴うものか?
500 local function create_dir_node(b, b_dir, new_dir, is_manual)
501    --print('create new node', b_dir, new_dir)
502    local info = dir_node_aux[b_dir][new_dir]
503    local w = getfield(b, 'width')
504    local h = getfield(b, 'height')
505    local d = getfield(b, 'depth')
506    local db = node_new(getid(b)) -- dir_node
507    set_attr(db, attr_dir, 
508             new_dir + (is_manual and dir_node_manual or dir_node_auto))
509    set_attr(db, attr_icflag, PROCESSED)
510    set_attr(b, attr_icflag, PROCESSED)
511    tex_set_attr('global', attr_dir, 0)
512    tex_set_attr('global', attr_icflag, 0)
513    setfield(db, 'dir', getfield(b, 'dir'))
514    setfield(db, 'shift', 0)
515    setfield(db, 'width',  info.width(w,h,d))
516    setfield(db, 'height', info.height(w,h,d))
517    setfield(db, 'depth',  info.depth(w,h,d))
518    return db
519 end
520
521 -- 異方向のボックスの処理
522 local make_dir_whatsit, process_dir_node
523 do
524    make_dir_whatsit = function (head, b, new_dir, origin)
525       -- head: list head, b: box
526       -- origin: コール元 (for debug)
527       -- return value: (new head), (next of b), (new b), (is_b_dir_node)
528       -- (new b): b か dir_node に被せられた b
529       local bh = getlist(b)
530       local box_dir, dn =  get_box_dir(b, ltjs.list_dir)
531       -- 既に b の中身にあるwhatsit
532
533       if box_dir==new_dir then
534          -- 組方向が一緒のボックスなので,何もしなくて良い
535          return head, node_next(b), b, false
536       elseif  box_dir%dir_node_auto == new_dir  then
537          -- dir_node としてカプセル化されている
538          local bc = node_next(node_next(node_next(bh)))
539          local _, dnc = get_box_dir(b, 0)
540          if dnc then -- free all other dir_node
541             Dnode.flush_list(getfield(dnc, 'value'))
542             setfield(dnc, 'value', nil)
543          end
544          set_attr(b, attr_dir, box_dir%dir_node_auto + dir_node_auto)
545          return head, node_next(b), b, true
546       else
547          --luatexja.ext_show_node_list(to_node(b), 'mkd> ', print)
548          -- 組方向を合わせる必要あり
549          local nh, nb, ret, flag
550          if box_dir>= dir_node_auto then -- unwrap
551             local b_dir
552             head, nb, b, b_dir = unwrap_dir_node(b, head, box_dir)
553             bh = getlist(b)
554             if b_dir==new_dir then
555                -- dir_node の中身が周囲の組方向とあっている
556                return head, nb, b, false 
557             else box_dir = b_dir end
558          end
559             local db
560             local dnh = getfield(dn, 'value')
561             for x in traverse(dnh) do
562                if has_attr(x, attr_dir)%dir_node_auto == new_dir then
563                   setfield(dn, 'value', to_node(node_remove(dnh, x)))
564                   db=x; break
565                end
566             end
567             Dnode.flush_list(dnh)
568             db = db or create_dir_node(b, box_dir, new_dir, false)
569             local w = getfield(b, 'width')
570             local h = getfield(b, 'height')
571             local d = getfield(b, 'depth')
572             nh, nb =  insert_before(head, b, db), nil
573             nh, nb = node_remove(nh, b)
574             local db_head, db_tail  = nil
575             for _,v in ipairs(dir_node_aux[box_dir][new_dir][getid(b)]) do
576                local cmd, arg, nn = v[1], v[2]
577                if cmd=='kern' then
578                   nn = node_new(id_kern)
579                   setfield(nn, 'kern', arg(w, h, d))
580                elseif cmd=='whatsit' then
581                   nn = node_new(id_whatsit, arg)
582                elseif cmd=='rotate' then
583                   nn = node_new(id_whatsit, sid_matrix)
584                   setfield(nn, 'data', arg)
585                elseif cmd=='box' then
586                   nn = b; setfield(b, 'next', nil)
587                   setfield(nn, 'shift', getfield(nn, 'shift') + arg(w,h,d))
588                end
589                if db_head then
590                   insert_after(db_head, db_tail, nn)
591                   db_tail = nn
592                else
593                   db_head, db_tail = nn, nn
594                end
595                setfield(db, 'head', db_head)
596                ret, flag = db, true
597          end
598          return nh, nb, ret, flag
599       end
600    end
601    process_dir_node = function (hd, gc)
602       local x, new_dir = hd, ltjs.list_dir or dir_yoko
603       while x do
604          local xid = getid(x)
605          if (xid==id_hlist and has_attr(x, attr_icflag)%PROCESSED_BEGIN_FLAG~=PACKED) 
606          or xid==id_vlist then
607             hd, x = make_dir_whatsit(hd, x, new_dir, 'process_dir_node:' .. gc)
608          else
609             x = node_next(x)
610          end
611       end
612       return hd
613    end
614
615    -- lastbox
616    local node_prev = (Dnode~=node) and Dnode.getprev or node.prev
617    local function lastbox_hook()
618       start_time_measure('box_primitive_hook')
619       local bn = tex_nest[tex_nest.ptr].tail
620       if bn then
621          local b, head = to_direct(bn), to_direct(tex_nest[tex_nest.ptr].head)
622          local bid = getid(b)
623          if bid==id_hlist or bid==id_vlist then
624             local box_dir =  get_box_dir(b, 0)
625             if box_dir>= dir_node_auto then -- unwrap dir_node
626                local p = node_prev(b)
627                local dummy1, dummy2, nb = unwrap_dir_node(b, nil, box_dir)
628                setfield(p, 'next', nb);  tex_nest[tex_nest.ptr].tail = to_node(nb)
629                setfield(b, 'next', nil); setfield(b, 'head', nil)
630                node_free(b); b = nb
631             end
632             local _, wh =  get_box_dir(b, 0) -- clean dir_node attached to the box
633             if wh then
634                Dnode.flush_list(getfield('value', wh))
635                setfield(wh, 'value', nil)
636             end
637          end
638       end
639       stop_time_measure('box_primitive_hook')
640    end
641
642    luatexja.direction.make_dir_whatsit = make_dir_whatsit
643    luatexja.direction.lastbox_hook = lastbox_hook
644 end
645
646 -- \wd, \ht, \dp の代わり
647 do
648    local getbox, setdimen = tex.getbox, tex.setdimen
649    local function get_box_dim_common(key, s, l_dir)
650       local s_dir, wh = get_box_dir(s, dir_yoko)
651       if s_dir ~= l_dir then
652          local not_found = true
653          for x in traverse(getfield(wh, 'value')) do
654             if l_dir == has_attr(x, attr_dir)%dir_node_auto then
655                setdimen('ltj@tempdima', getfield(x, key))
656                not_found = false; break
657             end
658          end
659          if not_found then
660             local w = getfield(s, 'width')
661             local h = getfield(s, 'height')
662             local d = getfield(s, 'depth')
663             setdimen('ltj@tempdima', 
664                          dir_node_aux[s_dir][l_dir][key](w,h,d))
665          end
666       else
667          setdimen('ltj@tempdima', getfield(s, key))
668       end
669    end
670    local function get_box_dim(key, n)
671       local gt = tex.globaldefs; tex.globaldefs = 0
672       local s = getbox(n)
673       if s then
674          local l_dir = get_dir_count()
675          s = to_direct(s)
676          local b_dir = get_box_dir(s,dir_yoko)
677          if b_dir<dir_node_auto then
678             get_box_dim_common(key, s, l_dir)
679          elseif b_dir%dir_node_auto==l_dir then
680             setdimen('ltj@tempdima', getfield(s, key))
681          else
682             get_box_dim_common(key, 
683                                node_next(node_next(node_next(getlist(s)))), l_dir)
684          end
685       else
686          setdimen('ltj@tempdima', 0)
687       end
688       tex.globaldefs = gt
689    end
690    luatexja.direction.get_box_dim = get_box_dim
691
692    -- return value: (changed dimen of box itself?)
693    local function set_box_dim_common(key, s, l_dir)
694       local s_dir, wh = get_box_dir(s, dir_yoko)
695       if s_dir ~= l_dir then
696          if not wh then
697             wh = create_dir_whatsit(getlist(s), 'set_box_dim', s_dir)
698             setfield(s, 'head', wh)
699          end
700          local db
701          local dnh = getfield(wh, 'value')
702          for x in traverse(dnh) do
703             if has_attr(x, attr_dir)%dir_node_auto==l_dir then
704                db = x; break
705             end
706          end
707          if not db then
708             db = create_dir_node(s, s_dir, l_dir, true)
709             setfield(db, 'next', dnh)
710             setfield(wh, 'value',to_node(db))
711          end
712          setfield(db, key, tex.getdimen('ltj@tempdima'))
713          return false
714       else
715          setfield(s, key, tex.getdimen('ltj@tempdima'))
716          if wh then
717             -- change dimension of dir_nodes which are created "automatically"
718                local bw, bh, bd 
719                   = getfield(s,'width'), getfield(s, 'height'), getfield(s, 'depth')
720             for x in traverse(getfield(wh, 'value')) do
721                local x_dir = has_attr(x, attr_dir)
722                if x_dir<dir_node_manual then
723                   local info = dir_node_aux[s_dir][x_dir%dir_node_auto]
724                   setfield(x, 'width',  info.width(bw,bh,bd))
725                   setfield(x, 'height', info.height(bw,bh,bd))
726                   setfield(x, 'depth',  info.depth(bw,bh,bd))
727                end
728             end
729          end
730          return true
731       end
732    end
733    local function set_box_dim(key)
734       local n = tex_getcount('ltj@tempcnta')
735       local s = getbox(n)
736       if s then
737          local l_dir = get_dir_count()
738          s = to_direct(s)
739          local b_dir = get_box_dir(s,dir_yoko)
740          if b_dir<dir_node_auto then
741             set_box_dim_common(key, s, l_dir)
742          elseif b_dir%dir_node_auto == l_dir then
743             -- s is dir_node
744             setfield(s, key, tex.getdimen('ltj@tempdima'))
745             if b_dir<dir_node_manual then
746                set_attr(s, attr_dir, b_dir%dir_node_auto + dir_node_manual)
747             end
748          else
749             local sid, sl = getid(s), getlist(s)
750             local b = node_next(node_next(node_next(sl)))
751             local info = dir_node_aux[get_box_dir(b,dir_yoko)][b_dir%dir_node_auto]
752             local shift_old
753             for _,v in ipairs(info[sid]) do 
754                if v[1]=='box' then
755                   shift_old = v[2](
756                      getfield(b,'width'), getfield(b, 'height'), getfield(b, 'depth'))
757                   break
758                end
759             end
760            if set_box_dim_common(key, b, l_dir) then
761                local bw, bh, bd 
762                   = getfield(b,'width'), getfield(b, 'height'), getfield(b, 'depth')
763                -- re-calculate shift
764                for i,v in ipairs(info[sid]) do 
765                   if getid(sl)==id_kern then
766                      setfield(sl, 'kern', v[2](bw,bh,bd) )
767                   elseif getid(sl)==sid then
768                      local d = getfield(sl, 'shift')
769                      setfield(sl, 'shift', 
770                               getfield(sl, 'shift') - shift_old + v[2](bw,bh,bd) )
771                   end
772                   sl = node_next(sl)
773                end
774                -- re-calculate dimension of s, if s is created "automatically"
775                if b_dir<dir_node_manual then
776                   setfield(s, 'width',  info.width(bw,bh,bd))
777                   setfield(s, 'height', info.height(bw,bh,bd))
778                   setfield(s, 'depth',  info.depth(bw,bh,bd))
779                end
780             end
781          end
782       end
783    end
784    luatexja.direction.set_box_dim = set_box_dim
785 end
786
787 do
788    local getbox = tex.getbox
789    local function get_register_dir(n)
790       local s = getbox(n)
791       if s then
792          s = to_direct(s)
793          local b_dir = get_box_dir(s, dir_yoko)
794          if b_dir<dir_node_auto then
795             return b_dir
796          else
797             local b_dir = get_box_dir(
798                node_next(node_next(node_next(getlist(s)))), dir_yoko)
799             return b_dir
800          end
801       else
802          return 0
803       end
804    end
805    luatexja.direction.get_register_dir = get_register_dir
806 end
807
808 -- raise, lower
809 do
810    local getbox, setbox, copy_list = tex.getbox, tex.setbox, Dnode.copy_list
811    function luatexja.direction.raise_box()
812       start_time_measure('box_primitive_hook')
813       local list_dir = get_dir_count()
814       local s = getbox('ltj@afbox')
815       if s then
816          local sd = to_direct(s)
817          local box_dir = get_box_dir(sd, dir_yoko)
818          if box_dir%dir_node_auto ~= list_dir then
819             setbox(
820                'ltj@afbox', 
821                to_node(
822                   copy_list(make_dir_whatsit(sd, sd, list_dir, 'box_move'))
823                   -- without copy_list, we get a segfault
824                )
825             )
826          end
827       end
828       stop_time_measure('box_primitive_hook')
829    end
830 end
831
832 -- 縦書き用字形への変換テーブル
833 local font_vert_table = {} -- key: fontnumber
834 do
835    local font_vert_basename = {} -- key: basename
836    local function add_feature_table(tname, src, dest)
837       for i,v in pairs(src) do
838          if type(v.slookups)=='table' then
839             local s = v.slookups[tname]
840             if s and not dest[i] then
841                dest[i] = s
842             end
843          end
844       end
845    end
846
847    local function prepare_vert_data(n, id)
848       -- test if already loaded
849       if type(id)=='number' then -- sometimes id is an integer
850          font_vert_table[n] = font_vert_table[id]; return
851       elseif (not id) or font_vert_table[n]  then return
852       end
853       local fname = id.filename
854       local bname = file.basename(fname)
855       if not fname then
856          font_vert_table[n] = {}; return
857       elseif font_vert_basename[bname] then
858          font_vert_table[n] = font_vert_basename[bname]; return
859       end
860       local vtable = {}
861       local a = id.resources.sequences
862       if a then
863          local s = id.shared.rawdata.descriptions
864          for i,v in pairs(a) do
865             if v.features.vert or v.features.vrt2 then
866                add_feature_table(v.subtables[1], s, vtable)
867             end
868          end
869       end
870       font_vert_basename[bname] = vtable
871       font_vert_table[n] = vtable
872    end
873    -- 縦書き用字形への変換
874    function luatexja.direction.get_vert_glyph(n, chr)
875       local fn = font_vert_table[n]
876       return fn and fn[chr] or chr
877    end
878    luatexbase.add_to_callback('luatexja.define_font',
879                               function (res, name, size, id)
880                                  prepare_vert_data(id, res)
881                               end,
882                               'prepare_vert_data', 1)
883
884    local function a (n, dat) font_vert_table[n] = dat end
885    luatexja.rmlgbm.vert_addfunc = a
886
887 end
888
889 -- PACKED の hbox から文字を取り出す
890 -- luatexja.jfmglue.check_box などで使用
891 do
892    local function glyph_from_packed(h)
893       local b = getlist(h)
894       return (getid(b)==id_kern) 
895          and node_next(node_next(node_next(node_next(b)))) or b
896    end
897    luatexja.direction.glyph_from_packed = glyph_from_packed
898 end
899
900 -- adjust and insertion
901 local id_adjust = node.id('adjust')
902 function luatexja.direction.check_adjust_direction()
903    start_time_measure('box_primitive_hook')
904    local list_dir = get_adjust_dir_count()
905    local a = tex_nest[tex_nest.ptr].tail
906    local ad = to_direct(a)
907    if a and getid(ad)==id_adjust then
908       local adj_dir = get_box_dir(ad)
909       if list_dir~=adj_dir then
910          ltjb.package_error(
911                  'luatexja',
912                  'Direction Incompatible',
913                  "\\vadjust's argument and outer vlist must have same direction.")
914          Dnode.last_node()
915       end
916    end
917    stop_time_measure('box_primitive_hook')
918 end
919
920 -- vsplit
921 do
922    local split_dir_whatsit
923    local function dir_adjust_vpack(h, gc)
924       start_time_measure('direction_vpack')
925       local hd = to_direct(h)
926       if gc=='split_keep' then
927          -- supply dir_whatsit
928          hd = create_dir_whatsit_vbox(hd, gc)
929          split_dir_whatsit = hd
930       elseif gc=='split_off'  then
931          local bh=hd
932          for i=1,2 do
933             if bh and getid(bh)==id_whatsit
934             and getsubtype(bh)==sid_user and getfield(bh, 'user_id')==DIR then
935                ltjs.list_dir  = has_attr(bh, attr_dir); break
936             end
937             bh = node_next(bh)
938          end
939          if split_dir_whatsit then
940             -- adjust direction of 'split_keep'
941             set_attr(split_dir_whatsit, attr_dir, ltjs.list_dir)
942          end
943          split_dir_whatsit=nil
944       elseif gc=='preamble' then
945          split_dir_whatsit=nil
946       else
947          adjust_badness(hd)
948          hd = process_dir_node(create_dir_whatsit_vbox(hd, gc), gc)
949          split_dir_whatsit=nil
950       end
951       stop_time_measure('direction_vpack')
952       return to_node(hd)
953    end
954    luatexbase.add_to_callback('vpack_filter',
955                               dir_adjust_vpack,
956                               'ltj.direction', 10000)
957 end
958
959 do
960    -- supply direction whatsit to the main vertical list "of the next page"
961    local function dir_adjust_pre_output(h, gc)
962       return to_node(create_dir_whatsit_vbox(to_direct(h), gc))
963    end
964    luatexbase.add_to_callback('pre_output_filter',
965                               dir_adjust_pre_output,
966                               'ltj.direction', 10000)
967
968    function luatexja.direction.remove_end_whatsit()
969       local h=tex.lists.page_head
970       if (not h.next) and
971          h.id==id_whatsit and h.subtype==sid_user and
972          h.user_id == DIR then
973             tex.lists.page_head = nil
974             node.free(h)
975       end
976    end
977 end
978
979 -- 
980 do
981    local function dir_adjust_buildpage(info)
982       if info=='box' then
983          local head = to_direct(tex.lists.contrib_head)
984          local nb
985          if head then
986             head, _, nb
987                = make_dir_whatsit(head, 
988                                   node_tail(head),
989                                   get_dir_count(), 
990                                   'buildpage')
991             tex.lists.contrib_head = to_node(head)
992          end
993       end
994    end
995    luatexbase.add_to_callback('buildpage_filter',
996                               dir_adjust_buildpage,
997                               'ltj.direction', 10000)
998 end