OSDN Git Service

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