OSDN Git Service

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