OSDN Git Service

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