OSDN Git Service

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