OSDN Git Service

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