OSDN Git Service

2fc116003f3bac96d747673b3b00caa1a1556624
[luatex-ja/luatexja.git] / src / luatexja.lua
1
2 require('lualibs')
3 tableunpack = table.unpack
4
5 ------------------------------------------------------------------------
6 local function load_lua(fn)
7    local found = kpse.find_file(fn, 'tex')
8    if not found then
9       tex.error("LuaTeX-ja error: File `" .. fn .. "' not found")
10    else
11       texio.write_nl('(' .. found .. ')')
12       dofile(found)
13    end
14 end
15 luatexja.load_lua = load_lua
16 function luatexja.load_module(name)
17    require('ltj-' .. name.. '.lua')
18 end
19
20 do
21     local setfield = node.direct.setfield
22     luatexja.setglue = node.direct.setglue or
23     function(g,w,st,sh,sto,sho)
24         setfield(g,'width', w or 0)
25         setfield(g,'stretch',st or 0)
26         setfield(g,'shrink', sh or 0)
27         setfield(g,'stretch_order',sto or 0)
28         setfield(g,'shrink_order', sho or 0)
29     end
30     local getfield = node.direct.getfield
31     luatexja.getglue = node.direct.getglue or
32     function(g)
33         return getfield(g,'width'),
34                getfield(g,'stretch'),
35                getfield(g,'shrink'),
36                getfield(g,'stretch_order'),
37                getfield(g,'shrink_order')
38     end
39 end
40
41 --- 以下は全ファイルで共有される定数
42 local icflag_table = {}
43 luatexja.icflag_table = icflag_table
44 icflag_table.ITALIC          = 1
45 icflag_table.PACKED          = 2
46 icflag_table.KINSOKU         = 3
47 icflag_table.FROM_JFM        = 4
48 -- FROM_JFM: 4, 5, 6, 7, 8 →優先度高(伸びやすく,縮みやすい)
49 -- 6 が標準
50 icflag_table.KANJI_SKIP      = 68 -- = 4+64
51 icflag_table.KANJI_SKIP_JFM  = 69
52 icflag_table.XKANJI_SKIP     = 70
53 icflag_table.XKANJI_SKIP_JFM = 71
54 icflag_table.LINEEND         = 72
55 icflag_table.PROCESSED       = 73
56 icflag_table.IC_PROCESSED    = 74
57 icflag_table.BOXBDD          = 75
58 icflag_table.PROCESSED_BEGIN_FLAG = 4096 -- sufficiently large power of 2
59
60 local stack_table_index = {}
61 luatexja.stack_table_index = stack_table_index
62 stack_table_index.PRE  = 0x200000 -- characterごと
63 stack_table_index.POST = 0x400000 -- characterごと
64 stack_table_index.KCAT = 0x600000 -- characterごと
65 stack_table_index.XSP  = 0x800000 -- characterごと
66 stack_table_index.RIPRE  = 0xA00000 -- characterごと,ruby pre
67 stack_table_index.RIPOST = 0xC00000 -- characterごと,ruby post
68 stack_table_index.JWP  = 0 -- これだけ
69 stack_table_index.KSK  = 1 -- これだけ
70 stack_table_index.XSK  = 2 -- これだけ
71 stack_table_index.MJT  = 0x100 -- 0--255
72 stack_table_index.MJS  = 0x200 -- 0--255
73 stack_table_index.MJSS = 0x300 -- 0--255
74 stack_table_index.KSJ  = 0x400 -- 0--9
75
76 local userid_table = {}
77 luatexja.userid_table = userid_table
78 userid_table.IHB  = luatexbase.newuserwhatsitid('inhibitglue',  'luatexja') -- \inhibitglue
79 userid_table.STCK = luatexbase.newuserwhatsitid('stack_marker', 'luatexja') -- スタック管理
80 userid_table.BPAR = luatexbase.newuserwhatsitid('begin_par',    'luatexja') -- 「段落始め」
81 userid_table.DIR  = luatexbase.newuserwhatsitid('direction',    'luatexja') -- 組方向
82 userid_table.BOXB = luatexbase.newuserwhatsitid('box_boundary', 'luatexja') -- 「ボックス始め・終わり」
83
84 local dir_table = {}
85 luatexja.dir_table = dir_table
86 dir_table.dir_dtou = 1
87 dir_table.dir_tate = 3
88 dir_table.dir_yoko = 4
89 dir_table.dir_math_mod    = 8
90 dir_table.dir_node_auto   = 128 -- 組方向を合わせるために自動で作られたもの
91 dir_table.dir_node_manual = 256 -- 寸法代入によって作られたもの
92 dir_table.dir_utod = dir_table.dir_tate + dir_table.dir_math_mod
93    -- 「縦数式ディレクション」 in pTeX
94 --- 定義終わり
95
96 local load_module = luatexja.load_module
97 load_module('base');      local ltjb = luatexja.base
98 load_module('rmlgbm');    local ltjr = luatexja.rmlgbm -- must be 1st
99
100 if luatexja_debug then load_module('debug') end
101
102 load_module('charrange'); local ltjc = luatexja.charrange
103 load_module('stack');     local ltjs = luatexja.stack
104 load_module('direction'); local ltjd = luatexja.direction -- +1 hlist +1 attr_list
105 load_module('jfont');     local ltjf = luatexja.jfont
106 load_module('inputbuf');  local ltji = luatexja.inputbuf
107 load_module('pretreat');  local ltjp = luatexja.pretreat
108 load_module('setwidth');  local ltjw = luatexja.setwidth
109 load_module('jfmglue');   local ltjj = luatexja.jfmglue -- +1 glue +1 gs +1 attr_list
110 load_module('math');      local ltjm = luatexja.math
111 load_module('base');    local ltjb = luatexja.base
112
113
114 local attr_jchar_class = luatexbase.attributes['ltj@charclass']
115 local attr_jchar_code = luatexbase.attributes['ltj@charcode']
116 local attr_curjfnt = luatexbase.attributes['ltj@curjfnt']
117 local attr_yablshift = luatexbase.attributes['ltj@yablshift']
118 local attr_icflag = luatexbase.attributes['ltj@icflag']
119 local attr_uniqid = luatexbase.attributes['ltj@uniqid']
120 local attr_dir = luatexbase.attributes['ltj@dir']
121 local cat_lp = luatexbase.catcodetables['latex-package']
122
123 -- Three aux. functions, bollowed from tex.web
124
125 local unity=65536
126 local floor = math.floor
127
128 local function print_scaled(s)
129    local out=''
130    local delta=10
131    if s<0 then
132       out=out..'-'; s=-s
133    end
134    out=out..tostring(floor(s/unity)) .. '.'
135    s=10*(s%unity)+5
136    repeat
137       if delta>unity then s=s+32768-50000 end
138       out=out .. tostring(floor(s/unity))
139       s=10*(s%unity)
140       delta=delta*10
141    until s<=delta
142    return out
143 end
144 luatexja.print_scaled = print_scaled
145
146 local function print_glue(d,order)
147    local out=print_scaled(d)
148    if order>0 then
149       out=out..'fi'
150       while order>1 do
151          out=out..'l'; order=order-1
152       end
153    else
154       out=out..'pt'
155    end
156    return out
157 end
158
159 local function print_spec(p)
160    local out=print_scaled(p.width)..'pt'
161    if p.stretch~=0 then
162       out=out..' plus '..print_glue(p.stretch,p.stretch_order)
163    end
164    if p.shrink~=0 then
165       out=out..' minus '..print_glue(p.shrink,p.shrink_order)
166    end
167 return out
168 end
169
170
171 ------------------------------------------------------------------------
172 -- CODE FOR GETTING/SETTING PARAMETERS
173 ------------------------------------------------------------------------
174
175 -- EXT: print parameters that don't need arguments
176 do
177    local tex_getattr = tex.getattribute
178    local function getattr(a)
179       local r = tex.getattribute(a)
180       return (r==-0x7FFFFFFF) and 0 or r
181    end 
182    luatexja.unary_pars = {
183       yalbaselineshift = function(t)
184          return print_scaled(getattr('ltj@yablshift'))..'pt'
185       end,
186       yjabaselineshift = function(t)
187          return print_scaled(getattr('ltj@ykblshift'))..'pt'
188       end,
189       talbaselineshift = function(t)
190          return print_scaled(getattr('ltj@tablshift'))..'pt'
191       end,
192       tjabaselineshift = function(t)
193          return print_scaled(getattr('ltj@tkblshift'))..'pt'
194       end,
195       kanjiskip = function(t)
196          return print_spec(ltjs.get_stack_skip(stack_table_index.KSK, t))
197       end,
198       xkanjiskip = function(t)
199          return print_spec(ltjs.get_stack_skip(stack_table_index.XSK, t))
200       end,
201       jcharwidowpenalty = function(t)
202          return ltjs.get_stack_table(stack_table_index.JWP, 0, t)
203       end,
204       autospacing = function(t)
205          return getattr('ltj@autospc')
206       end,
207       autoxspacing = function(t)
208          return getattr('ltj@autoxspc')
209       end,
210       differentjfm = function(t)
211          local f, r = luatexja.jfmglue.diffmet_rule, '???'
212          if f == math.max then r = 'large'
213          elseif f == math.min then r = 'small'
214          elseif f == math.two_average then r = 'average'
215          elseif f == math.two_paverage then r = 'paverage'
216          elseif f == math.two_pleft then r = 'pleft'
217          elseif f == math.two_pright then r = 'pright'
218          elseif f == math.two_add then r = 'both'
219          end
220          return r
221       end,
222       direction = function()
223          local v = ltjd.get_dir_count()
224          if math.abs(tex.nest[tex.nest.ptr].mode) == ltjs.mmode and v == dir_table.dir_tate then
225             v = dir_table.dir_utod
226          end
227          return v
228       end,
229       adjustdir = ltjd.get_adjust_dir_count,
230    }
231
232    local unary_pars = luatexja.unary_pars
233    function luatexja.ext_get_parameter_unary(k)
234       if unary_pars[k] then
235          tex.write(tostring(unary_pars[k](tex.getcount('ltj@@stack'))))
236       end
237       ltjb.stop_time_measure('get_par')
238    end
239 end
240
241
242 -- EXT: print parameters that need arguments
243 do
244    luatexja.binary_pars = {
245       jacharrange = function(c, t)
246          if type(c)~='number' or c<-1 or c>31*ltjc.ATTR_RANGE then
247             -- 0, -1 はエラーにしない(隠し)
248             ltjb.package_error('luatexja',
249                                'invalid character range number (' .. tostring(c) .. ')',
250                                'A character range number should be in the range 1..'
251                                   .. 31*ltjc.ATTR_RANGE .. ",\n"..
252                                   'So I changed this one to ' .. 31*ltjc.ATTR_RANGE .. ".")
253             c=0 -- external range 217 == internal range 0
254          elseif c==31*ltjc.ATTR_RANGE then c=0
255          end
256       -- 負の値は <U+0080 の文字の文字範囲,として出てくる.この時はいつも欧文文字なので 1 を返す
257          return (c<0) and 1 or ltjc.get_range_setting(c)
258       end,
259       prebreakpenalty = function(c, t)
260          return ltjs.get_stack_table(stack_table_index.PRE
261                                           + ltjb.in_unicode(c, true), 0, t)
262       end,
263       postbreakpenalty = function(c, t)
264          return ltjs.get_stack_table(stack_table_index.POST
265                                           + ltjb.in_unicode(c, true), 0, t)
266       end,
267       kcatcode = function(c, t)
268          return ltjs.get_stack_table(stack_table_index.KCAT
269                                           + ltjb.in_unicode(c, false), 0, t)
270       end,
271       chartorange = function(c, t)
272          return ltjc.char_to_range(ltjb.in_unicode(c, false))
273       end,
274       jaxspmode = function(c, t)
275          return ltjs.get_stack_table(stack_table_index.XSP
276                                           + ltjb.in_unicode(c, true), 3, t)
277       end,
278       boxdir = function(c, t)
279          if type(c)~='number' or c<0 or c>65535 then
280             ltjb.package_error('luatexja',
281                                'Bad register code (' .. tostring(c) .. ')',
282                                'A register must be between 0 and 65535.\n'..
283                                   'I changed this one to zero.')
284             c=0
285          end
286          return ltjd.get_register_dir(c)
287       end,
288    }
289    local binary_pars = luatexja.binary_pars
290
291    binary_pars.alxspmode = binary_pars.jaxspmode
292    function luatexja.ext_get_parameter_binary(k,c)
293       if binary_pars[k] then
294          tex.write(tostring(binary_pars[k](c,tex.getcount('ltj@@stack'))))
295       end
296       ltjb.stop_time_measure('get_par')
297    end
298 end
299
300 -- EXT: print \global if necessary
301 function luatexja.ext_print_global()
302    if luatexja.isglobal=='global' then tex.sprint(cat_lp, '\\global') end
303 end
304
305
306 -- main process
307 do
308    local start_time_measure, stop_time_measure
309       = ltjb.start_time_measure, ltjb.stop_time_measure
310    local nullfunc = function (n) return n end
311    local to_node = node.direct.tonode
312    local to_direct = node.direct.todirect
313    local ensure_tex_attr = ltjb.ensure_tex_attr
314
315    -- mode = true iff main_process is called from pre_linebreak_filter
316    local function main_process(head, mode, dir, gc)
317       ensure_tex_attr(attr_icflag, 0)
318       if gc == 'fin_row' then return head
319       else
320             --luatexja.ext_show_node_list(head, 'T> ', print)
321             start_time_measure('jfmglue')
322             local p = ltjj.main(to_direct(head),mode, dir)
323             stop_time_measure('jfmglue')
324             return to_node(p)
325       end
326    end
327
328    local function adjust_icflag(h)
329       -- kern from luaotfload will have icflag = 1
330       -- (same as italic correction)
331       ensure_tex_attr(attr_icflag, 1)
332       return h
333    end
334
335    -- callbacks
336    ltjb.add_to_callback(
337       'pre_linebreak_filter',
338       function (head,groupcode)
339          return main_process(head, true, tex.textdir, groupcode)
340       end,'ltj.main',
341       luatexbase.priority_in_callback('pre_linebreak_filter', 'luaotfload.node_processor')+1)
342    ltjb.add_to_callback(
343       'hpack_filter',
344       function (head,groupcode,size,packtype, dir)
345          return main_process(head, false, dir, groupcode)
346       end,'ltj.main',
347       luatexbase.priority_in_callback('hpack_filter', 'luaotfload.node_processor')+1)
348    ltjb.add_to_callback('pre_linebreak_filter', adjust_icflag, 'ltj.adjust_icflag', 1)
349    ltjb.add_to_callback('hpack_filter', adjust_icflag, 'ltj.adjust_icflag', 1)
350
351 end
352
353 -- cleanup process
354 function luatexja.ext_cleanup()
355    ltjf.cleanup_size_cache()
356    ltjd.remove_end_whatsit()
357 end
358
359
360 -- lastnodechar
361 do
362    local id_glyph = node.id('glyph')
363    function luatexja.pltx_composite_last_node_char()
364       local n = tex.nest[tex.nest.ptr].tail
365       local r = '-1'
366       if n then
367          if n.id==id_glyph then
368             while n.componetns and  n.subtype and n.subtype%4 >= 2 do
369                n = node.tail(n)
370             end
371             r = tostring(n.char)
372          end
373       end
374       tex.sprint(r)
375    end
376 end
377
378 -- debug
379
380 do
381
382 local node_type = node.type
383 local node_next = node.next
384 local has_attr = node.has_attribute
385
386 local id_penalty = node.id('penalty')
387 local id_glyph = node.id('glyph')
388 local id_glue = node.id('glue')
389 local id_kern = node.id('kern')
390 local id_hlist = node.id('hlist')
391 local id_vlist = node.id('vlist')
392 local id_rule = node.id('rule')
393 local id_math = node.id('math')
394 local id_whatsit = node.id('whatsit')
395 local sid_user = node.subtype('user_defined')
396
397 local function get_attr_icflag(p)
398    return (has_attr(p, attr_icflag) or 0) % icflag_table.PROCESSED_BEGIN_FLAG
399 end
400
401 local prefix, inner_depth
402
403 local function debug_show_node_X(p,print_fn, limit)
404    local k = prefix
405    local s
406    local pt=node_type(p.id)
407    local base = prefix .. string.format('%X', get_attr_icflag(p))
408    .. ' ' .. pt .. ' ' .. tostring(p.subtype) .. ' '
409    if pt == 'glyph' then
410       s = base .. ' ' .. 
411          (p.char>=0xF0000 and string.format('(U+%X)', p.char) or utf.char(p.char)) .. ' '
412          .. tostring(p.font) .. ' (' .. print_scaled(p.height) .. '+'
413          .. print_scaled(p.depth) .. ')x' .. print_scaled(p.width)
414       if p.xoffset~=0 or p.yoffset~=0 then
415          s = s .. ' off: (' .. print_scaled(p.xoffset)
416                .. ',' .. print_scaled(p.yoffset) .. ')'
417       end
418       print_fn(s)
419    elseif pt=='hlist' or pt=='vlist' or pt=='unset'or pt=='ins' then
420       if pt=='ins' then
421          s = base .. '(' .. print_scaled(p.height) .. '+'
422             .. print_scaled(p.depth) .. ')'
423             .. ', dir=' .. tostring(node.has_attribute(p, attr_dir))
424       else
425          s = base .. '(' .. print_scaled(p.height) .. '+'
426             .. print_scaled(p.depth) .. ')x' .. print_scaled(p.width)
427             .. ', dir=' .. tostring(node.has_attribute(p, attr_dir))
428       end
429       if (p.shift or 0)~=0 then
430          s = s .. ', shifted ' .. print_scaled(p.shift)
431       end
432       if p.glue_set and p.glue_sign ==2 or ( p.glue_sign==1 and p.glue_set>0) then
433          s = s .. ' glue set '
434          if p.glue_sign == 2 then s = s .. '-' end
435          s = s .. tostring(floor(p.glue_set*10000)/10000)
436          if p.glue_order == 0 then
437             s = s .. 'pt'
438          else
439             s = s .. 'fi'
440             for i = 2,  p.glue_order do s = s .. 'l' end
441          end
442       end
443       if get_attr_icflag(p) == icflag_table.PACKED then
444          s = s .. ' (packed)'
445       end
446       print_fn(s);
447       local bid = inner_depth
448       prefix, inner_depth = prefix.. '.', inner_depth + 1
449       if inner_depth < limit then
450          for q in node.traverse(p.head) do
451             debug_show_node_X(q, print_fn, limit)
452          end
453       end
454       prefix=k
455    elseif pt=='rule' then
456       s = base .. '(' .. print_scaled(p.height) .. '+'
457          .. print_scaled(p.depth) .. ')x' .. print_scaled(p.width)
458          .. ', dir=' .. tostring(node.has_attribute(p, attr_dir))
459       print_fn(s)
460    elseif pt == 'glue' then
461       s = base .. ' ' ..  print_spec(p)
462       if get_attr_icflag(p)>icflag_table.KINSOKU
463          and get_attr_icflag(p)<icflag_table.KANJI_SKIP then
464          s = s .. ' (from JFM: priority ' .. get_attr_icflag(p)-icflag_table.FROM_JFM .. ')'
465       elseif get_attr_icflag(p)==icflag_table.KANJI_SKIP then
466          s = s .. ' (kanjiskip)'
467       elseif get_attr_icflag(p)==icflag_table.KANJI_SKIP_JFM then
468          s = s .. ' (kanjiskip, JFM specified)'
469       elseif get_attr_icflag(p)==icflag_table.XKANJI_SKIP then
470          s = s .. ' (xkanjiskip)'
471       elseif get_attr_icflag(p)==icflag_table.XKANJI_SKIP_JFM then
472          s = s .. ' (xkanjiskip, JFM specified)'
473       end
474       print_fn(s)
475    elseif pt == 'kern' then
476       s = base .. ' ' .. print_scaled(p.kern) .. 'pt'
477       if p.subtype==2 then
478          s = s .. ' (for accent)'
479       elseif get_attr_icflag(p)==icflag_table.IC_PROCESSED then
480          s = s .. ' (italic correction)'
481       elseif get_attr_icflag(p)==icflag_table.LINEEND then
482          s = s .. ' (end-of-line)'
483          -- elseif get_attr_icflag(p)==ITALIC then
484          --    s = s .. ' (italic correction)'
485       elseif get_attr_icflag(p)>icflag_table.KINSOKU
486          and get_attr_icflag(p)<icflag_table.KANJI_SKIP then
487          s = s .. ' (from JFM: priority ' .. get_attr_icflag(p)-icflag_table.FROM_JFM .. ')'
488       end
489       print_fn(s)
490    elseif pt == 'penalty' then
491       s = base .. ' ' .. tostring(p.penalty)
492       if get_attr_icflag(p)==icflag_table.KINSOKU then
493          s = s .. ' (for kinsoku)'
494       end
495       print_fn(s)
496    elseif pt == 'whatsit' then
497       s = base
498       if p.subtype==sid_user then
499          local t = tostring(p.user_id) .. ' (' ..
500             luatexbase.get_user_whatsit_name(p.user_id) .. ') '
501          if p.type ~= 110 then
502             s = s .. ' userid:' .. t .. p.value
503             print_fn(s)
504          else
505             s = s .. ' userid:' .. t .. '(node list)'
506             if p.user_id==userid_table.DIR then
507                s = s .. ' dir: ' .. tostring(node.has_attribute(p, attr_dir))
508             end
509             print_fn(s)
510             local bid = inner_depth
511             prefix, inner_depth =prefix.. '.', inner_depth + 1
512             if inner_depth < limit then
513                for q in node.traverse(p.value) do
514                   debug_show_node_X(q, print_fn, limit)
515                end
516             end
517             prefix, inner_depth = k, bid
518          end
519       else
520          s = s .. (node.subtype(p.subtype) or '')
521          if p.subtype==1 then
522             s = s .. ' stream=' .. p.stream
523             print_fn(s)
524             for i=1,#p.data do
525                print_fn(s .. '  [' .. i .. '] = ' .. tostring(p.data[i].csname))
526             end
527          else
528             print_fn(s)
529          end
530       end
531    -------- math node --------
532    elseif pt=='noad' then
533       s = base ; print_fn(s)
534       if p.nucleus then
535          prefix = k .. 'N'; debug_show_node_X(p.nucleus, print_fn, limit);
536       end
537       if p.sup then
538          prefix = k .. '^'; debug_show_node_X(p.sup, print_fn, limit);
539       end
540       if p.sub then
541          prefix = k .. '_'; debug_show_node_X(p.sub, print_fn, limit);
542       end
543       prefix = k;
544    elseif pt=='math_char' then
545       s = base .. ' fam: ' .. p.fam .. ' , char = ' .. utf.char(p.char)
546       print_fn(s)
547    elseif pt=='sub_box' or pt=='sub_mlist' then
548       print_fn(base)
549       if p.head then
550          prefix = k .. '.';
551          for q in node.traverse(p.head) do
552             debug_show_node_X(q, print_fn)
553          end
554       end
555    else
556       print_fn(base)
557    end
558    p=node_next(p)
559 end
560 function luatexja.ext_show_node_list(head,depth,print_fn, lim)
561    prefix = depth
562    inner_depth = 0
563    if head then
564       while head do
565          debug_show_node_X(head, print_fn, lim or 1/0); head = node_next(head)
566       end
567    else
568       print_fn(prefix .. ' (null list)')
569    end
570 end
571 function luatexja.ext_show_node(head,depth,print_fn, lim)
572    prefix = depth
573    inner_depth = 0
574    if head then
575       debug_show_node_X(head, print_fn, lim or 1/0)
576    else
577       print_fn(prefix .. ' (null list)')
578    end
579 end
580
581 end