OSDN Git Service

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