OSDN Git Service

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