OSDN Git Service

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