OSDN Git Service

3c028af75253df79dd43c800a83035ffcef89491
[luatex-ja/luatexja.git] / src / ltj-jfont.lua
1 --
2 -- luatexja/jfont.lua
3 --
4 luatexbase.provides_module({
5   name = 'luatexja.jfont',
6   date = '2015/09/19',
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 luatexja.load_module('rmlgbm');    local ltjr = luatexja.rmlgbm
14 luatexja.load_module('direction'); local ltjd = luatexja.direction
15
16
17 local Dnode = node.direct or node
18
19 local setfield = (Dnode ~= node) and Dnode.setfield or function(n, i, c) n[i] = c end
20 local getid = (Dnode ~= node) and Dnode.getid or function(n) return n.id end
21
22 local nullfunc = function(n) return n end
23 local to_direct = (Dnode ~= node) and Dnode.todirect or nullfunc
24
25 local node_new = Dnode.new
26 local node_free = Dnode.free
27 local has_attr = Dnode.has_attribute
28 local set_attr = Dnode.set_attribute
29 local round = tex.round
30 local font_getfont = font.getfont
31
32 local attr_icflag = luatexbase.attributes['ltj@icflag']
33 local attr_curjfnt = luatexbase.attributes['ltj@curjfnt']
34 local attr_curtfnt = luatexbase.attributes['ltj@curtfnt']
35 local id_glyph = node.id('glyph')
36 local id_kern = node.id('kern')
37 local id_glue_spec = node.id('glue_spec')
38 local id_glue = node.id('glue')
39 local cat_lp = luatexbase.catcodetables['latex-package']
40 local FROM_JFM     = luatexja.icflag_table.FROM_JFM
41 local tokenlib = luatexja.token
42 ------------------------------------------------------------------------
43 -- LOADING JFM
44 ------------------------------------------------------------------------
45
46 metrics={} -- this table stores all metric informations
47 font_metric_table={} -- [font number] -> jfm_name, jfm_var, size
48
49 luatexbase.create_callback("luatexja.load_jfm", "data", function (ft, jn) return ft end)
50
51 local jfm_file_name, jfm_var, jfm_ksp
52 local defjfm_res
53 local jfm_dir, is_def_jfont, is_vert_enabled
54
55 local function norm_val(a)
56    if (not a) or (a==0.) then
57       return nil
58    elseif a==true then
59       return 1
60    else
61       return a
62    end
63 end
64
65 function define_jfm(t)
66    local real_char -- Does current character class have the 'real' character?
67    if t.dir~=jfm_dir then
68       defjfm_res= nil; return
69    elseif type(t.zw)~='number' or type(t.zh)~='number' then
70       defjfm_res= nil; return
71    end
72    t.char_type = {}; t.chars = {}
73    for i,v in pairs(t) do
74       if type(i) == 'number' then -- char_type
75          if not v.chars then
76             if i ~= 0 then defjfm_res= nil; return  end
77          else
78             for j,w in pairs(v.chars) do
79                if type(w) == 'number' and w~=-1 then
80                elseif type(w) == 'string' and utf.len(w)==1 then
81                   w = utf.byte(w)
82                elseif type(w) == 'string' and utf.len(w)==2 and utf.sub(w,2) == '*' then
83                   w = utf.byte(utf.sub(w,1,1))
84                end
85                if not t.chars[w] then
86                   t.chars[w] = i
87                else
88                   defjfm_res= nil; return
89                end
90             end
91             v.chars = nil
92          end
93          if type(v.align)~='string' then
94             v.align = 'left' -- left
95          end
96          if type(v.width)~='number' then
97             v.width = (jfm_dir=='tate') and  1.0
98          end
99          if type(v.height)~='number' then
100             v.height = (jfm_dir=='tate') and  0.0
101          end
102          if type(v.depth)~='number' then
103             v.depth =  (jfm_dir=='tate') and  0.0
104          end
105          if type(v.italic)~='number' then
106             v.italic = 0.0
107          end
108          if type(v.left)~='number' then
109             v.left = 0.0
110          end
111          if type(v.down)~='number' then
112             v.down = 0.0
113          end
114          v.kern = v.kern or {}; v.glue = v.glue or {}
115          for j,x in pairs(v.glue) do
116             if v.kern[j] then defjfm_res= nil; return end
117             x.ratio, x[5] = (x.ratio or (x[5] and 0.5*(1+x[5]) or 0.5)), nil
118             x.priority, x[4] = (x.priority or x[4] or 0), nil
119             x.kanjiskip_natural = norm_val(x.kanjiskip_natural)
120             x.kanjiskip_stretch = norm_val(x.kanjiskip_stretch)
121             x.kanjiskip_shrink = norm_val(x.kanjiskip_shrink)
122          end
123          for j,x in pairs(v.kern) do
124             if type(x)=='number' then
125                v.kern[j] = {x, 0.5}
126             elseif type(x)=='table' then
127                v.kern[j] = { x[1], ratio=x.ratio or (x[2] and 0.5*(1+x[2]) or 0.5) }
128             end
129          end
130          t.char_type[i] = v
131          t[i] = nil
132       end
133    end
134    t = luatexbase.call_callback("luatexja.load_jfm", t, jfm_file_name)
135    t.size_cache = {}
136    defjfm_res = t
137 end
138
139 local update_jfm_cache
140 do
141    local function mult_table(old,scale) -- modified from table.fastcopy
142       if old then
143          local new = { }
144          for k,v in next, old do
145             if type(v) == "table" then
146                new[k] = mult_table(v,scale)
147             elseif type(v) == "number" then
148                new[k] = round(v*scale)
149             else
150                new[k] = v
151             end
152          end
153          return new
154       else return nil end
155    end
156    update_jfm_cache = function (j,sz)
157       if metrics[j].size_cache[sz] then return end
158       --local TEMP = node_new(id_kern)
159       local t = {}
160       metrics[j].size_cache[sz] = t
161       t.chars = metrics[j].chars
162       t.char_type = mult_table(metrics[j].char_type, sz)
163       for i,v in pairs(t.char_type) do
164          v.align = (v.align=='left') and 0 or
165             ((v.align=='right') and 1 or 0.5)
166          if type(i) == 'number' then -- char_type
167             for k,w in pairs(v.glue) do
168                local h = node_new(id_glue_spec)
169                v[k] = {
170                   true, h, 
171                   ratio=w.ratio/sz, 
172                   priority=FROM_JFM + w.priority/sz,
173                   kanjiskip_natural = w.kanjiskip_natural and w.kanjiskip_natural/sz,
174                   kanjiskip_stretch = w.kanjiskip_stretch and w.kanjiskip_stretch/sz,
175                   kanjiskip_shrink =  w.kanjiskip_shrink  and w.kanjiskip_shrink/sz,
176                }
177                setfield(h, 'width', w[1])
178                setfield(h, 'stretch', w[2])
179                setfield(h, 'shrink', w[3])
180                setfield(h, 'stretch_order', 0)
181                setfield(h, 'shrink_order', 0)
182             end
183             for k,w in pairs(v.kern) do
184                local g = node_new(id_kern)
185                setfield(g, 'kern', w[1])
186                setfield(g, 'subtype', 1)
187                set_attr(g, attr_icflag, FROM_JFM)
188                v[k] = {false, g, ratio=w[2]/sz}
189             end
190          end
191          v.glue, v.kern = nil, nil
192       end
193       t.kanjiskip = mult_table(metrics[j].kanjiskip, sz)
194       t.xkanjiskip = mult_table(metrics[j].xkanjiskip,sz)
195       t.zw = round(metrics[j].zw*sz)
196       t.zh = round(metrics[j].zh*sz)
197       t.size = sz
198       --node_free(TEMP)
199    end
200 end
201
202 luatexbase.create_callback("luatexja.find_char_class", "data",
203                            function (arg, fmtable, char)
204                               return 0
205                            end)
206 do
207    local start_time_measure = ltjb.start_time_measure
208    local stop_time_measure = ltjb.stop_time_measure
209    local fcc_temp = { chars_cbcache = {} }
210    setmetatable(
211       fcc_temp.chars_cbcache,
212       {
213          __index = function () return 0 end,
214       })
215    function find_char_class(c,m)
216       -- c: character code, m:
217       local r = (m or fcc_temp).chars_cbcache[c]
218       if not r then
219          r = m.chars[c] or
220             luatexbase.call_callback("luatexja.find_char_class", 0, m, c)
221          m.chars_cbcache[c or 0] = r
222       end
223       return r
224    end
225 end
226
227
228 ------------------------------------------------------------------------
229 -- LOADING JAPANESE FONTS
230 ------------------------------------------------------------------------
231
232 do
233    local cstemp
234    local global_flag -- true if \globaljfont, false if \jfont
235    local function load_jfont_metric()
236       if jfm_file_name=='' then
237          ltjb.package_error('luatexja',
238                             'no JFM specified',
239                             'To load and define a Japanese font, a JFM must be specified.'..
240                             "The JFM 'ujis' will be  used for now.")
241          jfm_file_name='ujis'
242       end
243       for j,v in ipairs(metrics) do
244          if v.name==jfm_file_name then return j end
245       end
246       luatexja.load_lua('jfm-' .. jfm_file_name .. '.lua')
247       if defjfm_res then
248          defjfm_res.name = jfm_file_name
249          table.insert(metrics, defjfm_res)
250          return #metrics
251       else
252          return nil
253       end
254    end
255
256 -- EXT
257    local utf8 = unicode.utf8
258    function jfontdefX(g, dir, csname)
259       jfm_dir, is_def_jfont = dir, true
260       cstemp = csname:sub( (utf8.byte(csname,1,1) == tex.escapechar) and 2 or 1, -1)
261       cstemp = cstemp:sub(1, ((cstemp:sub(-1,-1)==' ') and (cstemp:len()>=2)) and -2 or -1)
262       global_flag = g and '\\global' or ''
263       tex.sprint(cat_lp, '\\expandafter\\font\\csname ', 
264                  (cstemp==' ') and '\\space' or cstemp, '\\endcsname')
265    end
266
267    luatexbase.create_callback("luatexja.define_jfont", "data", function (ft, fn) return ft end)
268
269 -- EXT
270    local identifiers = fonts.hashes.identifiers
271    function jfontdefY()
272       local j = load_jfont_metric(jfm_dir)
273       local fn = font.id(cstemp)
274       local f = font_getfont(fn)
275       if not j then
276          ltjb.package_error('luatexja',
277                             "bad JFM `" .. jfm_file_name .. "'",
278                             'The JFM file you specified is not valid JFM file.\n'..
279                                'So defining Japanese font is cancelled.')
280          tex.sprint(cat_lp, global_flag, '\\expandafter\\let\\csname ', 
281                     (cstemp==' ') and '\\space' or cstemp,
282                        '\\endcsname=\\relax')
283          return
284       end
285       update_jfm_cache(j, f.size)
286       local ad = identifiers[fn].parameters
287       local sz = metrics[j].size_cache[f.size]
288       local fmtable = { jfm = j, size = f.size, var = jfm_var,
289                         with_kanjiskip = jfm_ksp, 
290                         zw = sz.zw, zh = sz.zh,
291                         ascent = ad.ascender,
292                         descent = ad.descender,
293                         chars = sz.chars, char_type = sz.char_type,
294                         kanjiskip = sz.kanjiskip, xkanjiskip = sz.xkanjiskip,
295                         chars_cbcache = {},
296                         vert_activated = is_vert_enabled,
297       }
298
299       fmtable = luatexbase.call_callback("luatexja.define_jfont", fmtable, fn)
300       font_metric_table[fn]=fmtable
301       tex.sprint(cat_lp, global_flag, '\\protected\\expandafter\\def\\csname ',
302                     (cstemp==' ') and '\\space' or cstemp, '\\endcsname{\\ltj@cur'..
303                     (jfm_dir == 'yoko' and 'j' or 't') .. 'fnt', fn, '\\relax}')
304    end
305 end
306
307 do
308    local get_dir_count = ltjd.get_dir_count
309    local dir_tate = luatexja.dir_table.dir_tate
310    local tex_get_attr = tex.getattribute
311    -- PUBLIC function
312    function get_zw()
313       local a = font_metric_table[
314          tex_get_attr((get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)]
315       return a and a.zw or 0
316    end
317    function get_zh()
318       local a = font_metric_table[
319          tex_get_attr((get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)]
320       return a and a.zw or 0
321    end
322 end
323
324 do
325    -- extract jfm_file_name and jfm_var
326    -- normalize position of 'jfm=' and 'jfmvar=' keys
327    local function extract_metric(name)
328       local is_braced = name:match('^{(.*)}$')
329        name= is_braced or name
330       jfm_file_name = ''; jfm_var = ''; jfm_ksp = true
331       local tmp, index = name:sub(1, 5), 1
332       if tmp == 'file:' or tmp == 'name:' or tmp == 'psft:' then
333          index = 6
334       end
335       local p = name:find(":", index); index = p and (p+1) or index
336       while index do
337          local l = name:len()+1
338          local q = name:find(";", index+1) or l
339          if name:sub(index, index+3)=='jfm=' and q>index+4 then
340             jfm_file_name = name:sub(index+4, q-1)
341             if l~=q then
342                name = name:sub(1,index-1) .. name:sub(q+1)
343             else
344                name = name:sub(1,index-1)
345                index = nil
346             end
347          elseif name:sub(index, index+6)=='jfmvar=' and q>index+6 then
348             jfm_var = name:sub(index+7, q-1)
349             if l~=q then
350                name = name:sub(1,index-1) .. name:sub(q+1)
351             else
352                name = name:sub(1,index-1)
353                index = nil
354             end
355          else
356             index = (l~=q) and (q+1) or nil
357          end
358       end
359       if jfm_file_name~='' then
360          local l = name:sub(-1)
361          name = name
362             .. ((l==':' or l==';') and '' or ';')
363             .. 'jfm=' .. jfm_file_name
364          if jfm_var~='' then
365             name = name .. 'jfmvar=' .. jfm_var
366          end
367       end
368       for x in string.gmatch (name, "[:;]([+%%-]?)ltjks") do
369          jfm_ksp = not (x=='-')
370       end
371       if jfm_dir == 'tate' then
372          is_vert_enabled = (not name:match('[:;]%-vert')) and (not  name:match('[:;]%-vrt2'))
373          if not name:match('vert') and not name:match('vrt2') then
374             name = name .. ';vert;vrt2'
375          end
376       else
377          is_vert_enabled = nil
378       end
379       return is_braced and ('{' .. name .. '}') or name
380    end
381
382    -- define_font callback
383    local otfl_fdr = fonts.definers.read
384    local ltjr_font_callback = ltjr.font_callback
385    function luatexja.font_callback(name, size, id)
386       local new_name = is_def_jfont and extract_metric(name) or name
387       is_def_jfont = false
388       local res =  ltjr_font_callback(new_name, size, id, otfl_fdr)
389       luatexbase.call_callback('luatexja.define_font', res, new_name, size, id)
390       -- this callback processes variation selector, so we execute it always
391       return res
392    end
393    luatexbase.create_callback('luatexja.define_font', 'simple', function (n) return n end)
394    luatexbase.add_to_callback('define_font',luatexja.font_callback,"luatexja.font_callback", 1)
395 end
396
397 ------------------------------------------------------------------------
398 -- LATEX INTERFACE
399 ------------------------------------------------------------------------
400 do
401    -- these function are called from ltj-latex.sty
402    local fenc_list, kyenc_list, ktenc_list = {}, {}, {}
403    function add_fenc_list(enc) fenc_list[enc] = 'true ' end
404    function add_kyenc_list(enc) kyenc_list[enc] = 'true ' end
405    function add_ktenc_list(enc) ktenc_list[enc] = 'true ' end
406    function is_kyenc(enc)
407       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (kyenc_list[enc] or 'false '))
408    end
409    function is_ktenc(enc)
410       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (ktenc_list[enc] or 'false '))
411    end
412    function is_kenc(enc)
413       tex.sprint(cat_lp, '\\let\\ifin@\\if'
414                  .. (kyenc_list[enc] or ktenc_list[enc] or 'false '))
415    end
416
417    local kfam_list, Nkfam_list = {}, {}
418    function add_kfam(fam)
419       kfam_list[fam]=true
420    end
421    function search_kfam(fam, use_fd)
422       if kfam_list[fam] then 
423          tex.sprint(cat_lp, '\\let\\ifin@\\iftrue '); return
424       elseif Nkfam_list[fam] then 
425          tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
426       elseif use_fd then
427          for i,_ in pairs(kyenc_list) do
428             if kpse.find_file(string.lower(i)..fam..'.fd') then
429                tex.sprint(cat_lp, '\\let\\ifin@\\iftrue '); return
430             end
431          end
432          for i,_ in pairs(ktenc_list) do
433             if kpse.find_file(string.lower(i)..fam..'.fd') then
434                tex.sprint(cat_lp, '\\let\\ifin@\\iftrue '); return
435             end
436          end
437          Nkfam_list[fam]=true; tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
438       else
439          tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
440       end
441    end
442    local ffam_list, Nffam_list = {}, {}
443    function is_ffam(fam)
444       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (ffam_list[fam] or 'false '))
445    end
446    function add_ffam(fam)
447       ffam_list[fam]='true '
448    end
449    function search_ffam_declared()
450      local s = ''
451      for i,_ in pairs(fenc_list) do
452         s = s .. '\\cdp@elt{' .. i .. '}'
453      end
454      tex.sprint(cat_lp, s)
455    end
456    function search_ffam_fd(fam)
457       if Nffam_list[fam] then 
458          tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
459       else
460          for i,_ in pairs(fenc_list) do
461             if kpse.find_file(string.lower(i)..fam..'.fd') then
462                tex.sprint(cat_lp, '\\let\\ifin@\\iftrue '); return
463             end
464          end
465          Nffam_list[fam]=true; tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
466       end
467    end
468
469 end
470 ------------------------------------------------------------------------
471 -- ALTERNATE FONTS
472 ------------------------------------------------------------------------
473 alt_font_table = {}
474 local alt_font_table = alt_font_table
475 local attr_curaltfnt = {}
476 local ucs_out = 0x110000
477
478 ------ for TeX interface
479 -- EXT
480 function set_alt_font(b,e,ind,bfnt)
481    -- ind: 新フォント, bfnt: 基底フォント
482    if b>e then b, e = e, b end
483    if b*e<=0 then
484       ltjb.package_error('luatexja',
485                         'bad character range ([' .. b .. ',' .. e .. ']). ' ..
486                            'I take the intersection with [0x80, 0x10ffff].')
487       b, e = math.max(0x80,b),math.min(ucs_out-1,e)
488    elseif e<0 then -- b<e<0
489       -- do nothing
490    elseif b<0x80 or e>=ucs_out then
491       ltjb.package_warning('luatexja',
492                            'bad character range ([' .. b .. ',' .. e .. ']). ' ..
493                               'I take the intersection with [0x80, 0x10ffff].')
494       b, e = math.max(0x80,b), math.min(ucs_out-1,e)
495    end
496    if not alt_font_table[bfnt] then alt_font_table[bfnt]={} end
497    local t = alt_font_table[bfnt]
498    local ac = font_getfont(ind).characters
499    if bfnt==ind then ind = nil end -- ind == bfnt の場合はテーブルから削除
500    if e>=0 then -- character range
501       for i=b, e do
502          if ac[i]then  t[i]=ind end
503       end
504    else
505       b, e = -e, -b
506       local tx = font_metric_table[bfnt].chars
507       for i,v in pairs(tx) do
508          if b<=v and v<=e and ac[i] then t[i]=ind end
509       end
510    end
511 end
512
513 -- EXT
514 function clear_alt_font(bfnt)
515    if alt_font_table[bfnt] then
516       local t = alt_font_table[bfnt]
517       for i,_ in pairs(t) do t[i]=nil; end
518    end
519 end
520
521 ------ used in ltjp.suppress_hyphenate_ja callback
522 function replace_altfont(pf, pc)
523    local a = alt_font_table[pf]
524    return a and a[pc] or pf
525 end
526
527 ------ for LaTeX interface
528
529 local alt_font_table_latex = {}
530
531 -- EXT
532 function clear_alt_font_latex(bbase)
533    local t = alt_font_table_latex[bbase]
534    if t then
535       for j,v in pairs(t) do t[j] = nil end
536    end
537 end
538
539 -- EXT
540 function set_alt_font_latex(b,e,ind,bbase)
541    -- ind: Alt font の enc/fam/ser/shape, bbase: 基底フォントの enc/fam/ser/shape
542    if b>e then b, e = e, b end
543    if b*e<=0 then
544       ltjb.package_error('luatexja',
545                         'bad character range ([' .. b .. ',' .. e .. ']). ' ..
546                            'I take the intersection with [0x80, 0x10ffff].')
547       b, e = math.max(0x80,b),math.min(ucs_out-1,e)
548    elseif e<0 then -- b<e<0
549       -- do nothing
550    elseif b<0x80 or e>=ucs_out then
551       ltjb.package_warning('luatexja',
552                            'bad character range ([' .. b .. ',' .. e .. ']). ' ..
553                               'I take the intersection with [0x80, 0x10ffff].')
554       b, e = math.max(0x80,b), math.min(ucs_out-1,e)
555    end
556
557    if not alt_font_table_latex[bbase] then alt_font_table_latex[bbase]={} end
558    local t = alt_font_table_latex[bbase]
559    if not t[ind] then t[ind] = {} end
560    for i=b, e do
561       for j,v in pairs(t) do
562          if v[i] then -- remove old entry
563             if j~=ind then v[i]=nil end; break
564          end
565       end
566       t[ind][i]=true
567    end
568    -- remove the empty tables
569    for j,v in pairs(t) do
570       local flag_clear = true
571       for k,_ in pairs(v) do flag_clear = false; break end
572       if flag_clear then t[j]=nil end
573    end
574    if ind==bbase  then t[bbase] = nil end
575 end
576
577 -- ここから先は 新 \selectfont の内部でしか実行されない
578 do
579    local alt_font_base, alt_font_base_num
580    local aftl_base
581    -- EXT
582    function does_alt_set(bbase)
583       aftl_base = alt_font_table_latex[bbase]
584       tex.sprint(cat_lp, '\\if' .. (aftl_base and 'true' or 'false'))
585    end
586    -- EXT
587    function print_aftl_address()
588       tex.sprint(cat_lp, ';ltjaltfont' .. tostring(aftl_base):sub(8))
589    end
590
591 -- EXT
592    function output_alt_font_cmd(dir, bbase)
593       alt_font_base = bbase
594       if dir == 't' then
595          alt_font_base_num = tex.getattribute(attr_curtfnt)
596       else
597          alt_font_base_num = tex.getattribute(attr_curjfnt)
598       end
599       local t = alt_font_table[alt_font_base_num]
600       if t then
601          for i,_ in pairs(t) do t[i]=nil end
602       end
603       t = alt_font_table_latex[bbase]
604       if t then
605        for i,_ in pairs(t) do
606             tex.sprint(cat_lp, '\\ltj@pickup@altfont@aux' .. dir .. '{' .. i .. '}')
607          end
608       end
609    end
610
611 -- EXT
612    function pickup_alt_font_a(size_str)
613       local t = alt_font_table_latex[alt_font_base]
614       if t then
615          for i,v in pairs(t) do
616             tex.sprint(cat_lp, '\\expandafter\\ltj@pickup@altfont@copy'
617                           .. '\\csname ' .. i .. '/' .. size_str .. '\\endcsname{' .. i .. '}')
618          end
619       end
620    end
621
622    local function pickup_alt_font_class(class, afnt_num, afnt_chars)
623       local t  = alt_font_table[alt_font_base_num]
624       local tx = font_metric_table[alt_font_base_num].chars
625       for i,v in pairs(tx) do
626          if v==class and afnt_chars[i] then t[i]=afnt_num end
627       end
628    end
629
630 -- EXT
631    function pickup_alt_font_b(afnt_num, afnt_base)
632       local t = alt_font_table[alt_font_base_num]
633       local ac = font_getfont(afnt_num).characters
634       if not t then t = {}; alt_font_table[alt_font_base_num] = t end
635       for i,v in pairs(alt_font_table_latex[alt_font_base]) do
636          if i == afnt_base then
637             for j,_ in pairs(v) do
638                if j>=0 then
639                   if ac[j] then t[j]=afnt_num end
640                else  -- -n (n>=1) means that the character class n,
641                      -- which is defined in the JFM
642                   pickup_alt_font_class(-j, afnt_num, ac)
643                end
644             end
645             return
646          end
647       end
648    end
649
650 end
651 ------------------------------------------------------------------------
652 -- 終了時に各種ノードを破棄
653 ------------------------------------------------------------------------
654 do
655    function cleanup_size_cache()
656       --local gs, ke = 0, 0
657       for _,n in pairs(metrics) do
658          for i,t in pairs(n.size_cache) do
659             for _,v in pairs(t.char_type) do
660                for k,w in pairs(v) do
661                   if type(k)=='number' then
662                      --if w[1] then gs = gs + 1 else ke = ke + 1 end
663                      node_free(w[2])
664                   end
665                end
666             end
667             n.size_cache[i]=nil
668          end
669       end
670       --print('glue spec: ', gs, 'kern: ', ke)
671    end
672 end
673
674 ------------------------------------------------------------------------
675 -- 追加のフォント情報
676 ------------------------------------------------------------------------
677 font_extra_info = {}
678 local font_extra_info = font_extra_info -- key: fontnumber
679 local font_extra_basename = {} -- key: basename
680
681 -- IVS and vertical metrics
682 local prepare_fl_data
683 local supply_vkern_table
684 do
685    local fields = fontloader.fields
686    local function glyph_vmetric(glyph)
687       local flds = fields(glyph)
688       local vw, tsb, vk = nil, nil, nil
689       for _,i in ipairs(flds) do
690          if i=='vwidth' then vw = glyph.vwidth end
691          if i=='tsidebearing' then tsb = glyph.tsidebearing end
692          if i=='vkerns' then vk = glyph.vkerns end
693       end
694       return vw, tsb, vk
695    end
696
697    local sort = table.sort
698    local function add_fl_table(dest, glyphs, unitable, asc_des, units)
699       local tg, glyphmin, glyphmax = glyphs.glyphs, 0, glyphs.glyphmax
700       for _,v in pairs(fields(glyphs)) do
701          if v=='glyphmin' then glyphmin = glyphs.glyphmin; break end
702       end
703       for i = glyphmin, glyphmax-1 do
704          local gv = tg[i]
705          if gv then
706             if gv.altuni then
707                for _,at in pairs(gv.altuni) do
708                   local bu, vsel = at.unicode, at.variant
709                   if vsel then
710                      if vsel>=0xE0100 then vsel = vsel - 0xE0100 end
711                      dest = dest or {}; dest[bu] = dest[bu] or {}
712                      local uniq_flag = true
713                      for i,_ in pairs(dest[bu]) do
714                         if i==vs then uniq_flag = false; break end
715                      end
716                      if uniq_flag then
717                         dest[bu][vsel] = unitable[gv.name]
718                      end
719                   end
720                end
721             end
722             -- vertical metric
723             local vw, tsb, vk = glyph_vmetric(gv)
724             local gi = unitable[gv.name]
725             if gi and vw and vw~=asc_des then
726                -- We do not use tsidebearing, since (1) fontloader does not read VORG table
727                -- and (2) 'tsidebearing' doea not appear in the returned table by fontloader.fields.
728                -- Hence, we assume that vertical origin == ascender
729                -- (see capsule_glyph_tate in ltj-setwidth.lua)
730                dest = dest or {}; dest[gi] = dest[gi] or {}
731                dest[gi].vwidth = vw/units
732             end
733             -- vertical kern
734             if gi and vk then
735                dest = dest or {};
736                local dest_vk = dest.vkerns or {}; dest.vkerns = dest_vk
737                for _,v in pairs(vk) do
738                   if unitable[v.char] then
739                      local vl = v.lookup
740                      if type(vl)=='table' then
741                         for _,vlt in pairs(vl) do
742                            dest_vk[vlt] = dest_vk[vlt] or {}
743                            dest_vk[vlt][gi] = dest_vk[vlt][gi] or {}
744                            dest_vk[vlt][gi][unitable[v.char]] = v.off
745                         end
746                      else
747                         dest_vk[vl] = dest_vk[vl] or {}
748                         dest_vk[vl][gi] = dest_vk[vl][gi] or {}
749                         dest_vk[vl][gi][unitable[v.char]] = v.off
750                      end
751                   end
752                end
753             end
754          end
755       end
756       return dest
757    end
758    prepare_fl_data = function (dest, id)
759       local fl = fontloader.open(id.filename)
760       local unicodes = id.resources.unicodes
761       if fl.glyphs then
762          dest = add_fl_table(dest, fl, unicodes,
763                              fl.ascent + fl.descent, fl.units_per_em)
764       end
765       if fl.subfonts then
766          for _,v in pairs(fl.subfonts) do
767             dest = add_fl_table(dest, v, unicodes, 
768                                 fl.ascent + fl.descent, fl.units_per_em)
769          end
770       end
771       fontloader.close(fl); collectgarbage("collect")
772       return dest
773    end
774    -- supply vkern table
775    supply_vkern_table = function(id, bname)
776       local bx = font_extra_basename[bname].vkerns
777       local lookuphash =  id.resources.lookuphash
778       local desc = id.shared.rawdata.descriptions
779       if bx and lookuphash then
780          for i,v in pairs(bx) do
781             lookuphash[i] = lookuphash[i] or v
782             for j,w in pairs(v) do
783                desc[j].kerns = desc[j].kerns or {}
784                desc[j].kerns[i] = w
785             end
786          end
787       end
788    end
789 end
790
791 --
792 do
793    local cache_ver = 6
794    local checksum = file.checksum
795
796    local function prepare_extra_data_base(id)
797       if not id then return end
798       local bname = file.nameonly(id.filename or '')
799       if not font_extra_basename[bname] then
800          -- if the cache is present, read it
801          local newsum = checksum(id.filename) -- MD5 checksum of the fontfile
802          local v = "extra_" .. string.lower(file.nameonly(id.filename))
803          local dat = ltjb.load_cache(
804             v,
805             function (t) return (t.version~=cache_ver) or (t.chksum~=newsum) end
806          )
807          -- if the cache is not found or outdated, save the cache
808          if dat then
809             font_extra_basename[bname] = dat[1] or {}
810          else
811             local dat = nil
812             dat = prepare_fl_data(dat, id)
813             font_extra_basename[bname] = dat or {}
814             ltjb.save_cache( v,
815                              {
816                                 chksum = checksum(id.filename),
817                                 version = cache_ver,
818                                 dat,
819                              })
820          end
821          return bname
822       end
823    end
824    local function prepare_extra_data_font(id, res)
825       if type(res)=='table' and res.shared then
826          font_extra_info[id] = font_extra_basename[file.nameonly(res.filename)]
827       end
828    end
829     luatexbase.add_to_callback(
830        'luaotfload.patch_font',
831        function (tfmdata)
832           -- these function is executed one time per one fontfile
833           local bname = prepare_extra_data_base(tfmdata)
834           if bname then supply_vkern_table(tfmdata, bname) end
835           return tfmdata
836        end,
837        'ltj.prepare_extra_data', 1)
838    luatexbase.add_to_callback(
839       'luatexja.define_font',
840       function (res, name, size, id)
841          prepare_extra_data_font(id, res)
842       end,
843       'ltj.prepare_extra_data', 1)
844
845    local nulltable = {} -- dummy
846    ltjr.vert_addfunc = function (n) font_extra_info[n] = nulltable end
847
848    local identifiers = fonts.hashes.identifiers
849    for i=1,font.nextid()-1 do
850       if identifiers[i] then
851          prepare_extra_data_base(identifiers[i])
852          prepare_extra_data_font(i,identifiers[i])
853       end
854    end
855 end
856
857
858 ------------------------------------------------------------------------
859 -- calculate vadvance
860 ------------------------------------------------------------------------
861 do
862    local function acc_feature(table_vadv, table_vorg, subtables, ft,  already_vert)
863       for char_num,v in pairs(ft.shared.rawdata.descriptions) do
864          if v.slookups then
865             for sn, sv in pairs(v.slookups) do
866                if subtables[sn] and type(sv)=='table' then
867                   if sv[4]~=0 then
868                      table_vadv[char_num]
869                         = (table_vadv[char_num] or 0) + sv[4]
870                   end
871                   if sv[2]~=0 and not already_vert then
872                      table_vorg[char_num]
873                         = (table_vorg[char_num] or 0) + sv[2]
874                   end
875                end
876             end
877          end
878       end
879    end
880
881 luatexbase.add_to_callback(
882    "luatexja.define_jfont",
883    function (fmtable, fnum)
884       local vadv = {}; fmtable.v_advance = vadv
885       local vorg = {}; fmtable.v_origin = vorg
886       local ft = font_getfont(fnum)
887       local subtables = {}
888       if ft.specification then
889          for feat_name,v in pairs(ft.specification.features.normal) do
890             if v==true then
891                for _,i in pairs(ft.resources.sequences) do
892                   if i.order[1]== feat_name and i.type == 'gpos_single' then
893                      for _,st in pairs(i.subtables) do
894                         subtables[st] = true
895                      end
896                   end
897                end
898             end
899          end
900          acc_feature(vadv, vorg, subtables, ft,
901                      ft.specification.features.normal.vrt2 or ft.specification.features.normal.vert)
902          for i,v in pairs(vadv) do
903             vadv[i]=vadv[i]/ft.units_per_em*fmtable.size
904          end
905          for i,v in pairs(vorg) do
906             vorg[i]=vorg[i]/ft.units_per_em*fmtable.size
907          end
908       end
909       return fmtable
910    end, 1, 'ltj.v_advance'
911 )
912 end
913
914 ------------------------------------------------------------------------
915 -- supply tounicode entries
916 ------------------------------------------------------------------------
917 do
918   local ltjr_prepare_cid_font = ltjr.prepare_cid_font
919   luatexbase.add_to_callback(
920      'luaotfload.patch_font',
921      function (tfmdata)
922         if tfmdata.cidinfo then
923            local rd = ltjr_prepare_cid_font(tfmdata.cidinfo.registry, tfmdata.cidinfo.ordering)
924            if rd then
925               local ru, rc = rd.resources.unicodes, rd.characters
926               for i,v in pairs(tfmdata.characters) do
927                  local w = ru["Japan1." .. tostring(v.index)]
928                  if w then
929                     v.tounicode = v.tounicode or rc[w]. tounicode
930                  end
931               end
932            end
933         end
934
935         return tfmdata
936      end,
937      'ltj.supply_tounicode', 1)  
938 end
939
940
941 ------------------------------------------------------------------------
942 -- MISC
943 ------------------------------------------------------------------------
944 do
945    local getfont = (Dnode ~= node) and Dnode.getfont or function(n) return n.font end
946    local getchar = (Dnode ~= node) and Dnode.getchar or function(n) return n.char end
947    local get_dir_count = ltjd.get_dir_count
948    local is_ucs_in_japanese_char = ltjc.is_ucs_in_japanese_char_direct
949    local ensure_tex_attr = ltjb.ensure_tex_attr
950    local node_write = Dnode.write
951    local font = font
952    local ITALIC       = luatexja.icflag_table.ITALIC
953    -- EXT: italic correction
954    function append_italic()
955       local p = to_direct(tex.nest[tex.nest.ptr].tail)
956       local TEMP = node_new(id_kern)
957       if p and getid(p)==id_glyph then
958          if is_ucs_in_japanese_char(p) then
959             local j = font_metric_table[
960                has_attr(p, (get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)
961                ]
962             local g = node_new(id_kern)
963             setfield(g, 'subtype', 1); set_attr(g, attr_icflag, ITALIC)
964             setfield(g, 'kern', j.char_type[find_char_class(getchar(p), j)].italic)
965             node_write(g); ensure_tex_attr(attr_icflag, 0)
966          else
967             local f = getfont(p)
968             local h = font_getfont(f) or font.fonts[f]
969             if h then
970                local g = node_new(id_kern)
971                setfield(g, 'subtype', 1); set_attr(g, attr_icflag, ITALIC)
972                setfield(g, 'kern', h.characters[getchar(p)].italic)
973                node_write(g); ensure_tex_attr(attr_icflag, 0)
974             end
975          end
976       end
977       node_free(TEMP)
978    end
979 end
980
981 ------------------------------------------------------------------------
982 -- VERT VARIANT TABLE
983 ------------------------------------------------------------------------
984 vert_form_table = {
985    [0x2013]=0xFE32, [0x2014]=0xFE31, [0x2025]=0xFE30,
986    [0xFF08]=0xFE35, [0xFF09]=0xFE36, [0xFF5B]=0xFE37, [0xFF5D]=0xFE38,
987    [0x3014]=0xFE39, [0x3015]=0xFE3A, [0x3010]=0xFE3B, [0x3011]=0xFE3C,
988    [0x300A]=0xFE3D, [0x300B]=0xFE3E, [0x3008]=0xFE3F, [0x3009]=0xFE40,
989    [0x300C]=0xFE41, [0x300D]=0xFE42, [0x300E]=0xFE43, [0x300F]=0xFE44,
990    [0xFF3B]=0xFE47, [0xFF3D]=0xFE48, [0xFF3F]=0xFE33,
991 }
992 setmetatable(vert_form_table, {__index=function(t,k) return k end});
993