OSDN Git Service

b3602ea4cbb03f7ac7b39ff45fcbab8af145f3c6
[luatex-ja/luatexja.git] / src / ltj-jfmglue.lua
1 --
2 -- luatexja/jfmglue.lua
3 --
4 luatexbase.provides_module({
5   name = 'luatexja.jfmglue',
6   date = '2012/04/25',
7   version = '0.4',
8   description = 'Insertion process of JFM glues and kanjiskip',
9 })
10 module('luatexja.jfmglue', package.seeall)
11 local err, warn, info, log = luatexbase.errwarinf(_NAME)
12 local node = node
13
14 luatexja.load_module('base');      local ltjb = luatexja.base
15 luatexja.load_module('stack');     local ltjs = luatexja.stack
16 luatexja.load_module('jfont');     local ltjf = luatexja.jfont
17 luatexja.load_module('pretreat');  local ltjp = luatexja.pretreat
18
19 local has_attr = node.has_attribute
20 local set_attr = node.set_attribute
21 local round = tex.round
22 local uniq_id = 0 -- unique id 
23
24 local id_glyph = node.id('glyph')
25 local id_hlist = node.id('hlist')
26 local id_vlist = node.id('vlist')
27 local id_rule = node.id('rule')
28 local id_ins = node.id('ins')
29 local id_mark = node.id('mark')
30 local id_adjust = node.id('adjust')
31 local id_disc = node.id('disc')
32 local id_whatsit = node.id('whatsit')
33 local id_math = node.id('math')
34 local id_glue = node.id('glue')
35 local id_kern = node.id('kern')
36 local id_penalty = node.id('penalty')
37
38 local id_glue_spec = node.id('glue_spec')
39 local id_jglyph = node.id('glyph') + 256      -- Japanese character
40 local id_box_like = node.id('hlist') + 256    -- vbox, shifted hbox
41 local id_pbox = node.id('hlist') + 512        -- already processed nodes (by \unhbox)
42 local id_pbox_w = node.id('hlist') + 513      -- cluster which consists of a whatsit
43 local sid_user = node.subtype('user_defined')
44
45 local sid_start_link = node.subtype('pdf_start_link')
46 local sid_start_thread = node.subtype('pdf_start_thread')
47 local sid_end_link = node.subtype('pdf_end_link')
48 local sid_end_thread = node.subtype('pdf_end_thread')
49
50 local ITALIC = 1
51 local PACKED = 2
52 local KINSOKU = 3
53 local FROM_JFM = 4
54 local LINE_END = 5
55 local KANJI_SKIP = 6
56 local XKANJI_SKIP = 7
57 local PROCESSED = 8
58 local IC_PROCESSED = 9
59 local BOXBDD = 15
60
61 local kanji_skip
62 local xkanji_skip
63
64 local attr_jchar_class = luatexbase.attributes['ltj@charclass']
65 local attr_orig_char = luatexbase.attributes['ltj@origchar']
66 local attr_curjfnt = luatexbase.attributes['ltj@curjfnt']
67 local attr_icflag = luatexbase.attributes['ltj@icflag']
68 local attr_autospc = luatexbase.attributes['ltj@autospc']
69 local attr_autoxspc = luatexbase.attributes['ltj@autoxspc']
70 local attr_uniqid = luatexbase.attributes['ltj@uniqid']
71 local max_dimen = 1073741823
72
73 local box_stack_level
74 local par_indented -- is the paragraph indented?
75
76 -------------------- Helper functions
77
78 local function copy_attr(new, old) 
79   -- 仕様が決まるまで off にしておく
80 end
81
82 -- This function is called only for acquiring `special' characters.
83 local function fast_find_char_class(c,m)
84    return m.size_cache.chars[c] or 0
85 end
86
87 local spec_zero_glue = node.new(id_glue_spec)
88    spec_zero_glue.width = 0; spec_zero_glue.stretch_order = 0; spec_zero_glue.stretch = 0
89    spec_zero_glue.shrink_order = 0; spec_zero_glue.shrink = 0
90
91 local function get_zero_spec()
92    return node.copy(spec_zero_glue)
93 end
94
95 local function skip_table_to_spec(n)
96    local g = node.new(id_glue_spec)
97    local st = ltjs.get_skip_table(n, box_stack_level)
98    g.width = st.width; g.stretch = st.stretch; g.shrink = st.shrink
99    g.stretch_order = st.stretch_order; g.shrink_order = st.shrink_order
100    return g
101 end
102
103 -- penalty 値の計算
104 local function add_penalty(p,e)
105    if p.penalty>=10000 then
106       if e<=-10000 then p.penalty = 0 end
107    elseif p.penalty<=-10000 then
108       if e>=10000 then p.penalty = 0 end
109    else
110       p.penalty = p.penalty + e
111       if p.penalty>=10000 then p.penalty = 10000
112       elseif p.penalty<=-10000 then p.penalty = -10000 end
113    end
114    return
115 end
116
117 -- 「異なる JFM」の間の調整方法
118 diffmet_rule = math.two_average
119 function math.two_add(a,b) return a+b end
120 function math.two_average(a,b) return (a+b)*0.5 end
121
122 -------------------- idea
123 -- 2 node の間に glue/kern/penalty を挿入する.
124 -- 基本方針: char node q と char node p の間
125
126 --  Np: 「p を核とする塊」
127 --   first: 最初の node,nuc: p,last: 最後の node
128 --   id: 核 node の種類
129 --  Nq: 「q を核とする塊」
130 --   実際の glue は Np.last, Nq.first の間に挿入される
131 --  Bp: Np.last, Nq.first の間の penalty node 達の配列
132
133 -- Np, Nq, Bp, widow_Bp について
134 -- Np, Nq は別々のテーブル.
135 -- 1回のループごとに Nq = Np, Np = (new table) となるのは効率が悪いので,
136 -- Np <-> Nq 入れ替え,その後 Np をクリアすることでテーブルを再利用.
137 -- 同様の関係は Bp, widow_Bp にも.
138
139
140 -- 核の定義:
141 --  node x が non-char node のときは,x のみ
142 --  x が char_node のときは,
143 --  - x が \accent の第二引数だったとき
144 --    [kern2 kern y kern2] x の 3 node が核に加わる
145 --  - x の直後に \/ 由来 kern があったとき
146 --    その \/ 由来の kern が核に加わる
147 -- p, q の走査で無視するもの:
148 --  ins, mark, adjust, whatsit, penalty
149 --
150 -- Nq.last .. + .. Bp.first .... Bp[last] .... * .. Np.first
151 -- +: kern from LINEEND はここに入る
152 -- *: jfm glue はここに入る
153
154 local head -- the head of current list
155 local last -- the last node of current list
156 local lp   -- 外側での list 走査時のカーソル
157
158 local Np, Nq, Bp
159 local widow_Bp, widow_Np -- \jcharwidowpenalty 挿入位置管理用
160
161 local ihb_flag -- JFM グルー挿入抑止用 flag
162                -- on: \inhibitglue 指定時,hlist の周囲
163
164 -------------------- hlist 内の文字の検索
165
166 local first_char, last_char, find_first_char
167
168 local function check_box(box_ptr, box_end)
169    local p = box_ptr; local found_visible_node = false
170    if not p then 
171       find_first_char = false; first_char = nil; last_char = nil
172       return true
173    end
174    while p and p~=box_end do
175       local pid = p.id
176       if pid==id_kern then
177          if p.subtype==2 then
178             p = node.next(node.next(node.next(p))); pid = p.id
179          elseif has_attr(p, attr_icflag)==IC_PROCESSED then
180             p = node.next(p); pid = p.id
181          end
182       end
183       if pid==id_glyph then
184          repeat 
185             if find_first_char then 
186                first_char = p; find_first_char = false
187             end
188             last_char = p; found_visible_node = true; p=node.next(p)
189             if (not p) or p==box_end then return found_visible_node end
190          until p.id~=id_glyph
191          pid = p.id
192       end
193       if pid==id_hlist then
194          if has_attr(p, attr_icflag)==PACKED then
195             for q in node.traverse_id(id_glyph, p.head) do
196                if find_first_char then
197                   first_char = q; find_first_char = false
198                end
199                last_char = q; found_visible_node = true; break
200             end
201          else
202             if p.shift==0 then
203                if check_box(p.head, nil) then found_visible_node = true end
204             else if find_first_char then 
205                   find_first_char = false
206                else 
207                   last_char = nil
208                end
209             end
210          end
211       elseif not (pid==id_ins   or pid==id_mark
212                   or pid==id_adjust or pid==id_whatsit
213                   or pid==id_penalty) then
214          found_visible_node = true
215          if find_first_char then 
216             find_first_char = false
217          else 
218             last_char = nil
219          end
220       end
221       p = node.next(p)
222    end
223    return found_visible_node
224 end 
225
226 function check_box_high(Nx, box_ptr, box_end)
227    first_char = nil;  last_char = nil;  find_first_char = true
228    if check_box(box_ptr, box_end) then
229       if first_char then
230          if first_char.font == has_attr(first_char, attr_curjfnt) then 
231             set_np_xspc_jachar(Nx, first_char)
232          else
233             set_np_xspc_alchar(Nx, first_char.char,first_char, ligature_head)
234          end
235       end
236    end
237    return last_char
238 end
239
240 -------------------- Np の計算と情報取得
241
242 luatexbase.create_callback("luatexja.jfmglue.whatsit_getinfo", "data", 
243                            function (Np, lp, Nq, box_stack_level) 
244                               if Np.nuc then return Np 
245                               else 
246                                  return Np  -- your code
247                               end
248                            end)
249 luatexbase.create_callback("luatexja.jfmglue.whatsit_after", "data", 
250                            function (stat, Nq, Np, box_stack_level) return false end)
251
252 -- calc next Np
253 local function set_attr_icflag_processed(p)
254    if (has_attr(p, attr_icflag) or 0)<= ITALIC then 
255       set_attr(p, attr_uniqid, uniq_id) 
256       set_attr(p, attr_icflag, PROCESSED) 
257    end
258 end
259
260 local function check_next_ickern()
261    if lp.id == id_kern and has_attr(lp, attr_icflag)==ITALIC then
262       set_attr(lp, attr_icflag, IC_PROCESSED) 
263       set_attr(lp, attr_uniqid, uniq_id) 
264       Np.last = lp; lp = node.next(lp)
265    else Np.last = Np.nuc end
266 end
267
268 local function calc_np_pbox()
269    local uid = has_attr(lp, attr_uniqid)
270    Np.first = Np.first or lp; Np.id = id_pbox
271    lpa = KINSOKU -- dummy=
272    while lp~=last and lpa>=PACKED and lpa~=BOXBDD
273       and has_attr(lp, attr_uniqid) == uid do
274       Np.nuc = lp; set_attr(lp, attr_uniqid, uniq_id) 
275       lp = node.next(lp); lpa = has_attr(lp, attr_icflag) or 0
276    end
277    return check_next_ickern()
278 end
279
280
281 local calc_np_auxtable = {
282    [id_glyph] = function() 
283                    Np.first = Np.first or lp
284                    if lp.font == has_attr(lp, attr_curjfnt) then 
285                       Np.id = id_jglyph 
286                    else 
287                       Np.id = id_glyph 
288                    end
289                    Np.nuc = lp; 
290                    set_attr(lp, attr_uniqid, uniq_id) 
291                    --set_attr_icflag_processed(lp) treated in ltj-setwidth.lua
292                    lp = node.next(lp); check_next_ickern(); return true
293                 end,
294    [id_hlist] = function() 
295                    Np.first = Np.first or lp; Np.last = lp; Np.nuc = lp; 
296                    set_attr_icflag_processed(lp)
297                    if lp.shift~=0 then 
298                       Np.id = id_box_like
299                    else 
300                       Np.id = id_hlist 
301                    end
302                    lp = node.next(lp); return true
303                 end,
304    [id_vlist] = function()
305                    Np.first = Np.first or lp; Np.nuc = lp; Np.last = lp;
306                    Np.id = id_box_like; set_attr_icflag_processed(lp); 
307                    lp = node.next(lp); return true
308                 end,
309    [id_rule] = function()
310                   Np.first = Np.first or lp; Np.nuc = lp; Np.last = lp;
311                   Np.id = id_box_like; set_attr_icflag_processed(lp); 
312                   lp = node.next(lp); return true
313                end,
314    [id_ins] = function() 
315                  set_attr_icflag_processed(lp); lp = node.next(lp)
316                  return false
317               end,
318    [id_mark] = function() 
319                   set_attr_icflag_processed(lp); lp = node.next(lp)
320                   return false
321                end,
322    [id_adjust] = function() 
323                     set_attr_icflag_processed(lp); lp = node.next(lp)
324                     return false
325                  end,
326    [id_disc] = function()
327                   Np.first = Np.first or lp; 
328                   Np.nuc = lp; set_attr_icflag_processed(lp); 
329                   Np.last = lp; Np.id = id_disc; lp = node.next(lp); return true
330                end,
331    [id_whatsit] = function() 
332                   if lp.subtype==sid_user then
333                      if lp.user_id==30111 then
334                         local lq = node.next(lp)
335                         head = node.remove(head, lp); node.free(lp); lp = lq; ihb_flag = true
336                      else
337                         set_attr_icflag_processed(lp)
338                         luatexbase.call_callback("luatexja.jfmglue.whatsit_getinfo"
339                                                  , Np, lp, Nq, box_stack_level)
340                         lp = node.next(lp)
341                         if Np.nuc then 
342                            Np.id = id_pbox_w; Np.first = Np.nuc; Np.last = Np.nuc; return true
343                         end
344                      end
345                   else
346                      -- we do special treatment for these whatsit nodes.
347                      if lp.subtype == sid_start_link or lp.subtype == sid_start_thread then
348                         Np.first = lp 
349                      elseif lp.subtype == sid_end_link or lp.subtype == sid_end_thread then
350                         Nq.last = lp; Np.first = nil
351                      end
352                      set_attr_icflag_processed(lp); lp = node.next(lp)
353                   end
354                   return false
355                   end,
356    [id_math] = function()
357                   Np.first = Np.first or lp; Np.nuc = lp; 
358                   set_attr_icflag_processed(lp); lp  = node.next(lp) 
359                   while lp.id~=id_math do 
360                      set_attr_icflag_processed(lp); lp  = node.next(lp) 
361                   end
362                   set_attr_icflag_processed(lp); 
363                   Np.last = lp; Np.id = id_math; lp = node.next(lp); 
364                   return true
365                end,
366    [id_glue] = function()
367                   Np.first = Np.first or lp; Np.nuc = lp; set_attr_icflag_processed(lp); 
368                   Np.last = lp; Np.id = id_glue; lp = node.next(lp); return true
369                end,
370    [id_kern] = function() 
371                   Np.first = Np.first or lp
372                   if lp.subtype==2 then
373                      set_attr_icflag_processed(lp); lp = node.next(lp)
374                      set_attr_icflag_processed(lp); lp = node.next(lp)
375                      set_attr_icflag_processed(lp); lp = node.next(lp)
376                      set_attr_icflag_processed(lp); Np.nuc = lp
377                      if lp.font == has_attr(lp, attr_curjfnt) then 
378                         Np.id = id_jglyph 
379                      else
380                         Np.id = id_glyph 
381                      end
382                      lp = node.next(lp); check_next_ickern(); 
383                   else
384                      Np.id = id_kern; set_attr_icflag_processed(lp);
385                      Np.last = lp; lp = node.next(lp)
386                   end
387                   return true
388                end,
389    [id_penalty] = function()
390                      Bp[#Bp+1] = lp; set_attr_icflag_processed(lp); 
391                      lp = node.next(lp); return false
392                   end,
393    [13] = function()
394                   Np.first = Np.first or lp; Np.nuc = lp; Np.last = lp;
395                   Np.id = id_box_like; set_attr_icflag_processed(lp); 
396                   lp = node.next(lp); return true
397                end,
398 }
399
400 local function calc_np()
401    -- We assume lp = node.next(Np.last)
402    local Nr = Nq
403    for k in pairs(Nr) do Nr[k] = nil end; Nq = Np; Np = Nr
404    for k in pairs(Bp) do Bp[k] = nil end
405    ihb_flag = false 
406    while lp ~= last do
407       local lpa = has_attr(lp, attr_icflag) or 0
408       if lpa>=PACKED then
409          if lpa == BOXBDD then
410             local lq = node.next(lp)
411             head = node.remove(head, lp); node.free(lp); lp = lq
412          else calc_np_pbox(); return 
413          end -- id_pbox
414       elseif calc_np_auxtable[lp.id]() then return end
415    end
416    Np = nil; return
417 end
418
419
420
421
422 -- extract informations from Np
423 -- We think that "Np is a Japanese character" if Np.met~=nil,
424 --            "Np is an alphabetic character" if Np.pre~=nil,
425 --            "Np is not a character" otherwise.
426
427 -- 和文文字のデータを取得
428 function set_np_xspc_jachar(Nx, x)
429    local m = ltjf.font_metric_table[x.font]
430    Nx.var  = m.var
431    local c = has_attr(x, attr_orig_char) or 0
432    local cls = ltjf.find_char_class(x.char, m) or 0
433    if cls==0 and c ~= x.char then cls = ltjf.find_char_class(-c, m) end
434    set_attr(x, attr_jchar_class, cls)
435    Nx.class = cls
436    Nx.char = c
437    Nx.met = m
438    Nx.pre = ltjs.get_penalty_table('pre', c, 0, box_stack_level)
439    Nx.post = ltjs.get_penalty_table('post', c, 0, box_stack_level)
440    local z = fast_find_char_class('lineend', m)
441    Nx.lend = m.size_cache.char_type[Nx.class].kern[z] or 0
442    local y = ltjs.get_penalty_table('xsp', c, 3, box_stack_level)
443    Nx.xspc_before = (y%2==1)
444    Nx.xspc_after  = (y>=2)
445    Nx.auto_kspc = (has_attr(x, attr_autospc)==1)
446    Nx.auto_xspc = (has_attr(x, attr_autoxspc)==1)
447 end
448
449 -- 欧文文字のデータを取得
450 local ligature_head = 1
451 local ligature_tail = 2
452 function set_np_xspc_alchar(Nx, c,x, lig)
453    if c~=-1 then
454       if lig == ligature_head then
455          while x.components and x.subtype and math.floor(x.subtype*0.5)%2==1 do
456             x = x.components; c = x.char
457          end
458       else
459          while x.components and x.subtype and math.floor(x.subtype*0.5)%2==1 do
460             x = node.tail(x.components); c = x.char
461          end
462       end
463       Nx.pre = ltjs.get_penalty_table('pre', c, 0, box_stack_level)
464       Nx.post = ltjs.get_penalty_table('post', c, 0, box_stack_level)
465       Nx.char = 'jcharbdd'
466    else
467       Nx.pre = 0; Nx.post = 0; Nx.char = -1
468    end
469    Nx.met = nil
470    local y = ltjs.get_penalty_table('xsp', c, 3, box_stack_level)
471    Nx.xspc_before = (y%2==1)
472    Nx.xspc_after  = (y>=2)
473    Nx.auto_xspc = (has_attr(x, attr_autoxspc)==1)
474 end
475
476 -- Np の情報取得メインルーチン
477 local function extract_np()
478    local x, i = Np.nuc, Np.id;
479    if i ==  id_jglyph then return set_np_xspc_jachar(Np, x)
480    elseif i == id_glyph then return set_np_xspc_alchar(Np, x.char, x, ligature_head)
481    elseif i == id_hlist then Np.last_char = check_box_high(Np, x.head, nil)
482    elseif i == id_pbox then Np.last_char = check_box_high(Np, Np.first, node.next(Np.last))
483    elseif i == id_disc then Np.last_char = check_box_high(Np, x.replace, nil)
484    elseif i == id_math then return set_np_xspc_alchar(Np, -1, x)
485    end
486 end
487
488 -- change the information for the next loop
489 -- (will be done if Nx is an alphabetic character or a hlist)
490 function after_hlist(Nx)
491    if Nx.last_char then
492       if Nx.last_char.font == has_attr(Nx.last_char, attr_curjfnt) then 
493          set_np_xspc_jachar(Nx, Nx.last_char);
494       else
495          set_np_xspc_alchar(Nx, Nx.last_char.char,Nx.last_char, ligature_tail)
496       end
497    else
498       Nx.pre = nil; Nx.met = nil
499    end
500 end
501
502 local function after_alchar(Nx)
503    local x = Nx.nuc
504    return set_np_xspc_alchar(Nx, x.char,x, ligature_tail)
505 end
506
507
508 -------------------- 最下層の処理
509
510 local function lineend_fix(g)
511    if g and g.id==id_kern then 
512       Nq.lend = 0
513    elseif Nq.lend~=0 then
514       if not g then
515          g = node.new(id_kern); copy_attr(g, Nq.nuc); 
516          g.subtype = 1; g.kern = -Nq.lend;
517      set_attr(g, attr_icflag, LINEEND)
518      set_attr(g, attr_uniqid, uniq_id) 
519       elseif g.id==id_kern then
520          g.kern = g.kern - Nq.lend
521       else
522          g.spec.width = g.spec.width - Nq.lend
523       end
524    end
525    return g
526 end
527
528 -- change penalties (or create a new penalty, if needed)
529 local function handle_penalty_normal(post, pre, g)
530    local a = (pre or 0) + (post or 0)
531    if #Bp == 0 then
532       if (a~=0 and not(g and g.id==id_kern)) or Nq.lend~=0 then
533          local p = node.new(id_penalty); copy_attr(p, Nq.nuc)
534          if a<-10000 then a = -10000 elseif a>10000 then a = 10000 end
535          p.penalty = a
536          head = node.insert_before(head, Np.first, p)
537          Bp[#Bp+1]=p; 
538      set_attr(p, attr_icflag, KINSOKU)
539      set_attr(p, attr_uniqid, uniq_id) 
540       end
541    else for i, v in pairs(Bp) do add_penalty(v,a) end
542    end
543 end
544
545 local function handle_penalty_always(post, pre, g)
546    local a = (pre or 0) + (post or 0)
547    if #Bp == 0 then
548       if not (g and g.id==id_glue) or Nq.lend~=0 then
549          local p = node.new(id_penalty); copy_attr(p, Nq.nuc)
550          if a<-10000 then a = -10000 elseif a>10000 then a = 10000 end
551          p.penalty = a
552          head = node.insert_before(head, Np.first, p)
553          Bp[#Bp+1]=p
554      set_attr(p, attr_icflag, KINSOKU)
555      set_attr(p, attr_uniqid, uniq_id) 
556       end
557    else for i, v in pairs(Bp) do add_penalty(v,a) end
558    end
559 end
560
561 local function handle_penalty_suppress(post, pre, g)
562    local a = (pre or 0) + (post or 0)
563    if #Bp == 0 then
564       if g and g.id==id_glue then
565          local p = node.new(id_penalty); copy_attr(p, Nq.nuc)
566          p.penalty = 10000; head = node.insert_before(head, Np.first, p)
567          Bp[#Bp+1]=p
568      set_attr(p, attr_icflag, KINSOKU)
569      set_attr(p, attr_uniqid, uniq_id) 
570       end
571    else for i, v in pairs(Bp) do add_penalty(v,a) end
572    end
573 end
574
575 -- 和文文字間の JFM glue を node 化
576 local function new_jfm_glue(Nn, bc, ac)
577 -- bc, ac: char classes
578    local g = nil
579    local z = Nn.met.size_cache.char_type[bc]
580    if z.glue[ac] then
581       local h = node.new(id_glue_spec)
582       h.width   = z.glue[ac][1]
583       h.stretch = z.glue[ac][2]
584       h.shrink  = z.glue[ac][3]
585       h.stretch_order=0; h.shrink_order=0
586       g = node.new(id_glue); copy_attr(g, Nn.nuc)
587       g.subtype = 0; g.spec = h
588       set_attr(g, attr_icflag, FROM_JFM); set_attr(g, attr_uniqid, uniq_id)
589    elseif z.kern[ac] then
590       g = node.new(id_kern); copy_attr(g, Nn.nuc)
591       g.subtype = 1; g.kern = z.kern[ac]
592       set_attr(g, attr_icflag, FROM_JFM); set_attr(g, attr_uniqid, uniq_id)
593    end
594    return g
595 end
596
597 -- Nq.last (kern w) .... (glue/kern g) Np.first
598 local function real_insert(w, g)
599    if w~=0 then
600       local h = node.new(id_kern); copy_attr(h, Nq.nuc)
601       set_attr(h, attr_icflag, LINE_END)
602       set_attr(h, attr_uniqid, uniq_id) 
603       h.kern = w; h.subtype = 1
604       head = node.insert_after(head, Nq.last, h)
605    end
606    if g then
607       head = node.insert_before(head, Np.first, g)
608       Np.first = g
609    end
610 end
611
612 -------------------- 和文文字間空白量の決定
613
614 -- get kanjiskip
615 local function get_kanji_skip_from_jfm(Nn)
616    local i = Nn.met.size_cache.kanjiskip
617    if i then
618       return { i[1], i[2], i[3] }
619    else return nil
620    end
621 end
622 local function get_kanjiskip()
623    local g = node.new(id_glue); copy_attr(g, Nq.nuc)
624    if Np.auto_kspc or Nq.auto_kspc then
625       if kanji_skip.width == max_dimen then
626          local gx = node.new(id_glue_spec);
627          gx.stretch_order = 0; gx.shrink_order = 0
628          local bk = get_kanji_skip_from_jfm(Nq)
629          local ak
630          if (Np.met.size_cache==Nq.met.size_cache) and (Nq.var==Np.var) then
631             ak = nil
632          else
633             ak = get_kanji_skip_from_jfm(Np)
634          end
635          if bk then
636             if ak then
637                gx.width = round(diffmet_rule(bk[1], ak[1]))
638                gx.stretch = round(diffmet_rule(bk[2], ak[2]))
639                gx.shrink = -round(diffmet_rule(-bk[3], -ak[3]))
640             else
641                gx.width = bk[1]; gx.stretch = bk[2]; gx.shrink = bk[3]
642             end
643          elseif ak then
644             gx.width = ak[1]; gx.stretch = ak[2]; gx.shrink = ak[3]
645          else node.free(gx); gx = get_zero_spec() -- fallback
646          end
647          g.spec = gx
648       else g.spec=node.copy(kanji_skip); node.free(gx) end
649    else
650       g.spec =  get_zero_spec(); node.free(gx)
651    end
652    set_attr(g, attr_icflag, KANJI_SKIP)
653    set_attr(g, attr_uniqid, uniq_id) 
654    return g
655 end
656
657 local function calc_ja_ja_aux(gb,ga)
658    if not gb then 
659       return ga
660    else
661       if not ga then return gb end
662       local k = node.type(gb.id) .. node.type(ga.id)
663       if k == 'glueglue' then 
664          -- 両方とも glue.
665          gb.spec.width   = round(diffmet_rule(gb.spec.width, ga.spec.width))
666          gb.spec.stretch = round(diffmet_rule(gb.spec.stretch,ga.spec.shrink))
667          gb.spec.shrink  = -round(diffmet_rule(-gb.spec.shrink, -ga.spec.shrink))
668          node.free(ga)
669          return gb
670       elseif k == 'kernkern' then
671          -- 両方とも kern.
672          gb.kern = round(diffmet_rule(gb.kern, ga.kern))
673          node.free(ga)
674          return gb
675       elseif k == 'kernglue' then 
676          -- gb: kern, ga: glue
677          ga.spec.width   = round(diffmet_rule(gb.kern,ga.spec.width))
678          ga.spec.stretch = round(diffmet_rule(ga.spec.stretch, 0))
679          ga.spec.shrink  = -round(diffmet_rule(-ga.spec.shrink, 0))
680          node.free(gb)
681          return ga
682       else
683          -- gb: glue, ga: kern
684          gb.spec.width   = round(diffmet_rule(ga.kern, gb.spec.width))
685          gb.spec.stretch = round(diffmet_rule(gb.spec.stretch, 0))
686          gb.spec.shrink  = -round(diffmet_rule(-gb.spec.shrink, 0))
687          node.free(ga)
688          return gb
689       end
690    end
691 end
692
693 local function calc_ja_ja_glue()
694    if  ihb_flag then return nil
695    elseif (Nq.met.size_cache==Np.met.size_cache) and (Nq.var==Np.var) then
696       return new_jfm_glue(Nq, Nq.class, Np.class)
697    else
698       return calc_ja_ja_aux(new_jfm_glue(Nq, Nq.class, fast_find_char_class('diffmet',Nq.met)),
699                             new_jfm_glue(Np, fast_find_char_class('diffmet',Np.met), Np.class))
700    end
701 end
702
703 -------------------- 和欧文間空白量の決定
704
705 -- get xkanjiskip
706 local function get_xkanji_skip_from_jfm(Nn)
707    local i = Nn.met.size_cache.xkanjiskip
708    if i then
709       return i and { i[1], i[2], i[3] }
710    else return nil
711    end
712 end
713 local function get_xkanjiskip(Nn)
714    local g = node.new(id_glue); copy_attr(g, Nn.nuc)
715    if Nq.xspc_after and Np.xspc_before and (Nq.auto_xspc or Np.auto_xspc) then
716       if xkanji_skip.width == max_dimen then
717          local gx = node.new(id_glue_spec);
718          gx.stretch_order = 0; gx.shrink_order = 0
719          local bk = get_xkanji_skip_from_jfm(Nn)
720          if bk then
721             gx.width = bk[1]; gx.stretch = bk[2]; gx.shrink = bk[3]
722          else node.free(gx); gx = get_zero_spec() -- fallback
723          end
724          g.spec = gx
725       else g.spec=node.copy(xkanji_skip) end
726    else
727       g.spec = get_zero_spec()
728    end
729    set_attr(g, attr_icflag, XKANJI_SKIP)
730    set_attr(g, attr_uniqid, uniq_id) 
731    return g
732 end
733
734
735 -------------------- 隣接した「塊」間の処理
736
737 local function get_OA_skip()
738    if not ihb_flag then
739       return new_jfm_glue(Np, fast_find_char_class(((Nq.id == id_math and -1) or 'jcharbdd'), Np.met), Np.class)
740    else return nil
741    end
742 end
743 local function get_OB_skip()
744    if not ihb_flag then
745       return new_jfm_glue(Nq, Nq.class, fast_find_char_class(((Np.id == id_math and -1) or'jcharbdd'), Nq.met))
746    else return nil
747    end
748 end
749
750 -- (anything) .. jachar
751 local function handle_np_jachar()
752    if Nq.id==id_jglyph or ((Nq.id==id_pbox or Nq.id==id_pbox_w) and Nq.met) then 
753       local g = lineend_fix(calc_ja_ja_glue() or get_kanjiskip()) -- M->K
754       handle_penalty_normal(Nq.post, Np.pre, g); real_insert(Nq.lend, g)
755    elseif Nq.met then  -- Nq.id==id_hlist
756       local g = get_OA_skip() or get_kanjiskip() -- O_A->K
757       handle_penalty_normal(0, Np.pre, g); real_insert(0, g)
758    elseif Nq.pre then 
759       local g = get_OA_skip() or get_xkanjiskip(Np) -- O_A->X
760       if Nq.id==id_hlist then Nq.post = 0 end
761       handle_penalty_normal(Nq.post, Np.pre, g); real_insert(0, g)
762    else
763       local g = get_OA_skip() -- O_A
764       if Nq.id==id_glue then handle_penalty_normal(0, Np.pre, g)
765       elseif Nq.id==id_kern then handle_penalty_suppress(0, Np.pre, g)
766       else handle_penalty_always(0, Np.pre, g)
767       end
768       real_insert(0, g)
769    end
770    -- \jcharwidowpenalty 挿入予定箇所更新
771    if mode and ltjs.get_penalty_table('kcat', Np.char, 0, box_stack_level)%2~=1 then
772       widow_Np.first = Np.first; 
773       local Bpr = widow_Bp; widow_Bp = Bp; Bp = Bpr
774    end
775 end
776
777 -- jachar .. (anything)
778 local function handle_nq_jachar()
779     if Np.pre then 
780       if Np.id==id_hlist then Np.pre = 0 end
781       local g = lineend_fix(get_OB_skip() or get_xkanjiskip(Nq)) -- O_B->X
782       handle_penalty_normal(Nq.post, Np.pre, g); real_insert(Nq.lend, g)
783    else
784       local g = lineend_fix(get_OB_skip()) -- O_B
785       if Np.id==id_glue then handle_penalty_normal(Nq.post, 0, g)
786       elseif Np.id==id_kern then handle_penalty_suppress(Nq.post, 0, g)
787       else handle_penalty_always(Nq.post, 0, g)
788       end
789       real_insert(Nq.lend, g)
790    end
791 end
792
793 -- (anything) .. (和文文字で始まる hlist)
794 local function handle_np_ja_hlist()
795    if Nq.id==id_jglyph or ((Nq.id==id_pbox or Nq.id == id_pbox_w) and Nq.met) then 
796       local g = lineend_fix(get_OB_skip() or get_kanjiskip()) -- O_B->K
797       handle_penalty_normal(Nq.post, 0, g); real_insert(Nq.lend, g)
798    elseif Nq.met then  -- Nq.id==id_hlist
799       local g = get_kanjiskip() -- K
800       handle_penalty_suppress(0, 0, g); real_insert(0, g)
801    elseif Nq.pre then 
802       local g = get_xkanjiskip(Np) -- X
803       handle_penalty_suppress(0, 0, g); real_insert(0, g)
804    end
805 end
806
807 -- (和文文字で終わる hlist) .. (anything)
808 local function handle_nq_ja_hlist()
809    if Np.pre then 
810       local g = get_xkanjiskip(Nq) -- X
811       handle_penalty_suppress(0, 0, g); real_insert(0, g)
812    end
813 end
814
815 -- Nq が前側のクラスタとなることによる修正
816 local function adjust_nq()
817    if Nq.id==id_glyph then after_alchar(Nq)
818    elseif Nq.id==id_hlist or Nq.id==id_pbox or Nq.id==id_disc then after_hlist(Nq)
819    elseif Nq.id == id_pbox_w then 
820       luatexbase.call_callback("luatexja.jfmglue.whatsit_after",
821                                false, Nq, Np, box_stack_level)
822    end
823 end
824
825 -------------------- 開始・終了時の処理
826
827 -- リスト末尾の処理
828 local function handle_list_tail()
829    adjust_nq(); Np = Nq
830    if mode then
831       -- the current list is to be line-breaked:
832       if Np.id == id_jglyph or (Np.id==id_pbox and Np.met) then 
833          if Np.lend~=0 then
834             g = node.new(id_kern); g.subtype = 0; g.kern = Np.lend
835             copy_attr(g, Np.nuc); set_attr(g, attr_icflag, BOXBDD)
836             node.insert_after(head, Np.last, g)
837          end
838       end
839       -- Insert \jcharwidowpenalty
840       Bp = widow_Bp; Np = widow_Np; Nq.lend = 0
841       if Np.first then
842          handle_penalty_normal(0,
843                                ltjs.get_penalty_table('jwp', 0, 0, box_stack_level))
844       end
845    else
846       -- the current list is the contents of a hbox
847       if Np.id == id_jglyph or (Np.id==id_pbox and Np.met) then 
848          local g = new_jfm_glue(Np, Np.class, fast_find_char_class('boxbdd',Np.met))
849          if g then
850             set_attr(g, attr_icflag, BOXBDD)
851             head = node.insert_after(head, Np.last, g)
852          end
853       end
854    end
855 end
856
857 -- リスト先頭の処理
858 local function handle_list_head()
859    if Np.id ==  id_jglyph or (Np.id==id_pbox and Np.met) then 
860       if not ihb_flag then
861          local g
862          if par_indented then
863             g = new_jfm_glue(Np, fast_find_char_class('parbdd',Np.met), Np.class)
864          else
865             g = new_jfm_glue(Np, fast_find_char_class('boxbdd',Np.met), Np.class)
866          end
867          if g then
868             set_attr(g, attr_icflag, BOXBDD)
869             if g.id==id_glue and #Bp==0 then
870                local h = node.new(id_penalty); copy_attr(h, Np.nuc)
871                h.penalty = 10000; set_attr(h, attr_icflag, BOXBDD)
872             end
873             head = node.insert_before(head, Np.first, g)
874          end
875       end
876    end
877 end
878
879 -- initialize
880 local function init_var()
881    uniq_id = uniq_id +1
882    if uniq_id == 0x7FFFFFF then uniq_id = 0 end
883    lp = head; Bp = {}; widow_Bp = {}; widow_Np = {first = nil}
884    par_indented = false 
885    box_stack_level = ltjp.box_stack_level
886    kanji_skip=skip_table_to_spec('kanjiskip')
887    xkanji_skip=skip_table_to_spec('xkanjiskip')
888    Np = {
889       auto_kspc=nil, auto_xspc=nil, char=nil, class=nil, 
890       first=nil, id=nil, last=nil, lend=0, met=nil, nuc=nil, 
891       post=nil, pre=nil, xspc_after=nil, xspc_before=nil, 
892    }
893    Nq = {
894       auto_kspc=nil, auto_xspc=nil, char=nil, class=nil, 
895       first=nil, id=nil, last=nil, lend=0, met=nil, nuc=nil, 
896       post=nil, pre=nil, xspc_after=nil, xspc_before=nil, 
897    }
898    if mode then 
899       -- the current list is to be line-breaked:
900       -- hbox from \parindent is skipped.
901       while lp and ((lp.id==id_whatsit and lp.subtype~=sid_user) 
902                  or ((lp.id==id_hlist) and (lp.subtype==3))) do
903          if (lp.id==id_hlist) and (lp.subtype==3) then par_indented = true end
904          lp=node.next(lp) end
905      last=node.tail(head)
906    else 
907       -- the current list is the contents of a hbox:
908       -- insert a sentinelEG
909       last=node.tail(head); local g = node.new(id_kern)
910       node.insert_after(head, last, g); last = g
911    end
912 end
913
914 local function cleanup()
915    -- adjust attr_icflag for avoiding error
916    tex.setattribute('global', attr_icflag, 0)
917    node.free(kanji_skip); node.free(xkanji_skip)
918    if mode then
919       local h = node.next(head)
920       if h.id == id_penalty and h.penalty == 10000 then
921          h = h.next
922          if h.id == id_glue and h.subtype == 15 and not h.next then
923             return false
924          end
925       end
926       return head
927    else
928       head = node.remove(head, last); node.free(last);-- remove the sentinel
929       return head
930    end
931 end
932 -------------------- 外部から呼ばれる関数
933
934 -- main interface
935 function main(ahead, amode)
936    if not ahead then return ahead end
937    head = ahead; mode = amode; init_var(); calc_np()
938    if Np then 
939       extract_np(); handle_list_head()
940    else
941       return cleanup()
942    end
943    calc_np()
944    while Np do
945       extract_np(); adjust_nq()
946       -- 挿入部
947       if Np.id == id_jglyph then 
948          handle_np_jachar()
949       elseif Np.met then 
950          if Np.id==id_hlist then handle_np_ja_hlist()
951          else handle_np_jachar() end
952       elseif Nq.met then 
953          if Nq.id==id_hlist then handle_nq_ja_hlist()
954          else handle_nq_jachar() end
955       end
956       calc_np()
957    end
958    handle_list_tail()
959    return cleanup()
960 end
961
962 -- \inhibitglue
963
964 function create_inhibitglue_node()
965    local tn = node.new(id_whatsit, sid_user)
966    tn.user_id=30111; tn.type=100; tn.value=1
967    node.write(tn)
968 end
969
970 -- Node for indicating beginning of a paragraph
971 -- (for ltjsclasses)
972 function create_beginpar_node()
973    local tn = node.new(id_whatsit, sid_user)
974    tn.user_id=30114; tn.type=100; tn.value=1
975    node.write(tn)
976 end
977
978 local function whatsit_callback(Np, lp, Nq, bsl)
979    if Np and Np.nuc then return Np 
980    elseif Np and lp.user_id == 30114 then
981       Np.first = lp; Np.nuc = lp; Np.last = lp
982       Np.char = 'parbdd'
983       Np.met = nil
984       Np.pre = 0; Np.post = 0
985       Np.xspc_before = false
986       Np.xspc_after  = false
987       Np.auto_xspc = false
988       return Np
989    end
990 end
991 local function whatsit_after_callback(s, Nq, Np, bsl)
992    if not s and Nq.nuc.user_id == 30114 then
993       local x, y = node.prev(Nq.nuc), Nq.nuc
994       Nq.first, Nq.nuc, Nq.last = x, x, x
995       head = node.remove(head, y)
996    end
997    return s
998 end
999
1000 luatexbase.add_to_callback("luatexja.jfmglue.whatsit_getinfo", whatsit_callback,
1001                            "luatexja.beginpar.np_info", 1)
1002 luatexbase.add_to_callback("luatexja.jfmglue.whatsit_after", whatsit_after_callback,
1003                            "luatexja.beginpar.np_info_after", 1)
1004