OSDN Git Service

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