OSDN Git Service

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