OSDN Git Service

cleanup
[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
143    local function test_list(h, lv)
144       if not h then
145          return 2 -- need to create dir_whatsit
146       else
147          local flag = 2 -- need to create dir_whatsit
148          local w
149          for p in node_traverse(h) do
150             if p.id==id_whatsit then
151                local ps = p.subtype
152                if ps==sid_user then
153                   local uid= p.user_id
154                   if uid==DIR then
155                      flag = 1; w = w or p -- found
156                   elseif not(uid==IHB or uid==STCK) then
157                      flag = 0; break -- error
158                   end
159                end
160             elseif p.id~=id_local then
161                flag = 0; break
162             end
163          end
164          if flag==1 then -- dir_whatsit already exists
165             return 1,w
166          else
167             return flag
168          end
169       end
170    end
171    function luatexja.direction.set_list_direction_hook(v)
172       local lv = tex_nest.ptr -- must be >= 1
173       if not v then
174          v = get_dir_count()
175          if abs(tex_nest[lv-1].mode) == ltjs.mmode and v == dir_tate then
176             v = dir_utod
177          end
178       elseif v=='adj' then
179          v = get_adjust_dir_count()
180       end
181       local h = to_direct(tex_nest[lv].head)
182       local w = dir_pool[v]()
183       insert_after(h, h, w)
184       tex_nest[lv].tail = to_node(node_tail(w))
185       ensure_tex_attr(attr_icflag, 0)
186       ensure_tex_attr(attr_dir, 0)
187    end
188
189    local function set_list_direction(v, name)
190       local lv = tex_nest.ptr
191       if not v then
192          v,name  = get_dir_count(), nil
193          if lv>=1 and abs(tex_nest[lv-1].mode) == ltjs.mmode and v == dir_tate then
194             v = dir_utod
195          end
196       elseif v=='adj' then
197          v,name = get_adjust_dir_count(), nil
198       end
199       if tex.currentgrouptype==6 then
200          ltjb.package_error(
201                  'luatexja',
202                  "You can't use `\\" .. name .. "' in an align",
203                  "To change direction in an align, \n"
204                     .. "you shold use \\hbox or \\vbox.")
205       else
206          local h = (lv==0) and tex.lists.page_head or tex_nest[lv].head.next
207          local flag,w = test_list(h,lv)
208          if flag==0 then
209             if lv==0 and not page_direction then
210                page_direction = v -- for first call of \yoko (in luatexja-core.sty)
211             else
212               ltjb.package_error(
213                  'luatexja',
214                  "Use `\\" .. tostring(name) .. "' at top of list",
215                  'Direction change command by LuaTeX-ja is available\n'
216                     .. 'only when the current list is null.')
217             end
218          elseif flag==1 then
219             node_set_attr(w, attr_dir, v)
220             if lv==0 then page_direction = v end
221          else
222             if lv==0 then page_direction = v end
223          end
224          ensure_tex_attr(attr_icflag, 0)
225       end
226       ensure_tex_attr(attr_dir, 0)
227    end
228    luatexja.direction.set_list_direction = set_list_direction
229 end
230
231 -- ボックスに dir whatsit を追加
232 local function create_dir_whatsit(hd, gc, new_dir)
233    if getid(hd)==id_whatsit and
234             getsubtype(hd)==sid_user and getfield(hd, 'user_id')==DIR then
235       set_attr(hd, attr_icflag,
236                get_attr_icflag(hd) + PROCESSED_BEGIN_FLAG)
237       local n = node_next(hd)
238       if n then
239          set_attr(n, attr_icflag,
240                   get_attr_icflag(n) + PROCESSED_BEGIN_FLAG)
241       end
242       ensure_tex_attr(attr_icflag, 0)
243       return hd
244    else
245       local w = dir_pool[new_dir]()
246       setfield(w, 'next', hd)
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    ltjb.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    ltjb.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    if bh~=0 then -- bh != nil
489       for bh in traverse_id(id_whatsit, bh) do
490          if getsubtype(bh)==sid_user and getfield(bh, 'user_id')==DIR then
491             c = bh
492            dir = (dir==0) and has_attr(bh, attr_dir) or dir
493          end
494       end
495    end
496    -- for i=1,2 do
497    --    if bh and getid(bh)==id_whatsit
498    --    and getsubtype(bh)==sid_user and getfield(bh, 'user_id')==DIR then
499    --    c = bh
500    --    dir = (dir==0) and has_attr(bh, attr_dir) or dir
501    --    end
502    --    bh = node_next(bh)
503    -- end
504    stop_time_measure('get_box_dir')
505    return (dir==0 and default or dir), c
506 end
507
508 do
509    local getbox = tex.getbox
510    local dir_backup
511    function luatexja.direction.unbox_check_dir(is_copy)
512       start_time_measure('box_primitive_hook')
513       local list_dir = get_dir_count()%dir_math_mod
514       local b = getbox(tex_getcount('ltj@tempcnta'))
515       if b then
516          local box_dir = get_box_dir(to_direct(b), dir_yoko)
517          if box_dir%dir_math_mod ~= list_dir then
518             ltjb.package_error(
519                'luatexja',
520                "Incompatible direction list can't be unboxed",
521                'I refuse to unbox a box in differrent direction.')
522             tex.sprint(cat_lp, '\\@gobbletwo')
523          else
524             dir_backup = nil
525             local bd = to_direct(b)
526             local hd = getlist(bd)
527             local nh = hd
528             while hd do
529                if getid(hd)==id_whatsit and getsubtype(hd)==sid_user
530                   and getfield(hd, 'user_id')==DIR then
531                      local d = hd
532                      nh, hd = node_remove(nh, hd)
533                      if is_copy and (not dir_backup) then
534                         dir_backup = d
535                         setfield(dir_backup, 'next', nil)
536                      else
537                         node_free(d)
538                      end
539                else
540                   hd = node_next(hd)
541                end
542             end
543             setfield(bd, 'head', nh)
544          end
545       end
546       if luatexja.global_temp and tex.globaldefs~=luatexja.global_temp then
547          tex.globaldefs = luatexja.global_temp
548       end
549       stop_time_measure('box_primitive_hook')
550    end
551    function luatexja.direction.uncopy_restore_whatsit()
552       local b = getbox(tex_getcount('ltj@tempcnta'))
553       if b then
554          local bd = to_direct(b)
555          if dir_backup then
556             setfield(dir_backup, 'next', getlist(bd))
557             setfield(bd, 'head', dir_backup)
558             dir_backup = nil
559          end
560       end
561    end
562 end
563
564 -- dir_node に包まれている「本来の中身」を取り出し,
565 -- dir_node を全部消去
566 local function unwrap_dir_node(b, head, box_dir)
567    -- b: dir_node, head: the head of list, box_dir:
568    -- return values are (new head), (next of b), (contents), (dir of contents)
569    local bh = getlist(b)
570    local nh, nb
571    if head then
572       nh = insert_before(head, b, bh)
573       nh, nb = node_remove(nh, b)
574       setfield(b, 'next', nil)
575       node_free(b)
576    end
577    local shift_old, b_dir, wh = nil, get_box_dir(bh, 0)
578    if wh then
579       node.direct.flush_list(getfield(wh, 'value'))
580       setfield(wh, 'value', nil)
581    end
582    return nh, nb, bh, b_dir
583 end
584
585 -- is_manual: 寸法変更に伴うものか?
586 local function create_dir_node(b, b_dir, new_dir, is_manual)
587    local info = dir_node_aux[b_dir%dir_math_mod][new_dir%dir_math_mod]
588    local w = getfield(b, 'width')
589    local h = getfield(b, 'height')
590    local d = getfield(b, 'depth')
591    local db = node_new(getid(b)) -- dir_node
592    set_attr(db, attr_dir,
593             new_dir + (is_manual and dir_node_manual or dir_node_auto))
594    set_attr(db, attr_icflag, PROCESSED)
595    set_attr(b, attr_icflag, PROCESSED)
596    ensure_tex_attr(attr_dir, 0)
597    ensure_tex_attr(attr_icflag, 0)
598    setfield(db, 'dir', getfield(b, 'dir'))
599    setfield(db, 'shift', 0)
600    setfield(db, 'width',  info.width(w,h,d))
601    setfield(db, 'height', info.height(w,h,d))
602    setfield(db, 'depth',  info.depth(w,h,d))
603    return db
604 end
605
606 -- 異方向のボックスの処理
607 local make_dir_whatsit, process_dir_node
608 do
609    make_dir_whatsit = function (head, b, new_dir, origin)
610       new_dir = new_dir%dir_math_mod
611       -- head: list head, b: box
612       -- origin: コール元 (for debug)
613       -- return value: (new head), (next of b), (new b), (is_b_dir_node)
614       -- (new b): b か dir_node に被せられた b
615       local bh = getlist(b)
616       local box_dir, dn =  get_box_dir(b, ltjs.list_dir)
617       -- 既に b の中身にあるwhatsit
618
619       if box_dir%dir_math_mod==new_dir then
620          if box_dir>=dir_node_auto then
621             -- dir_node としてカプセル化されている
622             local _, dnc = get_box_dir(b, 0)
623             if dnc then -- free all other dir_node
624                node.direct.flush_list(getfield(dnc, 'value'))
625                setfield(dnc, 'value', nil)
626             end
627             set_attr(b, attr_dir, box_dir%dir_math_mod + dir_node_auto)
628             return head, node_next(b), b, true
629          else
630             -- 組方向が一緒 (up to math dir) のボックスなので,何もしなくて良い
631             return head, node_next(b), b, false
632          end
633       else
634          -- 組方向を合わせる必要あり
635          local nh, nb, ret, flag
636          if box_dir>= dir_node_auto then -- unwrap
637             local b_dir
638             head, nb, b, b_dir = unwrap_dir_node(b, head, box_dir)
639             bh = getlist(b)
640             if b_dir%dir_math_mod==new_dir then
641                -- dir_node の中身が周囲の組方向とあっている
642                return head, nb, b, false
643             else box_dir = b_dir end
644          end
645          box_dir = box_dir%dir_math_mod
646          local db
647          local dnh = getfield(dn, 'value')
648          for x in traverse(dnh) do
649             if has_attr(x, attr_dir)%dir_math_mod == new_dir then
650                setfield(dn, 'value', to_node(node_remove(dnh, x)))
651                db=x; break
652             end
653          end
654          node.direct.flush_list(getfield(dn, 'value'))
655          setfield(dn, 'value', nil)
656          db = db or create_dir_node(b, box_dir, new_dir, false)
657          local w = getfield(b, 'width')
658          local h = getfield(b, 'height')
659          local d = getfield(b, 'depth')
660          local dn_w = getfield(db, 'width')
661          local dn_h = getfield(db, 'height')
662          local dn_d = getfield(db, 'depth')
663          nh, nb =  insert_before(head, b, db), nil
664          nh, nb = node_remove(nh, b)
665          setfield(b, 'next', nil); setfield(db, 'head', b)
666          ret, flag = db, true
667          return nh, nb, ret, flag
668       end
669    end
670    process_dir_node = function (hd, gc)
671       local x, new_dir = hd, ltjs.list_dir or dir_yoko
672       while x do
673          local xid = getid(x)
674          if (xid==id_hlist and get_attr_icflag(x)~=PACKED)
675          or xid==id_vlist then
676             hd, x = make_dir_whatsit(hd, x, new_dir, 'process_dir_node:' .. gc)
677          else
678             x = node_next(x)
679          end
680       end
681       return hd
682    end
683
684    -- lastbox
685    local node_prev = (node.direct~=node) and node.direct.getprev or node.prev
686    local function lastbox_hook()
687       start_time_measure('box_primitive_hook')
688       local bn = tex_nest[tex_nest.ptr].tail
689       if bn then
690          local b, head = to_direct(bn), to_direct(tex_nest[tex_nest.ptr].head)
691          local bid = getid(b)
692          if bid==id_hlist or bid==id_vlist then
693             local box_dir =  get_box_dir(b, 0)
694             if box_dir>= dir_node_auto then -- unwrap dir_node
695                local p = node_prev(b)
696                local dummy1, dummy2, nb = unwrap_dir_node(b, nil, box_dir)
697                setfield(p, 'next', nb);  tex_nest[tex_nest.ptr].tail = to_node(nb)
698                setfield(b, 'next', nil); setfield(b, 'head', nil)
699                node_free(b); b = nb
700             end
701             local _, wh =  get_box_dir(b, 0) -- clean dir_node attached to the box
702             if wh then
703                node.direct.flush_list(getfield('value', wh))
704                setfield(wh, 'value', nil)
705             end
706          end
707       end
708       stop_time_measure('box_primitive_hook')
709    end
710
711    luatexja.direction.make_dir_whatsit = make_dir_whatsit
712    luatexja.direction.lastbox_hook = lastbox_hook
713 end
714
715 -- \wd, \ht, \dp の代わり
716 do
717    local getbox, setdimen = tex.getbox, tex.setdimen
718    local function get_box_dim_common(key, s, l_dir)
719       -- s: not dir_node.
720       local s_dir, wh = get_box_dir(s, dir_yoko)
721       s_dir = s_dir%dir_math_mod
722       if s_dir ~= l_dir then
723          local not_found = true
724          for x in traverse(getfield(wh, 'value')) do
725             if l_dir == has_attr(x, attr_dir)%dir_node_auto then
726                setdimen('ltj@tempdima', getfield(x, key))
727                not_found = false; break
728             end
729          end
730          if not_found then
731             local w = getfield(s, 'width')
732             local h = getfield(s, 'height')
733             local d = getfield(s, 'depth')
734             setdimen('ltj@tempdima',
735                          dir_node_aux[s_dir][l_dir][key](w,h,d))
736          end
737       else
738          setdimen('ltj@tempdima', getfield(s, key))
739       end
740    end
741    local function get_box_dim(key, n)
742       local gt = tex.globaldefs; tex.globaldefs = 0
743       local s = getbox(n)
744       if s then
745          local l_dir = (get_dir_count())%dir_math_mod
746          s = to_direct(s)
747          local b_dir = get_box_dir(s,dir_yoko)
748          if b_dir<dir_node_auto then
749             get_box_dim_common(key, s, l_dir)
750          elseif b_dir%dir_math_mod==l_dir then
751             setdimen('ltj@tempdima', getfield(s, key))
752          else
753             get_box_dim_common(key, getlist(s), l_dir)
754          end
755       else
756          setdimen('ltj@tempdima', 0)
757       end
758       tex.sprint(cat_lp, '\\ltj@tempdima')
759       tex.globaldefs = gt
760    end
761    luatexja.direction.get_box_dim = get_box_dim
762
763    -- return value: (changed dimen of box itself?)
764    local scan_dimen, scan_int = token.scan_dimen, token.scan_int
765    local scan_keyword = token.scan_keyword
766    local function set_box_dim_common(key, s, l_dir)
767       local s_dir, wh = get_box_dir(s, dir_yoko)
768       s_dir = s_dir%dir_math_mod
769       if s_dir ~= l_dir then
770          if not wh then
771             wh = create_dir_whatsit(getlist(s), 'set_box_dim', s_dir)
772             setfield(s, 'head', wh)
773          end
774          local db
775          local dnh = getfield(wh, 'value')
776          for x in traverse(dnh) do
777             if has_attr(x, attr_dir)%dir_node_auto==l_dir then
778                db = x; break
779             end
780          end
781          if not db then
782             db = create_dir_node(s, s_dir, l_dir, true)
783             setfield(db, 'next', dnh)
784             setfield(wh, 'value',to_node(db))
785          end
786          setfield(db, key, scan_dimen())
787          return false
788       else
789          setfield(s, key, scan_dimen())
790          if wh then
791             -- change dimension of dir_nodes which are created "automatically"
792                local bw, bh, bd
793                   = getfield(s,'width'), getfield(s, 'height'), getfield(s, 'depth')
794             for x in traverse(getfield(wh, 'value')) do
795                local x_dir = has_attr(x, attr_dir)
796                if x_dir<dir_node_manual then
797                   local info = dir_node_aux[s_dir][x_dir%dir_node_auto]
798                   setfield(x, 'width',  info.width(bw,bh,bd))
799                   setfield(x, 'height', info.height(bw,bh,bd))
800                   setfield(x, 'depth',  info.depth(bw,bh,bd))
801                end
802             end
803          end
804          return true
805       end
806    end
807    local function set_box_dim(key)
808       local s = getbox(scan_int()); scan_keyword('=')
809       if s then
810          local l_dir = (get_dir_count())%dir_math_mod
811          s = to_direct(s)
812          local b_dir = get_box_dir(s,dir_yoko)
813          if b_dir<dir_node_auto then
814             set_box_dim_common(key, s, l_dir)
815          elseif b_dir%dir_math_mod == l_dir then
816             -- s is dir_node
817             setfield(s, key, scan_dimen())
818             if b_dir<dir_node_manual then
819                set_attr(s, attr_dir, b_dir%dir_node_auto + dir_node_manual)
820             end
821          else
822             local sid, b = getid(s), getlist(s)
823             local info = dir_node_aux[get_box_dir(b,dir_yoko)%dir_math_mod][b_dir%dir_node_auto]
824             local bw, bh, bd
825                = getfield(b,'width'), getfield(b, 'height'), getfield(b, 'depth')
826             local sw, sh, sd
827                = getfield(s,'width'), getfield(s, 'height'), getfield(s, 'depth')
828             if set_box_dim_common(key, b, l_dir) and b_dir<dir_node_manual then
829                -- re-calculate dimension of s, if s is created "automatically"
830                if b_dir<dir_node_manual then
831                   setfield(s, 'width',  info.width(bw,bh,bd))
832                   setfield(s, 'height', info.height(bw,bh,bd))
833                   setfield(s, 'depth',  info.depth(bw,bh,bd))
834                end
835             end
836          end
837       end
838    end
839    luatexja.direction.set_box_dim = set_box_dim
840 end
841
842 do
843    local getbox = tex.getbox
844    local function get_register_dir(n)
845       local s = getbox(n)
846       if s then
847          s = to_direct(s)
848          local b_dir = get_box_dir(s, dir_yoko)
849          if b_dir<dir_node_auto then
850             return b_dir
851          else
852             local b_dir = get_box_dir(
853                node_next(node_next(node_next(getlist(s)))), dir_yoko)
854             return b_dir
855          end
856       else
857          return 0
858       end
859    end
860    luatexja.direction.get_register_dir = get_register_dir
861 end
862
863 do
864    local getbox, setbox, copy_list = tex.getbox, tex.setbox, node.direct.copy_list
865    -- raise, lower
866    function luatexja.direction.raise_box()
867       start_time_measure('box_primitive_hook')
868       local list_dir = get_dir_count()
869       local s = getbox('ltj@afbox')
870       if s then
871          local sd = to_direct(s)
872          local box_dir = get_box_dir(sd, dir_yoko)
873          if box_dir%dir_math_mod ~= list_dir then
874             setbox(
875                'ltj@afbox',
876                to_node(copy_list(make_dir_whatsit(sd, sd, list_dir, 'box_move')))
877                -- copy_list しないとリストの整合性が崩れる……?
878             )
879          end
880       end
881       stop_time_measure('box_primitive_hook')
882    end
883 end
884
885 -- PACKED の hbox から文字を取り出す
886 -- luatexja.jfmglue.check_box などで使用
887 do
888    local function glyph_from_packed(h)
889       local b = getlist(h)
890       return (getid(b)==id_kern or (getid(b)==id_whatsit and getsubtype(b)==sid_save) )
891          and node_next(node_next(node_next(b))) or b
892    end
893    luatexja.direction.glyph_from_packed = glyph_from_packed
894 end
895
896 -- adjust
897 do
898    local id_adjust = node.id('adjust')
899    function luatexja.direction.check_adjust_direction()
900       start_time_measure('box_primitive_hook')
901       local list_dir = get_adjust_dir_count()
902       local a = tex_nest[tex_nest.ptr].tail
903       local ad = to_direct(a)
904       if a and getid(ad)==id_adjust then
905          local adj_dir = get_box_dir(ad)
906          if list_dir~=adj_dir then
907             ltjb.package_error(
908                'luatexja',
909                'Direction Incompatible',
910                "\\vadjust's argument and outer vlist must have same direction.")
911             node.direct.last_node()
912          end
913       end
914       stop_time_measure('box_primitive_hook')
915    end
916 end
917
918 -- insert
919 do
920    local id_ins = node.id('ins')
921    local id_rule = node.id('rule')
922    function luatexja.direction.populate_insertion_dir_whatsit()
923       start_time_measure('box_primitive_hook')
924       local list_dir = get_dir_count()
925       local a = tex_nest[tex_nest.ptr].tail
926       local ad = to_direct(a)
927       if a and getid(ad)==id_ins then
928          local h = getfield(ad, 'head')
929          if getid(h)==id_whatsit and
930             getsubtype(h)==sid_user and getfield(h, 'user_id')==DIR then
931                local n = h; h = node_remove(h,h)
932                node_free(n)
933          end
934          for box_rule in traverse(h) do
935             if getid(box_rule)<id_rule then
936                h = insert_before(h, box_rule, dir_pool[list_dir]())
937             end
938          end
939          ensure_tex_attr(attr_dir, 0)
940          setfield(ad, 'head', h)
941       end
942       stop_time_measure('box_primitive_hook')
943    end
944 end
945
946 -- vsplit
947 do
948    local split_dir_whatsit
949    local function dir_adjust_vpack(h, gc)
950       start_time_measure('direction_vpack')
951       local hd = to_direct(h)
952       if gc=='split_keep' then
953          -- supply dir_whatsit
954          hd = create_dir_whatsit_vbox(hd, gc)
955          split_dir_whatsit = hd
956       elseif gc=='split_off'  then
957          for  bh in traverse_id(id_whatsit, hd) do
958             if getsubtype(bh)==sid_user and getfield(bh, 'user_id')==DIR then
959                ltjs.list_dir  = has_attr(bh, attr_dir); break
960             end
961          end
962          if split_dir_whatsit then
963             -- adjust direction of 'split_keep'
964             set_attr(split_dir_whatsit, attr_dir, ltjs.list_dir)
965          end
966          split_dir_whatsit=nil
967       elseif gc=='preamble' then
968          split_dir_whatsit=nil
969       else
970          adjust_badness(hd)
971          -- hd = process_dir_node(create_dir_whatsit_vbox(hd, gc), gc)
972          -- done in append_to_vpack callback
973          hd = create_dir_whatsit_vbox(hd, gc)
974          split_dir_whatsit=nil
975       end
976       stop_time_measure('direction_vpack')
977       return to_node(hd)
978    end
979    ltjb.add_to_callback('vpack_filter',
980                               dir_adjust_vpack,
981                               'ltj.direction', 10000)
982 end
983
984 do
985    -- supply direction whatsit to the main vertical list "of the next page"
986    local function dir_adjust_pre_output(h, gc)
987       return to_node(create_dir_whatsit_vbox(to_direct(h), gc))
988    end
989    ltjb.add_to_callback('pre_output_filter',
990                               dir_adjust_pre_output,
991                               'ltj.direction', 10000)
992
993    function luatexja.direction.remove_end_whatsit()
994       local h=tex.lists.page_head
995       if h and (not h.next) and
996          h.id==id_whatsit and h.subtype==sid_user and
997          h.user_id == DIR then
998             tex.lists.page_head = nil
999             node.free(h)
1000       end
1001    end
1002 end
1003
1004 -- append_to_vlist filter
1005 do
1006    local id_glue = node.id('glue')
1007    local getglue = node.direct.getglue or
1008       function(g)
1009          return getfield(g,'width'), getfield(g,'stretch'), getfield(g,'shrink'),
1010          getfield(g,'stretch_order'), getfield(g,'shrink_order')
1011       end
1012 local setglue = luatexja.setglue
1013    local function copy_glue (new_glue, old_glue, subtype, new_w)
1014       setfield(new_glue, 'subtype', subtype)
1015       local w,st,sp,sto,spo = getglue(to_direct(old_glue))
1016       setglue(new_glue, new_w or w, st, sp, sto, spo)
1017    end
1018    local node_write = node.direct.write
1019    local function dir_adjust_append_vlist(b, loc, prev, mirrored)
1020       local old_b = to_direct(b)
1021       local new_b = loc=='box' and 
1022          make_dir_whatsit(old_b, old_b, get_dir_count(), 'append_vlist') or old_b
1023       
1024       if prev > -65536000 then
1025          local d = tex.baselineskip.width - prev 
1026             - getfield(new_b, mirrored and 'depth' or 'height')
1027          local g = node_new(id_glue)
1028          if d < tex.lineskiplimit then
1029             copy_glue(g, tex.lineskip, 1)
1030          else
1031             copy_glue(g, tex.baselineskip, 2, d);
1032          end
1033          node_write(g)
1034       end
1035       node_write(new_b)
1036       tex.prevdepth = getfield(new_b, mirrored and 'height' or 'depth')
1037       return nil -- do nothing on tex side
1038    end
1039    ltjb.add_to_callback('append_to_vlist_filter',
1040                         dir_adjust_append_vlist,
1041                         'ltj.direction', 10000)
1042 end
1043
1044 -- finalize (executed just before \shipout)
1045 -- we supply correct pdfsavematrix nodes etc. inside dir_node
1046 do
1047    local finalize_inner
1048    local function finalize_dir_node(db,new_dir)
1049       local b = getlist(db)
1050       finalize_inner(b)
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
1058       for _,v in ipairs(dir_node_aux
1059                         [get_box_dir(b, dir_yoko)%dir_math_mod][new_dir][getid(b)]) do
1060          local cmd, arg, nn = v[1], v[2]
1061          if cmd=='kern' then
1062             nn = node_new(id_kern)
1063             setfield(nn, 'kern', arg(w, h, d, dn_w, dn_h, dn_d))
1064          elseif cmd=='whatsit' then
1065             nn = node_new(id_whatsit, arg)
1066          elseif cmd=='rotate' then
1067             nn = node_new(id_whatsit, sid_matrix)
1068             setfield(nn, 'data', arg)
1069          elseif cmd=='box' then
1070             nn = b; setfield(b, 'next', nil)
1071             setfield(nn, 'shift', arg(w, h, d, dn_w, dn_h, dn_d))
1072          end
1073          if db_head then
1074             insert_after(db_head, db_tail, nn)
1075             db_tail = nn
1076          else
1077             setfield(db, 'head', nn)
1078             db_head, db_tail = nn, nn
1079          end
1080       end
1081    end
1082
1083    tex.setattribute(attr_dir, dir_yoko)
1084    local shipout_temp =  node_new(id_hlist)
1085    tex.setattribute(attr_dir, 0)
1086
1087    finalize_inner = function (box)
1088       for n in traverse(getlist(box)) do
1089          local nid = getid(n)
1090          if (nid==id_hlist or nid==id_vlist) then
1091             local ndir = get_box_dir(n, dir_yoko)
1092             if ndir>=dir_node_auto then -- n is dir_node
1093                finalize_dir_node(n, ndir%dir_math_mod)
1094             else
1095                finalize_inner(n)
1096             end
1097          end
1098       end
1099    end
1100    local getbox = tex.getbox
1101    local setbox, copy = node.direct.setbox, node.direct.copy
1102    local lua_mem_kb = 0
1103    function luatexja.direction.finalize()
1104       local a = to_direct(tex.getbox("AtBeginShipoutBox"))
1105       local a_dir = get_box_dir(a, dir_yoko)
1106       if a_dir~=dir_yoko then
1107          local b = create_dir_node(a, a_dir, dir_yoko, false)
1108          setfield(b, 'head', a); a = b
1109       end
1110       setfield(shipout_temp, 'head', a)
1111       finalize_inner(shipout_temp)
1112       setbox('global', "AtBeginShipoutBox", copy(getlist(shipout_temp)))
1113       setfield(shipout_temp, 'head',nil)
1114
1115       -- garbage collect
1116       --local m = collectgarbage('count')
1117       --if m>lua_mem_kb+20480 then
1118       --   collectgarbage(); lua_mem_kb = collectgarbage('count')
1119       --end
1120       --print('Lua Memory Usage', lua_mem_kb)
1121    end
1122 end