OSDN Git Service

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