OSDN Git Service

typo in ltj-jfmglue.lua
[luatex-ja/luatexja.git] / src / ltj-jfont.lua
1 --
2 -- luatexja/jfont.lua
3 --
4 luatexbase.provides_module({
5   name = 'luatexja.jfont',
6   date = '2014/01/23',
7   description = 'Loader for Japanese fonts',
8 })
9 module('luatexja.jfont', package.seeall)
10
11 luatexja.load_module('base');      local ltjb = luatexja.base
12 luatexja.load_module('charrange'); local ltjc = luatexja.charrange
13
14 local mem_leak_glue, mem_leak_gs, mem_leak_kern = 0, 0, 0
15
16 local Dnode = node.direct or node
17
18 local setfield = (Dnode ~= node) and Dnode.setfield or function(n, i, c) n[i] = c end
19 local getid = (Dnode ~= node) and Dnode.getid or function(n) return n.id end
20 local getfont = (Dnode ~= node) and Dnode.getfont or function(n) return n.font end
21 local getchar = (Dnode ~= node) and Dnode.getchar or function(n) return n.char end
22
23 local nullfunc = function(n) return n end
24 local to_direct = (Dnode ~= node) and Dnode.todirect or nullfunc
25
26 local node_new = Dnode.new
27 local node_free = Dnode.free
28 local has_attr = Dnode.has_attribute
29 local set_attr = Dnode.set_attribute
30 local node_write = Dnode.write
31 local round = tex.round
32 local font_getfont = font.getfont
33
34 local attr_icflag = luatexbase.attributes['ltj@icflag']
35 local attr_curjfnt = luatexbase.attributes['ltj@curjfnt']
36 local id_glyph = node.id('glyph')
37 local id_kern = node.id('kern')
38 local id_glue_spec = node.id('glue_spec')
39 local id_glue = node.id('glue')
40 local cat_lp = luatexbase.catcodetables['latex-package']
41 local ITALIC       = luatexja.icflag_table.ITALIC
42 local FROM_JFM     = luatexja.icflag_table.FROM_JFM
43
44 ------------------------------------------------------------------------
45 -- LOADING JFM
46 ------------------------------------------------------------------------
47
48 metrics={} -- this table stores all metric informations
49 font_metric_table={} -- [font number] -> jfm_name, jfm_var, size
50
51 luatexbase.create_callback("luatexja.load_jfm", "data", function (ft, jn) return ft end)
52
53 local jfm_file_name, jfm_var
54 local defjfm_res
55
56 function define_jfm(t)
57    local real_char -- Does current character class have the 'real' character?
58    if t.dir~='yoko' then
59       defjfm_res= nil; return
60    elseif type(t.zw)~='number' or type(t.zh)~='number' then 
61       defjfm_res= nil; return
62    end
63    t.char_type = {}; t.chars = {}
64    for i,v in pairs(t) do
65       if type(i) == 'number' then -- char_type
66          if not v.chars then
67             if i ~= 0 then defjfm_res= nil; return  end
68             real_char = true
69          else
70             real_char = false
71             for j,w in pairs(v.chars) do
72                if type(w) == 'number' then
73                   real_char = true;
74                elseif type(w) == 'string' and utf.len(w)==1 then
75                   real_char = true; w = utf.byte(w)
76                elseif type(w) == 'string' and utf.len(w)==2 and utf.sub(w,2) == '*' then
77                   real_char = true; w = utf.byte(utf.sub(w,1,1))
78                   if not t.chars[-w] then 
79                      t.chars[-w] = i
80                   else 
81                      defjfm_res= nil; return
82                   end
83                end
84                if not t.chars[w] then
85                   t.chars[w] = i
86                else 
87                   defjfm_res= nil; return
88                end
89             end
90             if type(v.align)~='string' then 
91                v.align = 'left' -- left
92             end
93             if real_char then
94                if not (type(v.width)=='number' or v.width~='prop') then
95                   defjfm_res= nil; return
96                else
97                   if type(v.height)~='number' then
98                      v.height = 0.0
99                   end
100                   if type(v.depth)~='number' then
101                      v.depth = 0.0
102                   end
103                   if type(v.italic)~='number' then 
104                      v.italic = 0.0
105                   end
106                   if type(v.left)~='number' then 
107                      v.left = 0.0
108                   end
109                   if type(v.down)~='number' then 
110                      v.down = 0.0
111                   end
112                end
113             end
114             v.chars = nil
115          end
116          v.kern = v.kern or {}; v.glue = v.glue or {}
117          for j in pairs(v.glue) do
118             if v.kern[j] then defjfm_res= nil; return end
119          end
120          for j,x in pairs(v.kern) do
121             if type(x)=='number' then 
122                v.kern[j] = {x, 0}
123             elseif type(x)=='table' then 
124                v.kern[j] = {x[1], x[2] or 0}
125             end
126          end
127          t.char_type[i] = v
128          t[i] = nil
129       end
130    end
131    t = luatexbase.call_callback("luatexja.load_jfm", t, jfm_file_name)
132    t.size_cache = {}
133    defjfm_res = t
134 end
135
136 local update_jfm_cache
137 do
138    local function mult_table(old,scale) -- modified from table.fastcopy
139       if old then
140          local new = { }
141          for k,v in next, old do
142             if type(v) == "table" then
143                new[k] = mult_table(v,scale)
144             elseif type(v) == "number" then
145                new[k] = round(v*scale)
146             else
147                new[k] = v
148             end
149          end
150          return new
151       else return nil end
152    end
153    
154    update_jfm_cache = function (j,sz)
155       if metrics[j].size_cache[sz] then return end
156       local t = {}
157       metrics[j].size_cache[sz] = t
158       t.chars = metrics[j].chars
159       t.char_type = mult_table(metrics[j].char_type, sz)
160       for i,v in pairs(t.char_type) do
161          if type(i) == 'number' then -- char_type
162             for k,w in pairs(v.glue) do
163                local h = node_new(id_glue_spec)
164 mem_leak_gs = mem_leak_gs+1
165                v[k] = {true, h, (w[5] and w[5]/sz or 0), FROM_JFM + (w[4] and w[4]/sz or 0)}
166                setfield(h, 'width', w[1])
167                setfield(h, 'stretch', w[2])
168                setfield(h, 'shrink', w[3])
169                setfield(h, 'stretch_order', 0)
170                setfield(h, 'shrink_order', 0)
171             end
172             for k,w in pairs(v.kern) do
173                local g = node_new(id_kern)
174 mem_leak_kern = mem_leak_kern +1
175                setfield(g, 'kern', w[1])
176                setfield(g, 'subtype', 1)
177                set_attr(g, attr_icflag, FROM_JFM)
178                v[k] = {false, g, w[2]/sz}
179             end
180          end
181       end
182       t.kanjiskip = mult_table(metrics[j].kanjiskip, sz)
183       t.xkanjiskip = mult_table(metrics[j].xkanjiskip,sz)
184       t.zw = round(metrics[j].zw*sz)
185       t.zh = round(metrics[j].zh*sz)
186    end
187 end
188
189 luatexbase.create_callback("luatexja.find_char_class", "data", 
190                            function (arg, fmtable, char)
191                               return 0
192                            end)
193
194 function find_char_class(c,m)
195 -- c: character code, m: 
196    if not m then return 0 end
197    return m.chars[c] or 
198       luatexbase.call_callback("luatexja.find_char_class", 0, m, c)
199 end
200
201
202 ------------------------------------------------------------------------
203 -- LOADING JAPANESE FONTS
204 ------------------------------------------------------------------------
205
206 do
207    local cstemp
208    local global_flag -- true if \globaljfont, false if \jfont
209    local function load_jfont_metric()
210       if jfm_file_name=='' then 
211          ltjb.package_error('luatexja',
212                             'no JFM specified',
213                             'To load and define a Japanese font, a JFM must be specified.'..
214                             "The JFM 'ujis' will be  used for now.")
215          jfm_file_name='ujis'
216       end
217       for j,v in ipairs(metrics) do 
218          if v.name==jfm_file_name then return j end
219       end
220       luatexja.load_lua('jfm-' .. jfm_file_name .. '.lua')
221       if defjfm_res then
222          defjfm_res.name = jfm_file_name
223          table.insert(metrics, defjfm_res)
224          return #metrics
225       else 
226          return nil
227       end
228    end
229
230 -- EXT
231    function jfontdefX(g)
232       local t = token.get_next()
233       cstemp=token.csname_name(t)
234       global_flag = g and '\\global' or ''
235       tex.sprint(cat_lp, '\\expandafter\\font\\csname ' .. cstemp .. '\\endcsname')
236    end
237    
238    luatexbase.create_callback("luatexja.define_jfont", "data", function (ft, fn) return ft end)
239
240 -- EXT
241    function jfontdefY() -- for horizontal font
242       local j = load_jfont_metric()
243       local fn = font.id(cstemp)
244       local f = font_getfont(fn)
245       if not j then 
246          ltjb.package_error('luatexja',
247                             "bad JFM `" .. jfm_file_name .. "'",
248                             'The JFM file you specified is not valid JFM file.\n'..
249                                'So defining Japanese font is cancelled.')
250          tex.sprint(cat_lp, global_flag .. '\\expandafter\\let\\csname ' ..cstemp 
251                        .. '\\endcsname=\\relax')
252          return 
253       end
254       update_jfm_cache(j, f.size)
255       --print('MEMORY LEAK (acc): ', mem_leak_glue, mem_leak_gs, mem_leak_kern)
256       local sz = metrics[j].size_cache[f.size]
257       local fmtable = { jfm = j, size = f.size, var = jfm_var, 
258                         zw = sz.zw, zh = sz.zh, 
259                         chars = sz.chars, char_type = sz.char_type,
260                         kanjiskip = sz.kanjiskip, xkanjiskip = sz.xkanjiskip, 
261       }
262       
263       fmtable = luatexbase.call_callback("luatexja.define_jfont", fmtable, fn)
264       font_metric_table[fn]=fmtable
265       tex.sprint(cat_lp, global_flag .. '\\protected\\expandafter\\def\\csname ' 
266                     .. cstemp  .. '\\endcsname{\\ltj@curjfnt=' .. fn .. '\\relax}')
267    end
268 end
269
270 do
271 -- EXT: zw, zh
272    function load_zw()
273       local a = font_metric_table[tex.attribute[attr_curjfnt]]
274       tex.setdimen('ltj@zw', a and a.zw or 0)
275    end
276    
277    function load_zh()
278       local a = font_metric_table[tex.attribute[attr_curjfnt]]
279       tex.setdimen('ltj@zh', a and a.zh or 0)
280    end
281 end
282
283 do
284    -- extract jfm_file_name and jfm_var
285    local function extract_metric(name)
286       local basename=name
287       local tmp = utf.sub(basename, 1, 5)
288       jfm_file_name = ''; jfm_var = ''
289       if tmp == 'file:' or tmp == 'name:' or tmp == 'psft:' then
290          basename = utf.sub(basename, 6)
291       end
292       local p = utf.find(basename, ":")
293       if p then 
294          basename = utf.sub(basename, p+1)
295       else return 
296       end
297       -- now basename contains 'features' only.
298       p=1
299       while p do
300          local q = utf.find(basename, ";", p+1) or utf.len(basename)+1
301          if utf.sub(basename, p, p+3)=='jfm=' and q>p+4 then
302             jfm_file_name = utf.sub(basename, p+4, q-1)
303          elseif utf.sub(basename, p, p+6)=='jfmvar=' and q>p+6 then
304             jfm_var = utf.sub(basename, p+7, q-1)
305          end
306          if utf.len(basename)+1==q then p = nil else p = q + 1 end
307       end
308       return
309    end
310    
311    -- replace fonts.define.read()
312    function font_callback(name, size, id, fallback)
313       extract_metric(name)
314       -- In the present imple., we don't remove "jfm=..." from name.
315       return fallback(name, size, id)
316    end
317 end
318
319 ------------------------------------------------------------------------
320 -- LATEX INTERFACE
321 ------------------------------------------------------------------------
322 do
323    local kyenc_list, ktenc_list = {}, {}
324    function add_kyenc_list(enc) kyenc_list[enc] = 'true ' end
325    function add_ktenc_list(enc) ktenc_list[enc] = 'true ' end
326    function is_kyenc(enc)
327       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (kyenc_list[enc] or 'false '))
328    end
329    function is_kyenc(enc) 
330       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (kyenc_list[enc] or 'false '))
331    end
332    function is_kenc(enc) 
333       tex.sprint(cat_lp, '\\let\\ifin@\\if' 
334                  .. (kyenc_list[enc] or ktenc_list[enc] or 'false '))
335    end
336
337    local kfam_list, Nkfam_list = {}, {}
338    function add_kfam_list(enc, fam)
339       if not kfam_list[enc] then kfam_list[enc] = {} end
340       kfam_list[enc][fam] = 'true '
341    end
342    function add_Nkfam_list(enc, fam)
343       if not Nkfam_list[enc] then Nkfam_list[enc] = {} end
344       Nkfam_list[enc][fam] = 'true '
345    end
346    function is_kfam(enc, fam)
347       tex.sprint(cat_lp, '\\let\\ifin@\\if' 
348                  .. (kfam_list[enc] and kfam_list[enc][fam] or 'false ')) end
349    function is_Nkfam(enc, fam)
350       tex.sprint(cat_lp, '\\let\\ifin@\\if' 
351                  .. (Nkfam_list[enc] and Nkfam_list[enc][fam] or 'false ')) end
352
353    local ffam_list, Nffam_list = {}, {}
354    function add_ffam_list(enc, fam)
355       if not ffam_list[enc] then ffam_list[enc] = {} end
356       ffam_list[enc][fam] = 'true '
357    end
358    function add_Nffam_list(enc, fam)
359       if not Nffam_list[enc] then Nffam_list[enc] = {} end
360       Nffam_list[enc][fam] = 'true '
361    end
362    function is_ffam(enc, fam)
363       tex.sprint(cat_lp, '\\let\\ifin@\\if' 
364                  .. (ffam_list[enc] and ffam_list[enc][fam] or 'false ')) end
365    function is_Nffam(enc, fam)
366       tex.sprint(cat_lp, '\\let\\ifin@\\if' 
367                  .. (Nffam_list[enc] and Nffam_list[enc][fam] or 'false ')) end
368 end
369 ------------------------------------------------------------------------
370 -- ALTERNATE FONTS
371 ------------------------------------------------------------------------
372 alt_font_table = {}
373 local alt_font_table = alt_font_table
374 local attr_curaltfnt = {}
375 local ucs_out = 0x110000
376
377 ------ for TeX interface
378 -- EXT
379 function set_alt_font(b,e,ind,bfnt)
380    -- ind: 新フォント, bfnt: 基底フォント
381    if b>e then b, e = e, b end
382    if b*e<=0 then
383       ltjb.package_eror('luatexja',
384                         'bad character range ([' .. b .. ',' .. e .. ']). ' ..
385                            'I take the intersection with [0x80, 0x10ffff].')
386       b, e = math.max(0x80,b),math.min(ucs_out-1,e)
387    elseif e<0 then -- b<e<0
388       -- do nothing
389    elseif b<0x80 or e>=ucs_out then
390       ltjb.package_warning('luatexja',
391                            'bad character range ([' .. b .. ',' .. e .. ']). ' ..
392                               'I take the intersection with [0x80, 0x10ffff].')
393       b, e = math.max(0x80,b), math.min(ucs_out-1,e)
394    end
395    if not alt_font_table[bfnt] then alt_font_table[bfnt]={} end
396    local t = alt_font_table[bfnt]
397    local ac = font_getfont(ind).characters
398    if bfnt==ind then ind = nil end -- ind == bfnt の場合はテーブルから削除
399    if e>=0 then -- character range
400       for i=b, e do
401          if ac[i]then  t[i]=ind end
402       end
403    else
404       b, e = -e, -b
405       local tx = font_metric_table[bfnt].chars
406       for i,v in pairs(tx) do
407          if b<=v and v<=e and ac[i] then t[i]=ind end
408       end
409    end
410 end
411
412 -- EXT
413 function clear_alt_font(bfnt)
414    if alt_font_table[bfnt] then 
415       local t = alt_font_table[bfnt]
416       for i,_ in pairs(t) do t[i]=nil; end
417    end
418 end
419
420 ------ used in ltjp.suppress_hyphenate_ja callback
421 function replace_altfont(pf, pc)
422    local a = alt_font_table[pf]
423    return a and a[pc] or pf
424 end
425
426 ------ for LaTeX interface
427
428 local alt_font_table_latex = {}
429
430 -- EXT
431 function clear_alt_font_latex(bbase)
432    local t = alt_font_table_latex[bbase]
433    if t then
434       for j,v in pairs(t) do t[j] = nil end 
435    end
436 end
437
438 -- EXT
439 function set_alt_font_latex(b,e,ind,bbase)
440    -- ind: Alt font の enc/fam/ser/shape, bbase: 基底フォントの enc/fam/ser/shape
441    if b>e then b, e = e, b end
442    if b*e<=0 then
443       ltjb.package_eror('luatexja',
444                         'bad character range ([' .. b .. ',' .. e .. ']). ' ..
445                            'I take the intersection with [0x80, 0x10ffff].')
446       b, e = math.max(0x80,b),math.min(ucs_out-1,e)
447    elseif e<0 then -- b<e<0
448       -- do nothing
449    elseif b<0x80 or e>=ucs_out then
450       ltjb.package_warning('luatexja',
451                            'bad character range ([' .. b .. ',' .. e .. ']). ' ..
452                               'I take the intersection with [0x80, 0x10ffff].')
453       b, e = math.max(0x80,b), math.min(ucs_out-1,e)
454    end
455
456    if not alt_font_table_latex[bbase] then alt_font_table_latex[bbase]={} end
457    local t = alt_font_table_latex[bbase]
458    if not t[ind] then t[ind] = {} end
459    for i=b, e do
460       for j,v in pairs(t) do
461          if v[i] then -- remove old entry
462             if j~=ind then v[i]=nil end; break
463          end
464       end
465       t[ind][i]=true
466    end
467    -- remove the empty tables
468    for j,v in pairs(t) do
469       local flag_clear = true
470       for k,_ in pairs(v) do flag_clear = false; break end
471       if flag_clear then t[j]=nil end
472    end
473    if ind==bbase  then t[bbase] = nil end
474 end
475
476 -- ここから先は 新 \selectfont の内部でしか実行されない
477 do
478    local alt_font_base, alt_font_base_num
479    local aftl_base
480    -- EXT
481    function does_alt_set(bbase)
482       aftl_base = alt_font_table_latex[bbase]
483       tex.sprint(cat_lp, '\\if' .. (aftl_base and 'true' or 'false'))
484    end
485    -- EXT
486    function print_aftl_address()
487       tex.sprint(cat_lp, ';ltjaltfont' .. tostring(aftl_base):sub(8))
488    end
489
490 -- EXT
491    function output_alt_font_cmd(bbase)
492       alt_font_base = bbase
493       alt_font_base_num = tex.getattribute(attr_curjfnt)
494       local t = alt_font_table[alt_font_base_num]
495       if t then 
496          for i,_ in pairs(t) do t[i]=nil end
497       end
498       t = alt_font_table_latex[bbase]
499       if t then
500          for i,_ in pairs(t) do
501             tex.sprint(cat_lp, '\\ltj@pickup@altfont@aux{' .. i .. '}')
502          end
503       end
504    end
505
506 -- EXT
507    function pickup_alt_font_a(size_str)
508       local t = alt_font_table_latex[alt_font_base]
509       if t then
510          for i,v in pairs(t) do
511             tex.sprint(cat_lp, '\\expandafter\\ltj@pickup@altfont@copy'
512                           .. '\\csname ' .. i .. '/' .. size_str .. '\\endcsname{' .. i .. '}')
513          end
514       end
515    end 
516
517    local function pickup_alt_font_class(class, afnt_num, afnt_chars)
518       local t  = alt_font_table[alt_font_base_num] 
519       local tx = font_metric_table[alt_font_base_num].chars
520       for i,v in pairs(tx) do
521          if v==class and afnt_chars[i] then t[i]=afnt_num end
522       end
523    end
524
525 -- EXT
526    function pickup_alt_font_b(afnt_num, afnt_base)
527       local t = alt_font_table[alt_font_base_num]
528       local ac = font_getfont(afnt_num).characters
529       if not t then t = {}; alt_font_table[alt_font_base_num] = t end
530       for i,v in pairs(alt_font_table_latex[alt_font_base]) do
531          if i == afnt_base then
532             for j,_ in pairs(v) do
533                if j>=0 then 
534                   if ac[j] then t[j]=afnt_num end
535                else  -- -n (n>=1) means that the character class n,
536                      -- which is defined in the JFM 
537                   pickup_alt_font_class(-j, afnt_num, ac) 
538                end
539             end
540             return
541          end
542       end
543    end
544
545 end
546
547
548 ------------------------------------------------------------------------
549 -- MISC
550 ------------------------------------------------------------------------
551
552 local is_ucs_in_japanese_char = ltjc.is_ucs_in_japanese_char_direct
553 -- EXT: italic correction
554 function append_italic()
555    local p = to_direct(tex.nest[tex.nest.ptr].tail)
556    if p and getid(p)==id_glyph then
557       local f = getfont(p)
558       local g = node_new(id_kern)
559       setfield(g, 'subtype', 1)
560       set_attr(g, attr_icflag, ITALIC)
561       if is_ucs_in_japanese_char(p) then
562          f = has_attr(p, attr_curjfnt)
563          local j = font_metric_table[f]
564          setfield(g, 'kern', j.char_type[find_char_class(getchar(p), j)].italic)
565       else
566          local h = font_getfont(f)
567          if h then
568             setfield(g, 'kern', h.characters[getchar(p)].italic)
569          else
570             tex.attribute[attr_icflag] = 0
571             return node_free(g)
572          end
573       end
574       node_write(g)
575       tex.attribute[attr_icflag] = 0
576    end
577 end