OSDN Git Service

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