OSDN Git Service

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