OSDN Git Service

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