OSDN Git Service

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