OSDN Git Service

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