OSDN Git Service

ltj-jfont.lua etc.: use data of UTR#50
[luatex-ja/luatexja.git] / src / ltj-jfont.lua
1 --
2 -- luatexja/jfont.lua
3 --
4 luatexbase.provides_module({
5   name = 'luatexja.jfont',
6   date = '2017/08/09',
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 local setfield = node.direct.setfield
17 local getid = node.direct.getid
18 local to_direct = node.direct.todirect
19
20 local node_new = node.direct.new
21 local node_free = node.direct.free
22 local has_attr = node.direct.has_attribute
23 local set_attr = node.direct.set_attribute
24 local round = tex.round
25 local font_getfont = font.getfont
26
27 local attr_icflag = luatexbase.attributes['ltj@icflag']
28 local attr_curjfnt = luatexbase.attributes['ltj@curjfnt']
29 local attr_curtfnt = luatexbase.attributes['ltj@curtfnt']
30 local id_glyph = node.id('glyph')
31 local id_kern = node.id('kern')
32 local cat_lp = luatexbase.catcodetables['latex-package']
33 local FROM_JFM     = luatexja.icflag_table.FROM_JFM
34 ------------------------------------------------------------------------
35 -- LOADING JFM
36 ------------------------------------------------------------------------
37
38 metrics={} -- this table stores all metric informations
39 font_metric_table={} -- [font number] -> jfm_name, jfm_var, size
40
41 luatexbase.create_callback("luatexja.load_jfm", "data", function (ft, jn) return ft end)
42
43 local jfm_file_name, jfm_var, jfm_ksp
44 local defjfm_res
45 local jfm_dir, is_def_jfont, is_vert_enabled, auto_enable_vrt2
46
47 local function norm_val(a)
48    if (not a) or (a==0.) then
49       return nil
50    elseif a==true then
51       return 1
52    else
53       return a
54    end
55 end
56
57 function define_jfm(t)
58    local real_char -- Does current character class have the 'real' character?
59    if t.dir~=jfm_dir then
60       defjfm_res= nil; return
61    elseif type(t.zw)~='number' or type(t.zh)~='number' then
62       defjfm_res= nil; return
63    end
64    t.version = (type(t.version)=='number') and t.version or 1
65    t.char_type = {}; t.chars = {}
66    for i,v in pairs(t) do
67       if type(i) == 'number' then -- char_type
68          if not v.chars then
69             if i ~= 0 then defjfm_res= nil; return  end
70          else
71             for j,w in pairs(v.chars) do
72                if type(w) == 'number' and w~=-1 then
73                elseif type(w) == 'string' and utf.len(w)==1 then
74                   w = utf.byte(w)
75                elseif type(w) == 'string' and utf.len(w)==2 and utf.sub(w,2) == '*' then
76                   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             v.chars = nil
85          end
86          if type(v.align)~='string' then
87             v.align = 'left' -- left
88          end
89          if type(v.width)~='number' then
90             v.width = nil
91          end
92          if type(v.height)~='number' then
93             v.height = (jfm_dir=='tate') and  0.0
94          end
95          if type(v.depth)~='number' then
96             v.depth =  (jfm_dir=='tate') and  0.0
97          end
98          if type(v.italic)~='number' then
99             v.italic = 0.0
100          end
101          if type(v.left)~='number' then
102             v.left = 0.0
103          end
104          if type(v.down)~='number' then
105             v.down = 0.0
106          end
107          if t.version>=2 then
108             if v.end_stretch then defjfm_res= nil; return end
109             if v.end_shrink  then defjfm_res= nil; return end
110             if v.end_adjust then
111                if type(v.end_adjust)~='table' then
112                   v.end_adjust = nil
113                elseif #(v.end_adjust)==0 then
114                   v.end_adjust = nil
115                else 
116                   table.sort(v.end_adjust)
117                end
118             end
119          else
120             v.end_adjust = nil
121             if v.end_stretch and v.end_stretch~=0.0 then 
122                v.end_adjust = (v.end_adjust or {}) 
123                v.end_adjust[#(v.end_adjust)+1] = v.end_stretch
124             end
125             if v.end_shrink and v.end_ahrink~=0.0 then 
126                v.end_adjust = (v.end_adjust or {}) 
127                v.end_adjust[#(v.end_adjust)+1] = -v.end_shrink
128             end
129             if v.end_adjust then v.end_adjust[#(v.end_adjust)+1] = 0.0 end
130          end
131          v.kern = v.kern or {}; v.glue = v.glue or {}
132          for j,x in pairs(v.glue) do
133             if v.kern[j] then defjfm_res= nil; return end
134             x.ratio, x[5] = (x.ratio or (x[5] and 0.5*(1+x[5]) or 0.5)), nil
135             do
136                local xp
137                xp, x[4] = (x.priority or x[4]), nil
138                if type(xp)=='table' and t.version>=2 then
139                   if type(xp[1])~='number' or xp[1]<-4 or xp[1]>3 then defjfm_res=nil end  -- stretch
140                   if type(xp[2])~='number' or xp[2]<-4 or xp[2]>3 then defjfm_res=nil end  -- shrink
141                   xp = (xp[1]+4)*8+(xp[2]+4)
142                elseif xp and type(xp)~='number' then
143                   defjfm_res = nil
144                else
145                   xp = (xp or 0)*9+36   
146                   if xp<0 or xp>=64 then defjfm_res=nil end 
147                end
148                x.priority = xp
149             end
150             x.kanjiskip_natural = norm_val(x.kanjiskip_natural)
151             x.kanjiskip_stretch = norm_val(x.kanjiskip_stretch)
152             x.kanjiskip_shrink = norm_val(x.kanjiskip_shrink)
153          end
154          for j,x in pairs(v.kern) do
155             if type(x)=='number' then
156                v.kern[j] = {x, 0.5}
157             elseif type(x)=='table' then
158                v.kern[j] = { x[1], (x.ratio or (x[2] and 0.5*(1+x[2]) or 0.5)) }
159             end
160          end
161          t.char_type[i] = v
162          t[i] = nil
163       end
164    end
165    if t.version<3 then
166       -- In version 3, 'jcharbdd' is divided into 
167       -- 'alchar': ALchar (or math boundary) 
168       -- 'nox_alchar': ALchar (or math boundary), where xkanjiskip won't inserted
169       -- 'glue': glue/kern, 'jcharbdd': other cases (和文B, rule, ...)
170       t.chars.alchar = t.chars.jcharbdd
171       t.chars.nox_alchar = t.chars.jcharbdd
172       t.chars.glue = t.chars.jcharbdd
173    end
174    t = luatexbase.call_callback("luatexja.load_jfm", t, jfm_file_name)
175    t.size_cache = {}
176    defjfm_res = t
177 end
178
179 local update_jfm_cache
180 do
181    local function mult_table(old,scale) -- modified from table.fastcopy
182       if old then
183          local new = { }
184          for k,v in next, old do
185             if type(v) == "table" then
186                new[k] = mult_table(v,scale)
187             elseif type(v) == "number" then
188                new[k] = round(v*scale)
189             else
190                new[k] = v
191             end
192          end
193          return new
194       else return nil end
195    end
196    update_jfm_cache = function (j,sz)
197       if metrics[j].size_cache[sz] then return end
198       local t = {}
199       metrics[j].size_cache[sz] = t
200       t.chars = metrics[j].chars
201       t.char_type = mult_table(metrics[j].char_type, sz)
202       for i,v in pairs(t.char_type) do
203          v.align = (v.align=='left') and 0 or
204             ((v.align=='right') and 1 or 0.5)
205          if type(i) == 'number' then -- char_type
206             for k,w in pairs(v.glue) do
207                v[k] = {
208                   nil,
209                   ratio=w.ratio/sz,
210                   priority=FROM_JFM + w.priority/sz,
211                   width = w[1], stretch = w[2], shrink = w[3],
212                   kanjiskip_natural = w.kanjiskip_natural and w.kanjiskip_natural/sz,
213                   kanjiskip_stretch = w.kanjiskip_stretch and w.kanjiskip_stretch/sz,
214                   kanjiskip_shrink =  w.kanjiskip_shrink  and w.kanjiskip_shrink/sz,
215                }
216             end
217             for k,w in pairs(v.kern) do
218                local g = node_new(id_kern, 1)
219                setfield(g, 'kern', w[1])
220                set_attr(g, attr_icflag, FROM_JFM)
221                v[k] = {g, ratio=w[2]/sz}
222             end
223          end
224          v.glue, v.kern = nil, nil
225       end
226       t.kanjiskip = mult_table(metrics[j].kanjiskip, sz)
227       t.xkanjiskip = mult_table(metrics[j].xkanjiskip,sz)
228       t.zw = round(metrics[j].zw*sz)
229       t.zh = round(metrics[j].zh*sz)
230       t.size = sz
231    end
232 end
233
234 luatexbase.create_callback("luatexja.find_char_class", "data",
235                            function (arg, fmtable, char)
236                               return 0
237                            end)
238 do
239    local start_time_measure = ltjb.start_time_measure
240    local stop_time_measure = ltjb.stop_time_measure
241    local fcc_temp = { chars_cbcache = {} }
242    setmetatable(
243       fcc_temp.chars_cbcache,
244       {
245          __index = function () return 0 end,
246       })
247    function find_char_class(c,m)
248       -- c: character code, m:
249       local r = (m or fcc_temp).chars_cbcache[c]
250       if not r then
251          r = m.chars[c] or
252             luatexbase.call_callback("luatexja.find_char_class", 0, m, c)
253          m.chars_cbcache[c or 0] = r
254       end
255       return r
256    end
257 end
258
259
260 ------------------------------------------------------------------------
261 -- LOADING JAPANESE FONTS
262 ------------------------------------------------------------------------
263
264 do
265    local cstemp
266    local global_flag -- true if \globaljfont, false if \jfont
267    local function load_jfont_metric()
268       if jfm_file_name=='' then
269          ltjb.package_error('luatexja',
270                             'no JFM specified',
271                             'To load and define a Japanese font, a JFM must be specified.'..
272                             "The JFM 'ujis' will be  used for now.")
273          jfm_file_name='ujis'
274       end
275       for j,v in ipairs(metrics) do
276          if v.name==jfm_file_name then return j end
277       end
278       luatexja.load_lua('jfm-' .. jfm_file_name .. '.lua')
279       if defjfm_res then
280          defjfm_res.name = jfm_file_name
281          table.insert(metrics, defjfm_res)
282          return #metrics
283       else
284          return nil
285       end
286    end
287
288 -- EXT
289    local utf8 = unicode.utf8
290    function jfontdefX(g, dir, csname)
291       jfm_dir, is_def_jfont = dir, true
292       cstemp = csname:sub( (utf8.byte(csname,1,1) == tex.escapechar) and 2 or 1, -1)
293       cstemp = cstemp:sub(1, ((cstemp:sub(-1,-1)==' ') and (cstemp:len()>=2)) and -2 or -1)
294       global_flag = g and '\\global' or ''
295       tex.sprint(cat_lp, '\\expandafter\\font\\csname ',
296                  (cstemp==' ') and '\\space' or cstemp, '\\endcsname')
297    end
298
299    luatexbase.create_callback("luatexja.define_jfont", "data", function (ft, fn) return ft end)
300
301 -- EXT
302    local identifiers = fonts.hashes.identifiers
303    local provides_feature = luaotfload.aux.provides_feature
304    function jfontdefY()
305       local j = load_jfont_metric(jfm_dir)
306       local fn = font.id(cstemp)
307       local f = font_getfont(fn)
308       if not j then
309          ltjb.package_error('luatexja',
310                             "bad JFM `" .. jfm_file_name .. "'",
311                             'The JFM file you specified is not valid JFM file.\n'..
312                                'So defining Japanese font is cancelled.')
313          tex.sprint(cat_lp, global_flag, '\\expandafter\\let\\csname ',
314                     (cstemp==' ') and '\\space' or cstemp,
315                        '\\endcsname=\\relax')
316          return
317       end
318       if not f then return end
319       update_jfm_cache(j, f.size)
320       local ad = identifiers[fn].parameters
321       local sz = metrics[j].size_cache[f.size]
322       local fmtable = { jfm = j, size = f.size, var = jfm_var,
323                         with_kanjiskip = jfm_ksp,
324                         zw = sz.zw, zh = sz.zh,
325                         ascent = ad.ascender,
326                         descent = ad.descender,
327                         chars = sz.chars, char_type = sz.char_type,
328                         kanjiskip = sz.kanjiskip, xkanjiskip = sz.xkanjiskip,
329                         chars_cbcache = {},
330                         vert_activated = is_vert_enabled,
331       }
332       if auto_enable_vrt2 then
333          local t = identifiers[fn]
334          local lang, scr = t.properties.language, t.properties.script
335          local vrt2_exist = provides_feature(
336            fn, t.properties.script, t.properties.language, 'vrt2'
337          )
338          t.shared.features[vrt2_exist and 'vrt2' or 'vert'] = true
339       end
340
341       fmtable = luatexbase.call_callback("luatexja.define_jfont", fmtable, fn)
342       font_metric_table[fn]=fmtable
343       tex.sprint(cat_lp, global_flag, '\\protected\\expandafter\\def\\csname ',
344                     (cstemp==' ') and '\\space' or cstemp, '\\endcsname{\\ltj@cur'..
345                     (jfm_dir == 'yoko' and 'j' or 't') .. 'fnt', fn, '\\relax}')
346    end
347 end
348
349 do
350    local get_dir_count = ltjd.get_dir_count
351    local dir_tate = luatexja.dir_table.dir_tate
352    local tex_get_attr = tex.getattribute
353    -- PUBLIC function
354    function get_zw()
355       local a = font_metric_table[
356          tex_get_attr((get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)]
357       return a and a.zw or 0
358    end
359    function get_zh()
360       local a = font_metric_table[
361          tex_get_attr((get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)]
362       return a and a.zw or 0
363    end
364 end
365
366 do
367    -- extract jfm_file_name and jfm_var
368    -- normalize position of 'jfm=' and 'jfmvar=' keys
369    local function extract_metric(name)
370       local is_braced = name:match('^{(.*)}$')
371       name= is_braced or name
372       jfm_file_name = ''; jfm_var = ''; jfm_ksp = true
373       local tmp, index = name:sub(1, 5), 1
374       if tmp == 'file:' or tmp == 'name:' or tmp == 'psft:' then
375          index = 6
376       end
377       local p = name:find(":", index); index = p and (p+1) or index
378       while index do
379          local l = name:len()+1
380          local q = name:find(";", index+1) or l
381          if name:sub(index, index+3)=='jfm=' and q>index+4 then
382             jfm_file_name = name:sub(index+4, q-1)
383             if l~=q then
384                name = name:sub(1,index-1) .. name:sub(q+1)
385             else
386                name = name:sub(1,index-1)
387                index = nil
388             end
389          elseif name:sub(index, index+6)=='jfmvar=' and q>index+6 then
390             jfm_var = name:sub(index+7, q-1)
391             if l~=q then
392                name = name:sub(1,index-1) .. name:sub(q+1)
393             else
394                name = name:sub(1,index-1)
395                index = nil
396             end
397          else
398             index = (l~=q) and (q+1) or nil
399          end
400       end
401       if jfm_file_name~='' then
402          local l = name:sub(-1)
403          name = name
404             .. ((l==':' or l==';') and '' or ';')
405             .. 'jfm=' .. jfm_file_name
406          if jfm_var~='' then
407             name = name .. 'jfmvar=' .. jfm_var
408          end
409       end
410       for x in string.gmatch (name, "[:;]([+%%-]?)ltjks") do
411          jfm_ksp = not (x=='-')
412       end
413       if jfm_dir == 'tate' then
414          is_vert_enabled = (not name:match('[:;]%-vert')) and (not  name:match('[:;]%-vrt2'))
415          auto_enable_vrt2 = (not name:match('vert') and not name:match('vrt2'))
416       else
417          is_vert_enabled, auto_enable_vrt2 = nil, nil
418       end
419       return is_braced and ('{' .. name .. '}') or name
420    end
421
422    -- define_font callback
423    local otfl_fdr
424    local ltjr_font_callback = ltjr.font_callback
425    function luatexja.font_callback(name, size, id)
426       local new_name = is_def_jfont and extract_metric(name) or name
427       is_def_jfont = false
428       local res =  ltjr_font_callback(new_name, size, id, otfl_fdr)
429       luatexbase.call_callback('luatexja.define_font', res, new_name, size, id)
430       -- this callback processes variation selector, so we execute it always
431       return res
432    end
433    luatexbase.create_callback('luatexja.define_font', 'simple', function (n) return n end)
434    otfl_fdr= luatexbase.remove_from_callback('define_font', 'luaotfload.define_font')
435    luatexbase.add_to_callback('define_font',luatexja.font_callback,"luatexja.font_callback", 1)
436 end
437
438 ------------------------------------------------------------------------
439 -- LATEX INTERFACE
440 ------------------------------------------------------------------------
441 do
442    -- these function are called from ltj-latex.sty
443    local fenc_list, kyenc_list, ktenc_list = {}, {}, {}
444    function add_fenc_list(enc) fenc_list[enc] = 'true ' end
445    function add_kyenc_list(enc) kyenc_list[enc] = 'true ' end
446    function add_ktenc_list(enc) ktenc_list[enc] = 'true ' end
447    function is_kyenc(enc)
448       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (kyenc_list[enc] or 'false '))
449    end
450    function is_ktenc(enc)
451       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (ktenc_list[enc] or 'false '))
452    end
453    function is_kenc(enc)
454       tex.sprint(cat_lp, '\\let\\ifin@\\if'
455                  .. (kyenc_list[enc] or ktenc_list[enc] or 'false '))
456    end
457
458    local kfam_list, Nkfam_list = {}, {}
459    function add_kfam(fam)
460       kfam_list[fam]=true
461    end
462    function search_kfam(fam, use_fd)
463       if kfam_list[fam] then
464          tex.sprint(cat_lp, '\\let\\ifin@\\iftrue '); return
465       elseif Nkfam_list[fam] then
466          tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
467       elseif use_fd then
468          for i,_ in pairs(kyenc_list) do
469             if kpse.find_file(string.lower(i)..fam..'.fd') then
470                tex.sprint(cat_lp, '\\let\\ifin@\\iftrue '); return
471             end
472          end
473          for i,_ in pairs(ktenc_list) do
474             if kpse.find_file(string.lower(i)..fam..'.fd') then
475                tex.sprint(cat_lp, '\\let\\ifin@\\iftrue '); return
476             end
477          end
478          Nkfam_list[fam]=true; tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
479       else
480          tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
481       end
482    end
483    local ffam_list, Nffam_list = {}, {}
484    function is_ffam(fam)
485       tex.sprint(cat_lp, '\\let\\ifin@\\if' .. (ffam_list[fam] or 'false '))
486    end
487    function add_ffam(fam)
488       ffam_list[fam]='true '
489    end
490    function search_ffam_declared()
491      local s = ''
492      for i,_ in pairs(fenc_list) do
493         s = s .. '\\cdp@elt{' .. i .. '}'
494      end
495      tex.sprint(cat_lp, s)
496    end
497    function search_ffam_fd(fam)
498       if Nffam_list[fam] then
499          tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
500       else
501          for i,_ in pairs(fenc_list) do
502             if kpse.find_file(string.lower(i)..fam..'.fd') then
503                tex.sprint(cat_lp, '\\let\\ifin@\\iftrue '); return
504             end
505          end
506          Nffam_list[fam]=true; tex.sprint(cat_lp, '\\let\\ifin@\\iffalse '); return
507       end
508    end
509
510 end
511 ------------------------------------------------------------------------
512 -- ALTERNATE FONTS
513 ------------------------------------------------------------------------
514 alt_font_table = {}
515 local alt_font_table = alt_font_table
516 local attr_curaltfnt = {}
517 local ucs_out = 0x110000
518
519 ------ for TeX interface
520 -- EXT
521 function set_alt_font(b,e,ind,bfnt)
522    -- ind: 新フォント, bfnt: 基底フォント
523    if b>e then b, e = e, b end
524    if b*e<=0 then
525       ltjb.package_error('luatexja',
526                         'bad character range ([' .. b .. ',' .. e .. ']). ' ..
527                            'I take the intersection with [0x80, 0x10ffff].')
528       b, e = math.max(0x80,b),math.min(ucs_out-1,e)
529    elseif e<0 then -- b<e<0
530       -- do nothing
531    elseif b<0x80 or e>=ucs_out then
532       ltjb.package_warning('luatexja',
533                            'bad character range ([' .. b .. ',' .. e .. ']). ' ..
534                               'I take the intersection with [0x80, 0x10ffff].')
535       b, e = math.max(0x80,b), math.min(ucs_out-1,e)
536    end
537    if not alt_font_table[bfnt] then alt_font_table[bfnt]={} end
538    local t = alt_font_table[bfnt]
539    local ac = font_getfont(ind).characters
540    if bfnt==ind then ind = nil end -- ind == bfnt の場合はテーブルから削除
541    if e>=0 then -- character range
542       for i=b, e do
543          if ac[i]then  t[i]=ind end
544       end
545    else
546       b, e = -e, -b
547       local tx = font_metric_table[bfnt].chars
548       for i,v in pairs(tx) do
549          if b<=v and v<=e and ac[i] then t[i]=ind end
550       end
551    end
552 end
553
554 -- EXT
555 function clear_alt_font(bfnt)
556    if alt_font_table[bfnt] then
557       local t = alt_font_table[bfnt]
558       for i,_ in pairs(t) do t[i]=nil; end
559    end
560 end
561
562 ------ used in ltjp.suppress_hyphenate_ja callback
563 function replace_altfont(pf, pc)
564    local a = alt_font_table[pf]
565    return a and a[pc] or pf
566 end
567
568 ------ for LaTeX interface
569
570 local alt_font_table_latex = {}
571
572 -- EXT
573 function clear_alt_font_latex(bbase)
574    local t = alt_font_table_latex[bbase]
575    if t then
576       for j,v in pairs(t) do t[j] = nil end
577    end
578 end
579
580 -- EXT
581 function set_alt_font_latex(b,e,ind,bbase)
582    -- ind: Alt font の enc/fam/ser/shape, bbase: 基底フォントの enc/fam/ser/shape
583    if b>e then b, e = e, b end
584    if b*e<=0 then
585       ltjb.package_error('luatexja',
586                         'bad character range ([' .. b .. ',' .. e .. ']). ' ..
587                            'I take the intersection with [0x80, 0x10ffff].')
588       b, e = math.max(0x80,b),math.min(ucs_out-1,e)
589    elseif e<0 then -- b<e<0
590       -- do nothing
591    elseif b<0x80 or e>=ucs_out then
592       ltjb.package_warning('luatexja',
593                            'bad character range ([' .. b .. ',' .. e .. ']). ' ..
594                               'I take the intersection with [0x80, 0x10ffff].')
595       b, e = math.max(0x80,b), math.min(ucs_out-1,e)
596    end
597
598    if not alt_font_table_latex[bbase] then alt_font_table_latex[bbase]={} end
599    local t = alt_font_table_latex[bbase]
600    if not t[ind] then t[ind] = {} end
601    for i=b, e do
602       for j,v in pairs(t) do
603          if v[i] then -- remove old entry
604             if j~=ind then v[i]=nil end; break
605          end
606       end
607       t[ind][i]=true
608    end
609    -- remove the empty tables
610    for j,v in pairs(t) do
611       local flag_clear = true
612       for k,_ in pairs(v) do flag_clear = false; break end
613       if flag_clear then t[j]=nil end
614    end
615    if ind==bbase  then t[bbase] = nil end
616 end
617
618 -- ここから先は 新 \selectfont の内部でしか実行されない
619 do
620    local alt_font_base, alt_font_base_num
621    local aftl_base
622    -- EXT
623    function does_alt_set(bbase)
624       aftl_base = alt_font_table_latex[bbase]
625       tex.sprint(cat_lp, '\\if' .. (aftl_base and 'true' or 'false'))
626    end
627    -- EXT
628    function print_aftl_address()
629       tex.sprint(cat_lp, ';ltjaltfont' .. tostring(aftl_base):sub(8))
630    end
631
632 -- EXT
633    function output_alt_font_cmd(dir, bbase)
634       alt_font_base = bbase
635       if dir == 't' then
636          alt_font_base_num = tex.getattribute(attr_curtfnt)
637       else
638          alt_font_base_num = tex.getattribute(attr_curjfnt)
639       end
640       local t = alt_font_table[alt_font_base_num]
641       if t then
642          for i,_ in pairs(t) do t[i]=nil end
643       end
644       t = alt_font_table_latex[bbase]
645       if t then
646        for i,_ in pairs(t) do
647             tex.sprint(cat_lp, '\\ltj@pickup@altfont@aux' .. dir .. '{' .. i .. '}')
648          end
649       end
650    end
651
652 -- EXT
653    function pickup_alt_font_a(size_str)
654       local t = alt_font_table_latex[alt_font_base]
655       if t then
656          for i,v in pairs(t) do
657             tex.sprint(cat_lp, '\\expandafter\\ltj@pickup@altfont@copy'
658                           .. '\\csname ' .. i .. '/' .. size_str .. '\\endcsname{' .. i .. '}')
659          end
660       end
661    end
662
663    local function pickup_alt_font_class(class, afnt_num, afnt_chars)
664       local t  = alt_font_table[alt_font_base_num]
665       local tx = font_metric_table[alt_font_base_num].chars
666       for i,v in pairs(tx) do
667          if v==class and afnt_chars[i] then t[i]=afnt_num end
668       end
669    end
670
671 -- EXT
672    function pickup_alt_font_b(afnt_num, afnt_base)
673       local t = alt_font_table[alt_font_base_num]
674       local ac = font_getfont(afnt_num).characters
675       if not t then t = {}; alt_font_table[alt_font_base_num] = t end
676       for i,v in pairs(alt_font_table_latex[alt_font_base]) do
677          if i == afnt_base then
678             for j,_ in pairs(v) do
679                if j>=0 then
680                   if ac[j] then t[j]=afnt_num end
681                else  -- -n (n>=1) means that the character class n,
682                      -- which is defined in the JFM
683                   pickup_alt_font_class(-j, afnt_num, ac)
684                end
685             end
686             return
687          end
688       end
689    end
690
691 end
692 ------------------------------------------------------------------------
693 -- 終了時に各種ノードを破棄
694 ------------------------------------------------------------------------
695 do
696    function cleanup_size_cache()
697       --local gs, ke = 0, 0
698       for _,n in pairs(metrics) do
699          for i,t in pairs(n.size_cache) do
700             for _,v in pairs(t.char_type) do
701                for k,w in pairs(v) do
702                   if type(k)=='number' then
703                      --if w[1] then gs = gs + 1 else ke = ke + 1 end
704                      if w[1] then node_free(w[1]) end
705                   end
706                end
707             end
708             n.size_cache[i]=nil
709          end
710       end
711    end
712 end
713
714 ------------------------------------------------------------------------
715 -- 追加のフォント情報
716 ------------------------------------------------------------------------
717 font_extra_info = {}
718 local font_extra_info = font_extra_info -- key: fontnumber
719 local font_extra_basename = {} -- key: basename
720
721 local list_rotate_glyphs
722 do
723   -- output of function_utr50.lua
724   local function rotate_in_utr50(i)
725   -- UTR#50 revision 17; 2016-10-20
726     if (0x0000<=i)and(i<0x00A7) then return true end
727     if (0x00A8<=i)and(i<0x00A9) then return true end
728     if (0x00AA<=i)and(i<0x00AE) then return true end
729     if (0x00AF<=i)and(i<0x00B1) then return true end
730     if (0x00B2<=i)and(i<0x00BC) then return true end
731     if (0x00BF<=i)and(i<0x00D7) then return true end
732     if (0x00D8<=i)and(i<0x00F7) then return true end
733     if (0x00F8<=i)and(i<0x02EA) then return true end
734     if (0x02EC<=i)and(i<0x0860) then return true end
735     if (0x08A0<=i)and(i<0x1100) then return true end
736     if (0x1200<=i)and(i<0x1401) then return true end
737     if (0x1680<=i)and(i<0x18B0) then return true end
738     if (0x1900<=i)and(i<0x1C90) then return true end
739     if (0x1CC0<=i)and(i<0x2016) then return true end
740     if (0x2017<=i)and(i<0x2020) then return true end
741     if (0x2022<=i)and(i<0x2030) then return true end
742     if (0x2032<=i)and(i<0x203B) then return true end
743     if (0x203D<=i)and(i<0x2042) then return true end
744     if (0x2043<=i)and(i<0x2047) then return true end
745     if (0x204A<=i)and(i<0x2051) then return true end
746     if (0x2052<=i)and(i<0x2065) then return true end
747     if (0x2066<=i)and(i<0x20DD) then return true end
748     if (0x20E1<=i)and(i<0x20E2) then return true end
749     if (0x20E5<=i)and(i<0x2100) then return true end
750     if (0x2102<=i)and(i<0x2103) then return true end
751     if (0x210A<=i)and(i<0x210F) then return true end
752     if (0x2110<=i)and(i<0x2113) then return true end
753     if (0x2115<=i)and(i<0x2116) then return true end
754     if (0x2118<=i)and(i<0x211E) then return true end
755     if (0x2124<=i)and(i<0x2125) then return true end
756     if (0x2126<=i)and(i<0x2127) then return true end
757     if (0x2128<=i)and(i<0x2129) then return true end
758     if (0x212A<=i)and(i<0x212E) then return true end
759     if (0x212F<=i)and(i<0x2135) then return true end
760     if (0x2140<=i)and(i<0x2145) then return true end
761     if (0x214B<=i)and(i<0x214C) then return true end
762     if (0x214E<=i)and(i<0x214F) then return true end
763     if (0x218A<=i)and(i<0x218C) then return true end
764     if (0x2190<=i)and(i<0x221E) then return true end
765     if (0x221F<=i)and(i<0x2234) then return true end
766     if (0x2236<=i)and(i<0x2300) then return true end
767     if (0x2308<=i)and(i<0x230C) then return true end
768     if (0x2320<=i)and(i<0x2324) then return true end
769     if (0x2329<=i)and(i<0x232B) then return true end
770     if (0x232C<=i)and(i<0x237D) then return true end
771     if (0x239B<=i)and(i<0x23BE) then return true end
772     if (0x23CE<=i)and(i<0x23CF) then return true end
773     if (0x23D0<=i)and(i<0x23D1) then return true end
774     if (0x23DC<=i)and(i<0x23E2) then return true end
775     if (0x2423<=i)and(i<0x2424) then return true end
776     if (0x2500<=i)and(i<0x25A0) then return true end
777     if (0x261A<=i)and(i<0x2620) then return true end
778     if (0x2768<=i)and(i<0x2776) then return true end
779     if (0x2794<=i)and(i<0x2B12) then return true end
780     if (0x2B30<=i)and(i<0x2B50) then return true end
781     if (0x2B5A<=i)and(i<0x2BB8) then return true end
782     if (0x2BEC<=i)and(i<0x2BF0) then return true end
783     if (0x2C00<=i)and(i<0x2E80) then return true end
784     if (0x3008<=i)and(i<0x3012) then return true end
785     if (0x3014<=i)and(i<0x3020) then return true end
786     if (0x3030<=i)and(i<0x3031) then return true end
787     if (0x30A0<=i)and(i<0x30A1) then return true end
788     if (0x30FC<=i)and(i<0x30FD) then return true end
789     if (0xA4D0<=i)and(i<0xA960) then return true end
790     if (0xA980<=i)and(i<0xAC00) then return true end
791     if (0xD800<=i)and(i<0xE000) then return true end
792     if (0xFB00<=i)and(i<0xFE10) then return true end
793     if (0xFE20<=i)and(i<0xFE30) then return true end
794     if (0xFE49<=i)and(i<0xFE50) then return true end
795     if (0xFE58<=i)and(i<0xFE5F) then return true end
796     if (0xFE63<=i)and(i<0xFE67) then return true end
797     if (0xFE70<=i)and(i<0xFF01) then return true end
798     if (0xFF08<=i)and(i<0xFF0A) then return true end
799     if (0xFF0D<=i)and(i<0xFF0E) then return true end
800     if (0xFF1A<=i)and(i<0xFF1F) then return true end
801     if (0xFF3B<=i)and(i<0xFF3C) then return true end
802     if (0xFF3D<=i)and(i<0xFF3E) then return true end
803     if (0xFF3F<=i)and(i<0xFF40) then return true end
804     if (0xFF5B<=i)and(i<0xFFE0) then return true end
805     if (0xFFE3<=i)and(i<0xFFE4) then return true end
806     if (0xFFE8<=i)and(i<0xFFF0) then return true end
807     if (0xFFF9<=i)and(i<0xFFFC) then return true end
808     if (0xFFFE<=i)and(i<0x10200) then return true end
809     if (0x10280<=i)and(i<0x103E0) then return true end
810     if (0x10400<=i)and(i<0x10570) then return true end
811     if (0x10600<=i)and(i<0x10780) then return true end
812     if (0x10800<=i)and(i<0x108B0) then return true end
813     if (0x108E0<=i)and(i<0x10940) then return true end
814     if (0x109A0<=i)and(i<0x10AA0) then return true end
815     if (0x10AC0<=i)and(i<0x10BB0) then return true end
816     if (0x10C00<=i)and(i<0x10C50) then return true end
817     if (0x10C80<=i)and(i<0x10D00) then return true end
818     if (0x10E60<=i)and(i<0x10E80) then return true end
819     if (0x11000<=i)and(i<0x11250) then return true end
820     if (0x11280<=i)and(i<0x11380) then return true end
821     if (0x11400<=i)and(i<0x114E0) then return true end
822     if (0x11600<=i)and(i<0x116D0) then return true end
823     if (0x11700<=i)and(i<0x11740) then return true end
824     if (0x118A0<=i)and(i<0x11900) then return true end
825     if (0x11AC0<=i)and(i<0x11B00) then return true end
826     if (0x11C00<=i)and(i<0x11CC0) then return true end
827     if (0x12000<=i)and(i<0x12550) then return true end
828     if (0x16800<=i)and(i<0x16A70) then return true end
829     if (0x16AD0<=i)and(i<0x16B90) then return true end
830     if (0x16F00<=i)and(i<0x16FA0) then return true end
831     if (0x1BC00<=i)and(i<0x1BCB0) then return true end
832     if (0x1D200<=i)and(i<0x1D250) then return true end
833     if (0x1D400<=i)and(i<0x1D800) then return true end
834     if (0x1E000<=i)and(i<0x1E030) then return true end
835     if (0x1E800<=i)and(i<0x1E8E0) then return true end
836     if (0x1E900<=i)and(i<0x1E960) then return true end
837     if (0x1EE00<=i)and(i<0x1EF00) then return true end
838     if (0x1F800<=i)and(i<0x1F900) then return true end
839     if (0xE0000<=i)and(i<0xE0080) then return true end
840     if (0xE0100<=i)and(i<0xE01F0) then return true end
841   end
842    list_rotate_glyphs = function (dest, id)
843       if id.specification and id.resources then
844          local rot = {}
845          for i,_ in pairs(id.characters) do
846             if rotate_in_utr50(i) then rot[i] = true end
847          end
848          if id.resources.sequences then
849          for _,i in pairs(id.resources.sequences) do
850             if i.order[1]== 'vert' and i.type == 'gsub_single' and i.steps then
851                for _,j in pairs(i.steps) do
852                   if type(j)=='table' then 
853                      if type(j,coverage)=='table' then
854                         for i,_ in pairs(j.coverage) do rot[i]=nil end
855                      end
856                   end
857                end
858             end
859          end; end
860          -- コードポイントが共有されているグリフについて
861          if id.resources.duplicates then
862          for i,v in pairs(id.resources.duplicates) do
863             local f = rot[i]
864             for j,_ in pairs(v) do f = f and rot[j] end
865             rot[i]=f
866             for j,_ in pairs(v) do rot[j] = f end
867          end; end
868          
869          for i,_ in pairs(rot) do
870             dest = dest or {}
871             dest[i] = dest[i] or {}
872             dest[i].rotation = true
873          end
874       end
875       return dest
876    end
877 end
878
879 -- vertical metrics
880 local prepare_fl_data
881 local supply_vkern_table
882 do
883    local fields = fontloader.fields
884    local function glyph_vmetric(glyph)
885       local flds = fields(glyph)
886       local vw, tsb, vk = nil, nil, nil
887       for _,i in ipairs(flds) do
888          if i=='vwidth' then vw = glyph.vwidth end
889          if i=='tsidebearing' then tsb = glyph.tsidebearing end
890          if i=='vkerns' then vk = glyph.vkerns end
891       end
892       return vw, tsb, vk
893    end
894
895    local sort = table.sort
896    local function add_fl_table(dest, glyphs, unitable, asc_des, units, id)
897       local glyphmin, glyphmax = glyphs.glyphmin, glyphs.glyphmax
898       if glyphmax < 0 then return dest end
899       local tg = glyphs.glyphs
900       for i = glyphmin, glyphmax do
901          local gv = tg[i]
902          if gv then
903             if gv.altuni then
904                for _,at in pairs(gv.altuni) do
905                   local bu, vsel = at.unicode, at.variant
906                   if vsel then
907                      if vsel>=0xE0100 then vsel = vsel - 0xE0100 end
908                      local uniq_flag = true
909                      if dest and dest[bu] then
910                         for i,_ in pairs(dest[bu]) do
911                            if i==vsel then uniq_flag = false; break end
912                         end
913                      end
914                      if uniq_flag then
915                         dest = dest or {}; dest[bu] = dest[bu] or {}
916                         dest[bu][vsel] = unitable[gv.name]
917                      end
918                   end
919                end
920             end
921             -- vertical metric
922             local vw, tsb, vk = glyph_vmetric(gv)
923             local gi = unitable[gv.name]
924             if gi and vw and vw~=asc_des then
925                -- We do not use tsidebearing, since (1) fontloader does not read VORG table
926                -- and (2) 'tsidebearing' doea not appear in the returned table by fontloader.fields.
927                -- Hence, we assume that vertical origin == ascender
928                -- (see capsule_glyph_tate in ltj-setwidth.lua)
929                dest = dest or {}; dest[gi] = dest[gi] or {}
930                dest[gi].vwidth = vw/units
931             end
932             -- vertical kern
933             if gi and vk then
934                dest = dest or {};
935                local dest_vk = dest.vkerns or {}; dest.vkerns = dest_vk
936                for _,v in pairs(vk) do
937                   if unitable[v.char] then
938                      local vl = v.lookup
939                      if type(vl)=='table' then
940                         for _,vlt in pairs(vl) do
941                            dest_vk[vlt] = dest_vk[vlt] or {}
942                            dest_vk[vlt][gi] = dest_vk[vlt][gi] or {}
943                            dest_vk[vlt][gi][unitable[v.char]] = v.off
944                         end
945                      else
946                         dest_vk[vl] = dest_vk[vl] or {}
947                         dest_vk[vl][gi] = dest_vk[vl][gi] or {}
948                         dest_vk[vl][gi][unitable[v.char]] = v.off
949                      end
950                   end
951                end
952             end
953          end
954       end
955       return dest
956    end
957    prepare_fl_data = function (dest, id)
958       local t = fontloader.info(id.filename)
959       local fl
960       if t.filename then
961         fl = fontloader.open(id.filename)
962       else
963         fl = fontloader.open(id.filename, id.fullname)
964       end
965       local ind_to_uni, unicodes = {}, {}
966       for i,v in pairs(id.characters) do
967           ind_to_uni[v.index] = i
968       end
969       if fl.glyphs then
970          local tg, glyphmin, glyphmax = fl.glyphs, fl.glyphmin, fl.glyphmax
971          if 0 <= glyphmax then
972             for i = glyphmin, glyphmax do
973                if tg[i] and tg[i].name then unicodes[tg[i].name] = ind_to_uni[i] end
974             end
975          end
976          dest = add_fl_table(dest, fl, unicodes,
977                              fl.ascent + fl.descent, fl.units_per_em, id)
978       end
979       if fl.subfonts then
980          for _,v in pairs(fl.subfonts) do
981             local tg, glyphmin, glyphmax = v.glyphs, v.glyphmin, v.glyphmax
982             if 0 <= glyphmax then
983                for i = glyphmin, glyphmax do
984                   if tg[i] and tg[i].name then unicodes[tg[i].name] = ind_to_uni[i] end
985                end
986            end
987        end
988          for _,v in pairs(fl.subfonts) do
989             dest = add_fl_table(dest, v, unicodes,
990                                 fl.ascent + fl.descent, fl.units_per_em, id)
991          end
992      end
993      if dest then dest.unicodes = unicodes end
994      fontloader.close(fl); collectgarbage("collect")
995      return dest
996    end
997    -- supply vkern table
998    supply_vkern_table = function(id, bname)
999       local bx = font_extra_basename[bname].vkerns
1000       local lookuphash =  id.resources.lookuphash
1001       local desc = id.shared.rawdata.descriptions
1002       if bx and lookuphash then
1003          for i,v in pairs(bx) do
1004             lookuphash[i] = lookuphash[i] or v
1005             for j,w in pairs(v) do
1006                desc[j].kerns = desc[j].kerns or {}
1007                desc[j].kerns[i] = w
1008             end
1009          end
1010       end
1011    end
1012 end
1013
1014 --
1015 do
1016    local cache_ver = 14
1017    local checksum = file.checksum
1018
1019    local function prepare_extra_data_base(id)
1020       if (not id) or (not id.filename) then return end
1021       local bname = id.psname or file.nameonly(id.filename)
1022       if not font_extra_basename[bname] then
1023          -- if the cache is present, read it
1024          local newsum = checksum(id.filename) -- MD5 checksum of the fontfile
1025          local v = "extra_" .. string.lower(bname)
1026          local dat = ltjb.load_cache(
1027             v,
1028             function (t) return (t.version~=cache_ver) or (t.chksum~=newsum) end
1029          )
1030          -- if the cache is not found or outdated, save the cache
1031          if dat then
1032             font_extra_basename[bname] = dat[1] or {}
1033          else
1034             local dat = nil
1035             dat = prepare_fl_data(dat, id)
1036             dat = list_rotate_glyphs(dat, id)
1037             font_extra_basename[bname] = dat or {}
1038             ltjb.save_cache( v,
1039                              {
1040                                 chksum = checksum(id.filename),
1041                                 version = cache_ver,
1042                                 dat,
1043                              })
1044          end
1045          return bname
1046       end
1047    end
1048    local function prepare_extra_data_font(id, res)
1049       if type(res)=='table' and res.shared and (res.psname or res.filename) then
1050          font_extra_info[id] = font_extra_basename[res.psname or file.nameonly(res.filename)]
1051       end
1052    end
1053     luatexbase.add_to_callback(
1054        'luaotfload.patch_font',
1055        function (tfmdata)
1056           -- these function is executed one time per one fontfile
1057           local bname = prepare_extra_data_base(tfmdata)
1058           if bname then supply_vkern_table(tfmdata, bname) end
1059           return tfmdata
1060        end,
1061        'ltj.prepare_extra_data', 1)
1062    luatexbase.add_to_callback(
1063       'luatexja.define_font',
1064       function (res, name, size, id)
1065          prepare_extra_data_font(id, res)
1066       end,
1067       'ltj.prepare_extra_data', 1)
1068
1069    local nulltable = {} -- dummy
1070    ltjr.vert_addfunc = function (n) font_extra_info[n] = nulltable end
1071
1072    local identifiers = fonts.hashes.identifiers
1073    for i=1,font.nextid()-1 do
1074       if identifiers[i] then
1075          prepare_extra_data_base(identifiers[i])
1076          prepare_extra_data_font(i,identifiers[i])
1077       end
1078    end
1079 end
1080
1081
1082 ------------------------------------------------------------------------
1083 -- calculate vadvance
1084 ------------------------------------------------------------------------
1085 do
1086    local function acc_feature(table_vadv, table_vorg, subtables, ft,  already_vert)
1087       for char_num,v in pairs(ft.shared.rawdata.descriptions) do
1088          if v.slookups then
1089             for sn, sv in pairs(v.slookups) do
1090                if subtables[sn] and type(sv)=='table' then
1091                   if sv[4]~=0 then
1092                      table_vadv[char_num]
1093                         = (table_vadv[char_num] or 0) + sv[4]
1094                   end
1095                   if sv[2]~=0 and not already_vert then
1096                      table_vorg[char_num]
1097                         = (table_vorg[char_num] or 0) + sv[2]
1098                   end
1099                end
1100             end
1101          end
1102       end
1103    end
1104
1105 luatexbase.add_to_callback(
1106    "luatexja.define_jfont",
1107    function (fmtable, fnum)
1108       local vadv = {}; fmtable.v_advance = vadv
1109       local vorg = {}; fmtable.v_origin = vorg
1110       local ft = font_getfont(fnum)
1111       local subtables = {}
1112       if ft.specification then
1113          for feat_name,v in pairs(ft.specification.features.normal) do
1114             if v==true and ft.resources then
1115                for _,i in pairs(ft.resources.sequences) do
1116                   if i.order[1]== feat_name and i.type == 'gpos_single' and type(i.subtables)=='table' then
1117                      for _,st in pairs(i.subtables) do
1118                         subtables[st] = true
1119                      end
1120                   end
1121                end
1122             end
1123          end
1124          acc_feature(vadv, vorg, subtables, ft,
1125                      ft.specification.features.normal.vrt2 or ft.specification.features.normal.vert)
1126          for i,v in pairs(vadv) do
1127             vadv[i]=vadv[i]/ft.units_per_em*fmtable.size
1128          end
1129          for i,v in pairs(vorg) do
1130             vorg[i]=vorg[i]/ft.units_per_em*fmtable.size
1131          end
1132       end
1133       return fmtable
1134    end, 'ltj.v_advance', 1
1135 )
1136 end
1137
1138 ------------------------------------------------------------------------
1139 -- make table of vertical glyphs which does not covered by vert feature
1140 -- nor UTR#50
1141 ------------------------------------------------------------------------
1142 do
1143 ------------------------------------------------------------------------
1144 -- VERT VARIANT TABLE
1145 ------------------------------------------------------------------------
1146   local vert_form_table = {
1147      [0x3001]=0xFE11, [0x3002]=0xFE12, [0x3016]=0xFE17, [0x3017]=0xFE18,
1148      [0x2026]=0xFE19,
1149      [0x2025]=0xFE30, [0x2014]=0xFE31, [0x2013]=0xFE32, [0xFF3F]=0xFE33,
1150      [0xFF08]=0xFE35, [0xFF09]=0xFE36, [0xFF5B]=0xFE37, [0xFF5D]=0xFE38,
1151      [0x3014]=0xFE39, [0x3015]=0xFE3A, [0x3010]=0xFE3B, [0x3011]=0xFE3C,
1152      [0x300A]=0xFE3D, [0x300B]=0xFE3E, [0x3008]=0xFE3F, [0x3009]=0xFE40,
1153      [0x300C]=0xFE41, [0x300D]=0xFE42, [0x300E]=0xFE43, [0x300F]=0xFE44,
1154      [0xFF3B]=0xFE47, [0xFF3D]=0xFE48, 
1155   }
1156   local function add_vform(coverage, vform, ft)
1157      if type(coverage)~='table' then return end
1158      for i,v in pairs(vert_form_table) do
1159          if (not coverage[i]) and ft.characters[v] then
1160              vform[i] = v
1161          end
1162      end
1163   end
1164
1165 luatexbase.add_to_callback(
1166    "luatexja.define_jfont",
1167    function (fmtable, fnum)
1168       local vform = {}; fmtable.vform = vform
1169       local ft = font_getfont(fnum)
1170       if ft.specification and ft.resources then
1171           for _,i in pairs(ft.resources.sequences) do
1172               if i.order[1]== 'vert' and i.type == 'gsub_single' and i.steps then
1173                   for _,j in pairs(i.steps) do
1174                      if type(j)=='table' then add_vform(j.coverage,vform, ft) end
1175                   end
1176               end
1177           end
1178       end
1179       return fmtable
1180    end, 'ltj.get_vert_form', 1
1181 )
1182 end
1183
1184 ------------------------------------------------------------------------
1185 -- supply tounicode entries
1186 ------------------------------------------------------------------------
1187 do
1188   local ltjr_prepare_cid_font = ltjr.prepare_cid_font
1189   luatexbase.add_to_callback(
1190      'luaotfload.patch_font',
1191      function (tfmdata)
1192         local cidinfo = tfmdata.cidinfo or tfmdata.resources.cidinfo
1193         if cidinfo and cidinfo.registry and cidinfo.ordering then
1194            local rd = ltjr_prepare_cid_font(cidinfo.registry, cidinfo.ordering)
1195            if rd then
1196               local ru, rc = rd.resources.unicodes, rd.characters
1197               for i,v in pairs(tfmdata.characters) do
1198                  local w = ru["Japan1." .. tostring(v.index)]
1199                  if w then
1200                     v.tounicode = v.tounicode or rc[w]. tounicode
1201                  end
1202               end
1203            end
1204         end
1205
1206         return tfmdata
1207      end,
1208      'ltj.supply_tounicode', 1)
1209 end
1210
1211
1212 ------------------------------------------------------------------------
1213 -- MISC
1214 ------------------------------------------------------------------------
1215 do
1216    local getfont = node.direct.getfont
1217    local getchar = node.direct.getchar
1218    local get_dir_count = ltjd.get_dir_count
1219    local is_ucs_in_japanese_char = ltjc.is_ucs_in_japanese_char_direct
1220    local ensure_tex_attr = ltjb.ensure_tex_attr
1221    local node_write = node.direct.write
1222    local font = font
1223    local new_ic_kern
1224    if status.luatex_version>=89 then
1225        new_ic_kern = function(g)  return node_new(id_kern,3) end
1226    else
1227        local ITALIC       = luatexja.icflag_table.ITALIC
1228        new_ic_kern = function()
1229          local g = node_new(id_kern, 1)
1230          set_attr(g, attr_icflag, ITALIC)
1231          return g
1232        end
1233    end
1234    -- EXT: italic correction
1235    function append_italic()
1236       local p = to_direct(tex.nest[tex.nest.ptr].tail)
1237       local TEMP = node_new(id_kern)
1238       if p and getid(p)==id_glyph then
1239          if is_ucs_in_japanese_char(p) then
1240             local j = font_metric_table[
1241                has_attr(p, (get_dir_count()==dir_tate) and attr_curtfnt or attr_curjfnt)
1242                ]
1243             local g = new_ic_kern()
1244             setfield(g, 'kern', j.char_type[find_char_class(getchar(p), j)].italic)
1245             node_write(g); ensure_tex_attr(attr_icflag, 0)
1246          else
1247             local f = getfont(p)
1248             local h = font_getfont(f) or font.fonts[f]
1249             if h then
1250                local g = new_ic_kern()
1251                if h.characters[getchar(p)] and h.characters[getchar(p)].italic then
1252                   setfield(g, 'kern', h.characters[getchar(p)].italic)
1253                   node_write(g); ensure_tex_attr(attr_icflag, 0)
1254                end
1255             end
1256          end
1257       end
1258       node_free(TEMP)
1259    end
1260 end
1261