OSDN Git Service

fix #36598
[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 to_node = node.direct.tonode
14 local to_direct = node.direct.todirect
15 local has_attr = node.direct.has_attribute
16 local set_attr = node.direct.set_attribute
17 local insert_before = node.direct.insert_before
18 local insert_after = node.direct.insert_after
19 local getid = node.direct.getid
20 local getsubtype = node.direct.getsubtype
21 local getlist = node.direct.getlist
22 local setfield = node.direct.setfield
23 local getfield = node.direct.getfield
24 local node_new = node.direct.new
25 local node_tail = node.direct.tail
26 local node_free = node.direct.free
27 local node_remove = node.direct.remove
28 local node_next = node.direct.getnext
29 local traverse = node.direct.traverse
30 local traverse_id = node.direct.traverse_id
31 local start_time_measure, stop_time_measure
32    = ltjb.start_time_measure, ltjb.stop_time_measure
33 local abs = math.abs
34
35 local id_kern = node.id('kern')
36 local id_hlist = node.id('hlist')
37 local id_vlist = node.id('vlist')
38 local id_whatsit = node.id('whatsit')
39 local sid_save = node.subtype('pdf_save')
40 local sid_restore = node.subtype('pdf_restore')
41 local sid_matrix = node.subtype('pdf_setmatrix')
42 local sid_user = node.subtype('user_defined')
43
44 local tex_nest = tex.nest
45 local tex_getcount = tex.getcount
46 local ensure_tex_attr = ltjb.ensure_tex_attr
47 local PROCESSED    = luatexja.icflag_table.PROCESSED
48 local PROCESSED_BEGIN_FLAG = luatexja.icflag_table.PROCESSED_BEGIN_FLAG
49 local PACKED       = luatexja.icflag_table.PACKED
50 local DIR  = luatexja.userid_table.DIR
51 local dir_tate = luatexja.dir_table.dir_tate
52 local dir_yoko = luatexja.dir_table.dir_yoko
53 local dir_dtou = luatexja.dir_table.dir_dtou
54 local dir_utod = luatexja.dir_table.dir_utod
55 local dir_math_mod    = luatexja.dir_table.dir_math_mod
56 local dir_node_auto   = luatexja.dir_table.dir_node_auto
57 local dir_node_manual = luatexja.dir_table.dir_node_manual
58 local function get_attr_icflag(p)
59    return (has_attr(p, attr_icflag) or 0) % PROCESSED_BEGIN_FLAG
60 end
61
62 local page_direction
63 --
64 local dir_pool
65 do
66    local node_copy = node.direct.copy
67    dir_pool = {}
68    for _,i in pairs({dir_tate, dir_yoko, dir_dtou, dir_utod}) do
69       local w = node_new(id_whatsit, sid_user)
70       set_attr(w, attr_dir, i)
71       setfield(w, 'user_id', DIR)
72       setfield(w, 'type', 110)
73       setfield(w, 'next', nil)
74       dir_pool[i] = function () return node_copy(w) end
75    end
76 end
77
78 --
79 local function adjust_badness(hd)
80    if not node_next(hd) and getid(hd)==id_whatsit and getsubtype(hd)==sid_user
81    and getfield(hd, 'user_id')==DIR then
82       -- avoid double whatsit
83       luatexja.global_temp=tex.globaldefs; tex.globaldefs=0
84       luatexja.hbadness_temp=tex.hbadness; tex.hbadness=10000
85       luatexja.vbadness_temp=tex.vbadness; tex.vbadness=10000
86    else
87       luatexja.global_temp = nil
88       luatexja.hbadness_temp=nil
89       luatexja.vbadness_temp=nil
90    end
91 end
92
93 local get_dir_count, get_adjust_dir_count
94 do
95    local function get_dir_count_inner(h)
96       if h then
97          if h.id==id_whatsit and h.subtype==sid_user and h.user_id==DIR then
98                local ic = node.has_attribute(h, attr_icflag) or 0
99                return (ic<PROCESSED_BEGIN_FLAG)
100                   and (node.has_attribute(h,attr_dir)%dir_node_auto) or 0
101          else
102             return 0
103          end
104       else
105          return 0
106       end
107    end
108    function get_dir_count()
109       for i=tex_nest.ptr, 1, -1 do
110          local h = tex_nest[i].head.next
111          if h then
112             local t = get_dir_count_inner(h)
113             if t~=0 then return t end
114          end
115       end
116       return page_direction
117    end
118    function get_adjust_dir_count()
119       for i=tex_nest.ptr, 1, -1 do
120          local v = tex_nest[i]
121          local h, m = v.head.next, v.mode
122          if abs(m)== ltjs.vmode and h then
123             local t = get_dir_count_inner(h)
124             if t~=0 then return t end
125          end
126       end
127       return page_direction
128    end
129    luatexja.direction.get_dir_count = get_dir_count
130    luatexja.direction.get_adjust_dir_count = get_adjust_dir_count
131 end
132
133
134 -- \tate, \yoko,\dtou, \utod
135 do
136    local node_next = node.next
137    local node_set_attr = node.set_attribute
138    local node_traverse = node.traverse
139    local STCK = luatexja.userid_table.STCK
140    local IHB = luatexja.userid_table.IHB
141    local id_local = node.id('local_par')
142
143    local function test_list(h, lv)
144       if not h then
145          return 2 -- need to create dir_whatsit
146       else
147          local flag = 2 -- need to create dir_whatsit
148          local w
149          for p in node_traverse(h) do
150             if p.id==id_whatsit then
151                local ps = p.subtype
152                if ps==sid_user then
153                   local uid= p.user_id
154                   if uid==DIR then
155                      flag = 1; w = w or p -- found
156                   elseif not(uid==IHB or uid==STCK) then
157                      flag = 0; break -- error
158                   end
159                end
160             elseif p.id~=id_local then
161                flag = 0; break
162             end
163          end
164          if flag==1 then -- dir_whatsit already exists
165             return 1,w
166          else
167             return flag
168          end
169       end
170    end
171    local node_next_node, node_tail_node = node.next, node.tail
172    local insert_after_node = node.insert_after
173    function luatexja.direction.set_list_direction_hook(v)
174       local lv = tex_nest.ptr -- must be >= 1
175       if not v then
176          v = get_dir_count()
177          if abs(tex_nest[lv-1].mode) == ltjs.mmode and v == dir_tate then
178             v = dir_utod
179          end
180       elseif v=='adj' then
181          v = get_adjust_dir_count()
182       end
183       local h = tex_nest[lv].head
184       local hn = node.next(h)
185       hn = (hn and hn.id==id_local) and hn or h
186       local w = to_node(dir_pool[v]())
187       insert_after_node(h, hn, w)
188       tex_nest[lv].tail = node_tail_node(w)
189       ensure_tex_attr(attr_icflag, 0)
190       ensure_tex_attr(attr_dir, 0)
191    end
192
193    local function set_list_direction(v, name)
194       local lv = tex_nest.ptr
195       if not v then
196          v,name  = get_dir_count(), nil
197          if lv>=1 and abs(tex_nest[lv-1].mode) == ltjs.mmode and v == dir_tate then
198             v = dir_utod
199          end
200       elseif v=='adj' then
201          v,name = get_adjust_dir_count(), nil
202       end
203       if tex.currentgrouptype==6 then
204          ltjb.package_error(
205                  'luatexja',
206                  "You can't use `\\" .. name .. "' in an align",
207                  "To change direction in an align, \n"
208                     .. "you shold use \\hbox or \\vbox.")
209       else
210          local h = (lv==0) and tex.lists.page_head or tex_nest[lv].head.next
211          local flag,w = test_list(h,lv)
212          if flag==0 then
213             if lv==0 and not page_direction then
214                page_direction = v -- for first call of \yoko (in luatexja-core.sty)
215             else
216               ltjb.package_error(
217                  'luatexja',
218                  "Use `\\" .. tostring(name) .. "' at top of list",
219                  'Direction change command by LuaTeX-ja is available\n'
220                     .. 'only when the current list is null.')
221             end
222          elseif flag==1 then
223             node_set_attr(w, attr_dir, v)
224             if lv==0 then page_direction = v end
225          elseif lv==0 then
226             page_direction = v
227          else -- flag == 2: need to create dir whatsit.
228             local h = tex_nest[lv].head
229             local hn = node.next(h)
230             hn = (hn and hn.id==id_local) and hn or h
231             local w = to_node(dir_pool[v]())
232             insert_after_node(h,hn,w)
233             tex_nest[lv].tail = node_tail_node(w)
234          end
235          ensure_tex_attr(attr_icflag, 0)
236       end
237       ensure_tex_attr(attr_dir, 0)
238    end
239    luatexja.direction.set_list_direction = set_list_direction
240 end
241
242 -- ボックスに dir whatsit を追加
243 local function create_dir_whatsit(hd, gc, new_dir)
244    if getid(hd)==id_whatsit and
245             getsubtype(hd)==sid_user and getfield(hd, 'user_id')==DIR then
246       set_attr(hd, attr_icflag,
247                get_attr_icflag(hd) + PROCESSED_BEGIN_FLAG)
248       local n =node_next(hd)
249       if n then
250          set_attr(n, attr_icflag,
251                   get_attr_icflag(n) + PROCESSED_BEGIN_FLAG)
252       end
253       ensure_tex_attr(attr_icflag, 0)
254       return hd
255    else
256       local w = dir_pool[new_dir]()
257       setfield(w, 'next', hd)
258       set_attr(w, attr_icflag, PROCESSED_BEGIN_FLAG)
259       set_attr(hd, attr_icflag,
260                get_attr_icflag(hd) + PROCESSED_BEGIN_FLAG)
261       ensure_tex_attr(attr_icflag, 0)
262       ensure_tex_attr(attr_dir, 0)
263       return w
264    end
265 end
266
267 -- hpack_filter, vpack_filter, post_line_break_filter
268 -- の結果を組方向を明示するため,先頭に dir_node を設置
269 do
270    local function create_dir_whatsit_hpack(h, gc)
271       local hd = to_direct(h)
272       if gc=='fin_row' or gc == 'preamble'  then
273          if hd  then
274             set_attr(hd, attr_icflag, PROCESSED_BEGIN_FLAG)
275             ensure_tex_attr(attr_icflag, 0)
276          end
277          return h
278       else
279          adjust_badness(hd)
280          return to_node(create_dir_whatsit(hd, gc, ltjs.list_dir))
281       end
282    end
283
284    ltjb.add_to_callback('hpack_filter',
285                               create_dir_whatsit_hpack, 'ltj.create_dir_whatsit', 10000)
286 end
287
288 do
289    local function create_dir_whatsit_parbox(h, gc)
290       stop_time_measure('tex_linebreak');
291       -- start 側は ltj-debug.lua に
292       local new_dir = ltjs.list_dir
293       for line in traverse_id(id_hlist, to_direct(h)) do
294          setfield(line, 'head', create_dir_whatsit(getlist(line), gc, new_dir) )
295       end
296       ensure_tex_attr(attr_dir, 0)
297       return h
298    end
299    ltjb.add_to_callback('post_linebreak_filter',
300                               create_dir_whatsit_parbox, 'ltj.create_dir_whatsit', 10000)
301 end
302
303 local create_dir_whatsit_vbox
304 do
305    local wh = {}
306    local id_glue, sid_parskip = node.id('glue'), 3
307    create_dir_whatsit_vbox = function (hd, gc)
308       ltjs.list_dir = get_dir_count()
309       -- remove dir whatsit
310       for x in traverse_id(id_whatsit, hd) do
311          if getsubtype(x)==sid_user and getfield(x, 'user_id')==DIR then
312             wh[#wh+1]=x
313          end
314       end
315       if hd==wh[1] then
316          ltjs.list_dir =has_attr(hd,attr_dir)
317          local x = node_next(hd)
318          if getid(x)==id_glue and getsubtype(x)==sid_parskip then
319             node_remove(hd,x); node_free(x)
320          end
321       end
322       for i=1,#wh do
323          hd = node_remove(hd, wh[i]); node_free(wh[i]); wh[i] = nil
324       end
325       if gc=='fin_row' then -- gc == 'preamble' case is treated in dir_adjust_vpack
326          if hd  then
327             set_attr(hd, attr_icflag, PROCESSED_BEGIN_FLAG)
328             ensure_tex_attr(attr_icflag, 0)
329          end
330          return hd
331       else
332          local n =node_next(hd)
333          if gc=='vtop' then
334             local w = create_dir_whatsit(hd, gc, ltjs.list_dir)
335             -- move  dir whatsit after hd
336             setfield(hd, 'next', w); setfield(w, 'next', n)
337             return hd
338          else
339             hd = create_dir_whatsit(hd, gc, ltjs.list_dir)
340             return hd
341          end
342       end
343    end
344 end
345
346 -- dir_node に包む方法を書いたテーブル
347 local dir_node_aux
348 do
349    local floor = math.floor
350    local get_h =function (w,h,d) return h end
351    local get_d =function (w,h,d) return d end
352    local get_h_d =function (w,h,d) return h+d end
353    local get_h_d_neg =function (w,h,d) return -h-d end
354    local get_d_neg =function (w,h,d) return -d end
355    local get_w_half =function (w,h,d) return floor(0.5*w) end
356    local get_w_half_rem =function (w,h,d) return w-floor(0.5*w) end
357    local get_w_neg =function (w,h,d) return -w end
358    local get_w =function (w,h,d) return w end
359    local zero = function() return 0 end
360    dir_node_aux = {
361       [dir_yoko] = { -- yoko を
362          [dir_tate] = { -- tate 中で組む
363             width  = get_h_d,
364             height = get_w_half,
365             depth  = get_w_half_rem,
366             [id_hlist] = {
367                { 'whatsit', sid_save },
368                { 'rotate', '0 1 -1 0' },
369                { 'kern', function(w,h,d,nw,nh,nd) return -nd end },
370                { 'box' , get_h},
371                { 'kern', function(w,h,d,nw,nh,nd) return nd-w end },
372                { 'whatsit', sid_restore },
373             },
374             [id_vlist] = {
375                { 'whatsit', sid_save },
376                { 'rotate', '0 1 -1 0' },
377                { 'kern' , zero },
378                { 'box' , function(w,h,d,nw,nh,nd) return -nh-nd end },
379                { 'kern', get_h_d_neg},
380                { 'whatsit', sid_restore },
381             },
382          },
383          [dir_dtou] = { -- dtou 中で組む
384             width  = get_h_d,
385             height = get_w,
386             depth  = zero,
387             [id_hlist] = {
388                { 'whatsit', sid_save },
389                { 'rotate', '0 -1 1 0' },
390                { 'kern', function(w,h,d,nw,nh,nd) return -nh end },
391                { 'box', get_d_neg },
392                { 'kern', function(w,h,d,nw,nh,nd) return nh-w end },
393                { 'whatsit', sid_restore },
394             },
395             [id_vlist] = {
396                { 'whatsit', sid_save },
397                { 'rotate', '0 -1 1 0' },
398                { 'kern', get_h_d_neg },
399                { 'box', zero },
400                { 'whatsit', sid_restore },
401             },
402          },
403       },
404       [dir_tate] = { -- tate を
405          [dir_yoko] = { -- yoko 中で組む
406             width  = get_h_d,
407             height = get_w,
408             depth  = zero,
409             [id_hlist] = {
410                { 'whatsit', sid_save },
411                { 'rotate', '0 -1 1 0' },
412                { 'kern', function (w,h,d,nw,nh,nd) return -nh end },
413                { 'box' , get_d_neg },
414                { 'kern', function (w,h,d,nw,nh,nd) return nh-w end },
415                { 'whatsit', sid_restore },
416             },
417             [id_vlist] = {
418                { 'whatsit', sid_save },
419                { 'rotate', '0 -1 1 0' },
420                { 'kern', get_h_d_neg },
421                { 'box', zero },
422                { 'whatsit', sid_restore },
423             },
424          },
425          [dir_dtou] = { -- dtou 中で組む
426             width  = get_w,
427             height = get_d,
428             depth  = get_h,
429             [id_hlist] = {
430                { 'whatsit', sid_save },
431                { 'rotate', '-1 0 0 -1' },
432                { 'kern', get_w_neg },
433                { 'box',  function (w,h,d,nw,nh,nd) return h-nd end },
434                { 'whatsit', sid_restore },
435             },
436             [id_vlist] = {
437                { 'whatsit', sid_save },
438                { 'rotate', '-1 0 0 -1' },
439                { 'kern', get_h_d_neg },
440                { 'box', get_w_neg },
441                { 'whatsit', sid_restore },
442             },
443          },
444       },
445       [dir_dtou] = { -- dtou を
446          [dir_yoko] = { -- yoko 中で組む
447             width  = get_h_d,
448             height = get_w,
449             depth  = zero,
450             [id_hlist] = {
451                { 'whatsit', sid_save },
452                { 'rotate', '0 1 -1 0' },
453                { 'kern', function (w,h,d,nw,nh,nd) return -nd end },
454                { 'box', get_h },
455                { 'kern', function (w,h,d,nw,nh,nd) return nd-w end },
456                { 'whatsit', sid_restore },
457             },
458             [id_vlist] = {
459                { 'kern', zero },
460                { 'whatsit', sid_save },
461                { 'rotate', '0 1 -1 0' },
462                { 'box', function (w,h,d,nw,nh,nd) return -nd-nh end },
463                { 'kern', get_h_d_neg },
464                { 'whatsit', sid_restore },
465             },
466          },
467          [dir_tate] = { -- tate 中で組む
468             width  = get_w,
469             height = get_d,
470             depth  = get_h,
471             [id_hlist] = {
472                { 'whatsit', sid_save },
473                { 'rotate', '-1 0 0 -1' },
474                { 'kern', get_w_neg },
475                { 'box', function (w,h,d,nw,nh,nd) return h-nd end },
476                { 'whatsit', sid_restore },
477             },
478             [id_vlist] = {
479                { 'whatsit', sid_save },
480                { 'rotate', ' -1 0 0 -1' },
481                { 'kern', function (w,h,d,nw,nh,nd) return -nh-nd end },
482                { 'box', get_w_neg },
483                { 'kern', function (w,h,d,nw,nh,nd) return nh+nd-h-d end },
484                { 'whatsit', sid_restore },
485             },
486          },
487       },
488    }
489 end
490
491 -- 1st ret val: b の組方向
492 -- 2nd ret val はその DIR whatsit
493 local function get_box_dir(b, default)
494    start_time_measure('get_box_dir')
495    local dir = has_attr(b, attr_dir) or 0
496    local bh = getfield(b,'head')
497    -- b は insert node となりうるので getlist() は使えない
498    local c
499    if bh~=0 then -- bh != nil
500       for bh in traverse_id(id_whatsit, bh) do
501          if getsubtype(bh)==sid_user and getfield(bh, 'user_id')==DIR then
502             c = bh
503            dir = (dir==0) and has_attr(bh, attr_dir) or dir
504          end
505       end
506    end
507    -- for i=1,2 do
508    --    if bh and getid(bh)==id_whatsit
509    --    and getsubtype(bh)==sid_user and getfield(bh, 'user_id')==DIR then
510    --    c = bh
511    --    dir = (dir==0) and has_attr(bh, attr_dir) or dir
512    --    end
513    --    bh = node_next(bh)
514    -- end
515    stop_time_measure('get_box_dir')
516    return (dir==0 and default or dir), c
517 end
518
519 do
520    local getbox = tex.getbox
521    local dir_backup
522    function luatexja.direction.unbox_check_dir(is_copy)
523       start_time_measure('box_primitive_hook')
524       local list_dir = get_dir_count()%dir_math_mod
525       local b = getbox(tex_getcount('ltj@tempcnta'))
526       if b then
527          local box_dir = get_box_dir(to_direct(b), dir_yoko)
528          if box_dir%dir_math_mod ~= list_dir then
529             ltjb.package_error(
530                'luatexja',
531                "Incompatible direction list can't be unboxed",
532                'I refuse to unbox a box in differrent direction.')
533             tex.sprint(cat_lp, '\\@gobbletwo')
534          else
535             dir_backup = nil
536             local bd = to_direct(b)
537             local hd = getlist(bd)
538             local nh = hd
539             while hd do
540                if getid(hd)==id_whatsit and getsubtype(hd)==sid_user
541                   and getfield(hd, 'user_id')==DIR then
542                      local d = hd
543                      nh, hd = node_remove(nh, hd)
544                      if is_copy and (not dir_backup) then
545                         dir_backup = d
546                         setfield(dir_backup, 'next', nil)
547                      else
548                         node_free(d)
549                      end
550                else
551                   hd = node_next(hd)
552                end
553             end
554             setfield(bd, 'head', nh)
555          end
556       end
557       if luatexja.global_temp and tex.globaldefs~=luatexja.global_temp then
558          tex.globaldefs = luatexja.global_temp
559       end
560       stop_time_measure('box_primitive_hook')
561    end
562    function luatexja.direction.uncopy_restore_whatsit()
563       local b = getbox(tex_getcount('ltj@tempcnta'))
564       if b then
565          local bd = to_direct(b)
566          if dir_backup then
567             setfield(dir_backup, 'next', getlist(bd))
568             setfield(bd, 'head', dir_backup)
569             dir_backup = nil
570          end
571       end
572    end
573 end
574
575 -- dir_node に包まれている「本来の中身」を取り出し,
576 -- dir_node を全部消去
577 local function unwrap_dir_node(b, head, box_dir)
578    -- b: dir_node, head: the head of list, box_dir:
579    -- return values are (new head), (next of b), (contents), (dir of contents)
580    local bh = getlist(b)
581    local nh, nb
582    if head then
583       nh = insert_before(head, b, bh)
584       nh, nb = node_remove(nh, b)
585       setfield(b, 'next', nil)
586       node_free(b)
587    end
588    local shift_old, b_dir, wh = nil, get_box_dir(bh, 0)
589    if wh then
590       node.direct.flush_list(getfield(wh, 'value'))
591       setfield(wh, 'value', nil)
592    end
593    return nh, nb, bh, b_dir
594 end
595
596 -- is_manual: 寸法変更に伴うものか?
597 local function create_dir_node(b, b_dir, new_dir, is_manual)
598    local info = dir_node_aux[b_dir%dir_math_mod][new_dir%dir_math_mod]
599    local w = getfield(b, 'width')
600    local h = getfield(b, 'height')
601    local d = getfield(b, 'depth')
602    local db = node_new(getid(b)) -- dir_node
603    set_attr(db, attr_dir,
604             new_dir + (is_manual and dir_node_manual or dir_node_auto))
605    set_attr(db, attr_icflag, PROCESSED)
606    set_attr(b, attr_icflag, PROCESSED)
607    ensure_tex_attr(attr_dir, 0)
608    ensure_tex_attr(attr_icflag, 0)
609    setfield(db, 'dir', getfield(b, 'dir'))
610    setfield(db, 'shift', 0)
611    setfield(db, 'width',  info.width(w,h,d))
612    setfield(db, 'height', info.height(w,h,d))
613    setfield(db, 'depth',  info.depth(w,h,d))
614    return db
615 end
616
617 -- 異方向のボックスの処理
618 local make_dir_whatsit, process_dir_node
619 do
620    make_dir_whatsit = function (head, b, new_dir, origin)
621       new_dir = new_dir%dir_math_mod
622       -- head: list head, b: box
623       -- origin: コール元 (for debug)
624       -- return value: (new head), (next of b), (new b), (is_b_dir_node)
625       -- (new b): b か dir_node に被せられた b
626       local bh = getlist(b)
627       local box_dir, dn =  get_box_dir(b, ltjs.list_dir)
628       -- 既に b の中身にあるwhatsit
629
630       if box_dir%dir_math_mod==new_dir then
631          if box_dir>=dir_node_auto then
632             -- dir_node としてカプセル化されている
633             local _, dnc = get_box_dir(b, 0)
634             if dnc then -- free all other dir_node
635                node.direct.flush_list(getfield(dnc, 'value'))
636                setfield(dnc, 'value', nil)
637             end
638             set_attr(b, attr_dir, box_dir%dir_math_mod + dir_node_auto)
639             return head, node_next(b), b, true
640          else
641             -- 組方向が一緒 (up to math dir) のボックスなので,何もしなくて良い
642             return head, node_next(b), b, false
643          end
644       else
645          -- 組方向を合わせる必要あり
646          local nh, nb, ret, flag
647          if box_dir>= dir_node_auto then -- unwrap
648             local b_dir
649             head, nb, b, b_dir = unwrap_dir_node(b, head, box_dir)
650             bh = getlist(b)
651             if b_dir%dir_math_mod==new_dir then
652                -- dir_node の中身が周囲の組方向とあっている
653                return head, nb, b, false
654             else box_dir = b_dir end
655          end
656          box_dir = box_dir%dir_math_mod
657          local db
658          local dnh = getfield(dn, 'value')
659          for x in traverse(dnh) do
660             if has_attr(x, attr_dir)%dir_math_mod == new_dir then
661                setfield(dn, 'value', to_node(node_remove(dnh, x)))
662                db=x; break
663             end
664          end
665          node.direct.flush_list(getfield(dn, 'value'))
666          setfield(dn, 'value', nil)
667          db = db or create_dir_node(b, box_dir, new_dir, false)
668          local w = getfield(b, 'width')
669          local h = getfield(b, 'height')
670          local d = getfield(b, 'depth')
671          local dn_w = getfield(db, 'width')
672          local dn_h = getfield(db, 'height')
673          local dn_d = getfield(db, 'depth')
674          nh, nb =  insert_before(head, b, db), nil
675          nh, nb = node_remove(nh, b)
676          setfield(b, 'next', nil); setfield(db, 'head', b)
677          ret, flag = db, true
678          return nh, nb, ret, flag
679       end
680    end
681    process_dir_node = function (hd, gc)
682       local x, new_dir = hd, ltjs.list_dir or dir_yoko
683       while x do
684          local xid = getid(x)
685          if (xid==id_hlist and get_attr_icflag(x)~=PACKED)
686          or xid==id_vlist then
687             hd, x = make_dir_whatsit(hd, x, new_dir, 'process_dir_node:' .. gc)
688          else
689             x = node_next(x)
690          end
691       end
692       return hd
693    end
694
695    -- lastbox
696    local node_prev = (node.direct~=node) and node.direct.getprev or node.prev
697    local id_glue = node.id('glue')
698    local function lastbox_hook()
699       start_time_measure('box_primitive_hook')
700       local bn = tex_nest[tex_nest.ptr].tail
701       if bn then
702          local b, head = to_direct(bn), to_direct(tex_nest[tex_nest.ptr].head)
703          local bid = getid(b)
704          if bid==id_hlist or bid==id_vlist then
705             local p = getlist(b)
706             -- alignment 由来
707             if p and getid(p)==id_glue and getsubtype(p)==12 then -- tabskip
708                local np = node_next(p); local npid = getid(np)
709                if npid==id_hlist or npid==id_vlist then
710                   setfield(b, 'head', create_dir_whatsit(p, 'align', get_box_dir(np, 0)))
711                end
712             end
713             local box_dir =  get_box_dir(b, 0)
714             if box_dir>= dir_node_auto then -- unwrap dir_node
715                local p = node_prev(b)
716                local dummy1, dummy2, nb = unwrap_dir_node(b, nil, box_dir)
717                setfield(p, 'next', nb);  tex_nest[tex_nest.ptr].tail = to_node(nb)
718                setfield(b, 'next', nil); setfield(b, 'head', nil)
719                node_free(b); b = nb
720             end
721             local _, wh =  get_box_dir(b, 0) -- clean dir_node attached to the box
722             if wh then
723                node.direct.flush_list(getfield('value', wh))
724                setfield(wh, 'value', nil)
725             end
726          end
727       end
728       stop_time_measure('box_primitive_hook')
729    end
730
731    luatexja.direction.make_dir_whatsit = make_dir_whatsit
732    luatexja.direction.lastbox_hook = lastbox_hook
733 end
734
735 -- \wd, \ht, \dp の代わり
736 do
737    local getbox, setdimen = tex.getbox, tex.setdimen
738    local function get_box_dim_common(key, s, l_dir)
739       -- s: not dir_node.
740       local s_dir, wh = get_box_dir(s, dir_yoko)
741       s_dir = s_dir%dir_math_mod
742       if s_dir ~= l_dir then
743          local not_found = true
744          for x in traverse(getfield(wh, 'value')) do
745             if l_dir == has_attr(x, attr_dir)%dir_node_auto then
746                setdimen('ltj@tempdima', getfield(x, key))
747                not_found = false; break
748             end
749          end
750          if not_found then
751             local w = getfield(s, 'width')
752             local h = getfield(s, 'height')
753             local d = getfield(s, 'depth')
754             setdimen('ltj@tempdima',
755                          dir_node_aux[s_dir][l_dir][key](w,h,d))
756          end
757       else
758          setdimen('ltj@tempdima', getfield(s, key))
759       end
760    end
761    local function get_box_dim(key, n)
762       local gt = tex.globaldefs; tex.globaldefs = 0
763       local s = getbox(n)
764       if s then
765          local l_dir = (get_dir_count())%dir_math_mod
766          s = to_direct(s)
767          local b_dir = get_box_dir(s,dir_yoko)
768          if b_dir<dir_node_auto then
769             get_box_dim_common(key, s, l_dir)
770          elseif b_dir%dir_math_mod==l_dir then
771             setdimen('ltj@tempdima', getfield(s, key))
772          else
773             get_box_dim_common(key, getlist(s), l_dir)
774          end
775       else
776          setdimen('ltj@tempdima', 0)
777       end
778       tex.sprint(cat_lp, '\\ltj@tempdima')
779       tex.globaldefs = gt
780    end
781    luatexja.direction.get_box_dim = get_box_dim
782
783    -- return value: (changed dimen of box itself?)
784    local scan_dimen, scan_int = token.scan_dimen, token.scan_int
785    local scan_keyword = token.scan_keyword
786    local function set_box_dim_common(key, s, l_dir)
787       local s_dir, wh = get_box_dir(s, dir_yoko)
788       s_dir = s_dir%dir_math_mod
789       if s_dir ~= l_dir then
790          if not wh then
791             wh = create_dir_whatsit(getlist(s), 'set_box_dim', s_dir)
792             setfield(s, 'head', wh)
793          end
794          local db
795          local dnh = getfield(wh, 'value')
796          for x in traverse(dnh) do
797             if has_attr(x, attr_dir)%dir_node_auto==l_dir then
798                db = x; break
799             end
800          end
801          if not db then
802             db = create_dir_node(s, s_dir, l_dir, true)
803             setfield(db, 'next', dnh)
804             setfield(wh, 'value',to_node(db))
805          end
806          setfield(db, key, scan_dimen())
807          return false
808       else
809          setfield(s, key, scan_dimen())
810          if wh then
811             -- change dimension of dir_nodes which are created "automatically"
812                local bw, bh, bd
813                   = getfield(s,'width'), getfield(s, 'height'), getfield(s, 'depth')
814             for x in traverse(getfield(wh, 'value')) do
815                local x_dir = has_attr(x, attr_dir)
816                if x_dir<dir_node_manual then
817                   local info = dir_node_aux[s_dir][x_dir%dir_node_auto]
818                   setfield(x, 'width',  info.width(bw,bh,bd))
819                   setfield(x, 'height', info.height(bw,bh,bd))
820                   setfield(x, 'depth',  info.depth(bw,bh,bd))
821                end
822             end
823          end
824          return true
825       end
826    end
827    local function set_box_dim(key)
828       local s = getbox(scan_int()); scan_keyword('=')
829       if s then
830          local l_dir = (get_dir_count())%dir_math_mod
831          s = to_direct(s)
832          local b_dir = get_box_dir(s,dir_yoko)
833          if b_dir<dir_node_auto then
834             set_box_dim_common(key, s, l_dir)
835          elseif b_dir%dir_math_mod == l_dir then
836             -- s is dir_node
837             setfield(s, key, scan_dimen())
838             if b_dir<dir_node_manual then
839                set_attr(s, attr_dir, b_dir%dir_node_auto + dir_node_manual)
840             end
841          else
842             local sid, b = getid(s), getlist(s)
843             local info = dir_node_aux[get_box_dir(b,dir_yoko)%dir_math_mod][b_dir%dir_node_auto]
844             local bw, bh, bd
845                = getfield(b,'width'), getfield(b, 'height'), getfield(b, 'depth')
846             local sw, sh, sd
847                = getfield(s,'width'), getfield(s, 'height'), getfield(s, 'depth')
848             if set_box_dim_common(key, b, l_dir) and b_dir<dir_node_manual then
849                -- re-calculate dimension of s, if s is created "automatically"
850                if b_dir<dir_node_manual then
851                   setfield(s, 'width',  info.width(bw,bh,bd))
852                   setfield(s, 'height', info.height(bw,bh,bd))
853                   setfield(s, 'depth',  info.depth(bw,bh,bd))
854                end
855             end
856          end
857       end
858    end
859    luatexja.direction.set_box_dim = set_box_dim
860 end
861
862 do
863    local getbox = tex.getbox
864    local function get_register_dir(n)
865       local s = getbox(n)
866       if s then
867          s = to_direct(s)
868          local b_dir = get_box_dir(s, dir_yoko)
869          if b_dir<dir_node_auto then
870             return b_dir
871          else
872             local b_dir = get_box_dir(
873                node_next(node_next(node_next(getlist(s)))), dir_yoko)
874             return b_dir
875          end
876       else
877          return 0
878       end
879    end
880    luatexja.direction.get_register_dir = get_register_dir
881 end
882
883 do
884    local getbox, setbox, copy_list = tex.getbox, tex.setbox, node.direct.copy_list
885    -- raise, lower
886    function luatexja.direction.raise_box()
887       start_time_measure('box_primitive_hook')
888       local list_dir = get_dir_count()
889       local s = getbox('ltj@afbox')
890       if s then
891          local sd = to_direct(s)
892          local box_dir = get_box_dir(sd, dir_yoko)
893          if box_dir%dir_math_mod ~= list_dir then
894             setbox(
895                'ltj@afbox',
896                to_node(copy_list(make_dir_whatsit(sd, sd, list_dir, 'box_move')))
897                -- copy_list しないとリストの整合性が崩れる……?
898             )
899          end
900       end
901       stop_time_measure('box_primitive_hook')
902    end
903 end
904
905 -- PACKED の hbox から文字を取り出す
906 -- luatexja.jfmglue.check_box などで使用
907 do
908    local function glyph_from_packed(h)
909       local b = getlist(h)
910       return (getid(b)==id_kern or (getid(b)==id_whatsit and getsubtype(b)==sid_save) )
911          and node_next(node_next(node_next(b))) or b
912    end
913    luatexja.direction.glyph_from_packed = glyph_from_packed
914 end
915
916 -- adjust
917 do
918    local id_adjust = node.id('adjust')
919    function luatexja.direction.check_adjust_direction()
920       start_time_measure('box_primitive_hook')
921       local list_dir = get_adjust_dir_count()
922       local a = tex_nest[tex_nest.ptr].tail
923       local ad = to_direct(a)
924       if a and getid(ad)==id_adjust then
925          local adj_dir = get_box_dir(ad)
926          if list_dir~=adj_dir then
927             ltjb.package_error(
928                'luatexja',
929                'Direction Incompatible',
930                "\\vadjust's argument and outer vlist must have same direction.")
931             node.direct.last_node()
932          end
933       end
934       stop_time_measure('box_primitive_hook')
935    end
936 end
937
938 -- insert
939 do
940    local id_ins = node.id('ins')
941    local id_rule = node.id('rule')
942    function luatexja.direction.populate_insertion_dir_whatsit()
943       start_time_measure('box_primitive_hook')
944       local list_dir = get_dir_count()
945       local a = tex_nest[tex_nest.ptr].tail
946       local ad = to_direct(a)
947       if a and getid(ad)==id_ins then
948          local h = getfield(ad, 'head')
949          if getid(h)==id_whatsit and
950             getsubtype(h)==sid_user and getfield(h, 'user_id')==DIR then
951                local n = h; h = node_remove(h,h)
952                node_free(n)
953          end
954          for box_rule in traverse(h) do
955             if getid(box_rule)<id_rule then
956                h = insert_before(h, box_rule, dir_pool[list_dir]())
957             end
958          end
959          ensure_tex_attr(attr_dir, 0)
960          setfield(ad, 'head', h)
961       end
962       stop_time_measure('box_primitive_hook')
963    end
964 end
965
966 -- vsplit
967 do
968    local split_dir_whatsit, split_dir_head
969    local cat_lp = luatexbase.catcodetables['latex-package']
970    local sprint, scan_int, tex_getbox = tex.sprint, token.scan_int, tex.getbox
971    function luatexja.direction.vsplit()
972       local n = scan_int();
973       local p = to_direct(tex_getbox(n))
974       split_dir_head = nil
975       if p then
976          local bh = getlist(p)
977          if getid(bh)==id_whatsit and getsubtype(bh)==sid_user and getfield(bh, 'user_id')==DIR 
978             and node_next(bh) then
979             ltjs.list_dir = has_attr(bh, attr_dir)
980             local q = node_next(p)
981             setfield(p, 'head', node_remove(bh,bh,bh))
982             split_dir_head = bh
983          end
984       end
985       sprint(cat_lp, '\\ltj@@orig@vsplit' .. tostring(n))
986    end  
987    local function dir_adjust_vpack(h, gc)
988       start_time_measure('direction_vpack')
989       local hd = to_direct(h)
990       if gc=='split_keep' then
991          -- supply dir_whatsit
992          hd = create_dir_whatsit_vbox(hd, gc)
993          split_dir_whatsit = hd
994       elseif gc=='split_off'  then
995          if split_dir_head then
996             list_dir = has_attr(split_dir_head, attr_dir)
997             hd = insert_before(hd, hd, split_dir_head)
998          end
999          if split_dir_whatsit then
1000             -- adjust direction of 'split_keep'
1001             set_attr(split_dir_whatsit, attr_dir, ltjs.list_dir)
1002          end
1003          split_dir_whatsit=nil
1004       elseif gc=='preamble' then
1005          split_dir_whatsit=nil
1006       else
1007          adjust_badness(hd)
1008          -- hd = process_dir_node(create_dir_whatsit_vbox(hd, gc), gc)
1009          -- done in append_to_vpack callback
1010          hd = create_dir_whatsit_vbox(hd, gc)
1011          split_dir_whatsit=nil
1012       end
1013       stop_time_measure('direction_vpack')
1014       return to_node(hd)
1015    end
1016    ltjb.add_to_callback('vpack_filter',
1017                               dir_adjust_vpack,
1018                               'ltj.direction', 10000)
1019 end
1020
1021 do
1022    -- supply direction whatsit to the main vertical list "of the next page"
1023    local function dir_adjust_pre_output(h, gc)
1024       return to_node(create_dir_whatsit_vbox(to_direct(h), gc))
1025    end
1026    ltjb.add_to_callback('pre_output_filter',
1027                               dir_adjust_pre_output,
1028                               'ltj.direction', 10000)
1029
1030    function luatexja.direction.remove_end_whatsit()
1031       local h=tex.lists.page_head
1032       if h and (not h.next) and
1033          h.id==id_whatsit and h.subtype==sid_user and
1034          h.user_id == DIR then
1035             tex.lists.page_head = nil
1036             node.free(h)
1037       end
1038    end
1039 end
1040
1041 -- append_to_vlist filter
1042 do
1043    local id_glue = node.id('glue')
1044    local getglue = node.direct.getglue or
1045       function(g)
1046          return getfield(g,'width'), getfield(g,'stretch'), getfield(g,'shrink'),
1047          getfield(g,'stretch_order'), getfield(g,'shrink_order')
1048       end
1049 local setglue = luatexja.setglue
1050    local function copy_glue (new_glue, old_glue, subtype, new_w)
1051       setfield(new_glue, 'subtype', subtype)
1052       local w,st,sp,sto,spo = getglue(to_direct(old_glue))
1053       setglue(new_glue, new_w or w, st, sp, sto, spo)
1054    end
1055    local node_write = node.direct.write
1056    local function dir_adjust_append_vlist(b, loc, prev, mirrored)
1057       local old_b = to_direct(b)
1058       local new_b = loc=='box' and 
1059          make_dir_whatsit(old_b, old_b, get_dir_count(), 'append_vlist') or old_b
1060       
1061       if prev > -65536000 then
1062          local d = tex.baselineskip.width - prev 
1063             - getfield(new_b, mirrored and 'depth' or 'height')
1064          local g = node_new(id_glue)
1065          if d < tex.lineskiplimit then
1066             copy_glue(g, tex.lineskip, 1)
1067          else
1068             copy_glue(g, tex.baselineskip, 2, d);
1069          end
1070          node_write(g)
1071       end
1072       node_write(new_b)
1073       tex.prevdepth = getfield(new_b, mirrored and 'height' or 'depth')
1074       return nil -- do nothing on tex side
1075    end
1076    ltjb.add_to_callback('append_to_vlist_filter',
1077                         dir_adjust_append_vlist,
1078                         'ltj.direction', 10000)
1079 end
1080
1081 -- finalize (executed just before \shipout)
1082 -- we supply correct pdfsavematrix nodes etc. inside dir_node
1083 do
1084    local finalize_inner
1085    local function finalize_dir_node(db,new_dir)
1086       local b = getlist(db)
1087       finalize_inner(b)
1088       local w = getfield(b, 'width')
1089       local h = getfield(b, 'height')
1090       local d = getfield(b, 'depth')
1091       local dn_w = getfield(db, 'width')
1092       local dn_h = getfield(db, 'height')
1093       local dn_d = getfield(db, 'depth')
1094       local db_head, db_tail
1095       for _,v in ipairs(dir_node_aux
1096                         [get_box_dir(b, dir_yoko)%dir_math_mod][new_dir][getid(b)]) do
1097          local cmd, arg, nn = v[1], v[2]
1098          if cmd=='kern' then
1099             nn = node_new(id_kern, 1)
1100             setfield(nn, 'kern', arg(w, h, d, dn_w, dn_h, dn_d))
1101          elseif cmd=='whatsit' then
1102             nn = node_new(id_whatsit, arg)
1103          elseif cmd=='rotate' then
1104             nn = node_new(id_whatsit, sid_matrix)
1105             setfield(nn, 'data', arg)
1106          elseif cmd=='box' then
1107             nn = b; setfield(b, 'next', nil)
1108             setfield(nn, 'shift', arg(w, h, d, dn_w, dn_h, dn_d))
1109          end
1110          if db_head then
1111             insert_after(db_head, db_tail, nn)
1112             db_tail = nn
1113          else
1114             setfield(db, 'head', nn)
1115             db_head, db_tail = nn, nn
1116          end
1117       end
1118    end
1119
1120    tex.setattribute(attr_dir, dir_yoko)
1121    local shipout_temp =  node_new(id_hlist)
1122    tex.setattribute(attr_dir, 0)
1123
1124    finalize_inner = function (box)
1125       for n in traverse(getlist(box)) do
1126          local nid = getid(n)
1127          if (nid==id_hlist or nid==id_vlist) then
1128             local ndir = get_box_dir(n, dir_yoko)
1129             if ndir>=dir_node_auto then -- n is dir_node
1130                finalize_dir_node(n, ndir%dir_math_mod)
1131             else
1132                finalize_inner(n)
1133             end
1134          end
1135       end
1136    end
1137    local getbox = tex.getbox
1138    local setbox, copy = node.direct.setbox, node.direct.copy
1139    local lua_mem_kb = 0
1140    function luatexja.direction.finalize()
1141       local a = to_direct(tex.getbox("AtBeginShipoutBox"))
1142       local a_dir = get_box_dir(a, dir_yoko)
1143       if a_dir~=dir_yoko then
1144          local b = create_dir_node(a, a_dir, dir_yoko, false)
1145          setfield(b, 'head', a); a = b
1146       end
1147       setfield(shipout_temp, 'head', a)
1148       finalize_inner(shipout_temp)
1149       setbox('global', "AtBeginShipoutBox", copy(getlist(shipout_temp)))
1150       setfield(shipout_temp, 'head',nil)
1151
1152       -- garbage collect
1153       --local m = collectgarbage('count')
1154       --if m>lua_mem_kb+20480 then
1155       --   collectgarbage(); lua_mem_kb = collectgarbage('count')
1156       --end
1157       --print('Lua Memory Usage', lua_mem_kb)
1158    end
1159 end