OSDN Git Service

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