OSDN Git Service

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