OSDN Git Service

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