OSDN Git Service

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