OSDN Git Service

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