OSDN Git Service

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