OSDN Git Service

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