summaryrefslogtreecommitdiff
path: root/tex/context/base/typo-krn.lua
blob: 56f58bb732d74ce7e2f194ca8ef04e0720e56074 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
if not modules then modules = { } end modules ['typo-krn'] = {
    version   = 1.001,
    comment   = "companion to typo-krn.mkiv",
    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
    copyright = "PRAGMA ADE / ConTeXt Development Team",
    license   = "see context related readme files"
}

-- glue is still somewhat suboptimal

local next, type, tonumber = next, type, tonumber
local utfchar = utf.char

local nodes, node, fonts = nodes, node, fonts

local find_node_tail     = node.tail or node.slide
local free_node          = node.free
local free_nodelist      = node.flush_list
local copy_node          = node.copy
local copy_nodelist      = node.copy_list
local insert_node_before = node.insert_before
local insert_node_after  = node.insert_after
local end_of_math        = node.end_of_math

local texsetattribute    = tex.setattribute
local unsetvalue         = attributes.unsetvalue

local nodepool           = nodes.pool
local tasks              = nodes.tasks

local new_gluespec       = nodepool.gluespec
local new_kern           = nodepool.kern
local new_glue           = nodepool.glue

local nodecodes          = nodes.nodecodes
local kerncodes          = nodes.kerncodes
local skipcodes          = nodes.skipcodes
local disccodes          = nodes.disccodes

local glyph_code         = nodecodes.glyph
local kern_code          = nodecodes.kern
local disc_code          = nodecodes.disc
local glue_code          = nodecodes.glue
local hlist_code         = nodecodes.hlist
local vlist_code         = nodecodes.vlist
local math_code          = nodecodes.math

local discretionary_code = disccodes.discretionary
local kerning_code       = kerncodes.kerning
local userkern_code      = kerncodes.userkern
local userskip_code      = skipcodes.userskip
local spaceskip_code     = skipcodes.spaceskip
local xspaceskip_code    = skipcodes.xspaceskip

local fonthashes         = fonts.hashes
local fontdata           = fonthashes.identifiers
local chardata           = fonthashes.characters
local quaddata           = fonthashes.quads
local markdata           = fonthashes.marks
local fontproperties     = fonthashes.properties
local fontdescriptions   = fonthashes.descriptions
local fontfeatures       = fonthashes.features

local tracers            = nodes.tracers
local setcolor           = tracers.colors.set
local resetcolor         = tracers.colors.reset

local v_max              = interfaces.variables.max
local v_auto             = interfaces.variables.auto

typesetters              = typesetters or { }
local typesetters        = typesetters

typesetters.kerns        = typesetters.kerns or { }
local kerns              = typesetters.kerns

local report             = logs.reporter("kerns")
local trace_ligatures    = false  trackers.register("typesetters.kerns.ligatures",function(v) trace_ligatures = v end)

kerns.mapping            = kerns.mapping or { }
kerns.factors            = kerns.factors or { }
local a_kerns            = attributes.private("kern")
local a_fontkern         = attributes.private('fontkern')

local contextsetups      = fonts.specifiers.contextsetups

storage.register("typesetters/kerns/mapping", kerns.mapping, "typesetters.kerns.mapping")
storage.register("typesetters/kerns/factors", kerns.factors, "typesetters.kerns.factors")

local mapping = kerns.mapping
local factors = kerns.factors

-- one must use liga=no and mode=base and kern=yes
-- use more helpers
-- make sure it runs after all others
-- there will be a width adaptor field in nodes so this will change
-- todo: interchar kerns / disc nodes / can be made faster
-- todo: use insert_before etc

local gluefactor = 4 -- assumes quad = .5 enspace

kerns.keepligature = false -- just for fun (todo: control setting with key/value)
kerns.keeptogether = false -- just for fun (todo: control setting with key/value)

-- red   : kept by dynamic feature
-- green : kept by static feature
-- blue  : keep by goodie

function kerns.keepligature(n) -- might become default
    local f = n.font
    local a = n[0] or 0
    if trace_ligatures then
        local c = n.char
        local d = fontdescriptions[f][c].name
        if a > 0 and contextsetups[a].keepligatures == v_auto then
            report("font %!font:name!, glyph %a, slot %X -> ligature %s, by %s feature %a",f,d,c,"kept","dynamic","keepligatures")
            setcolor(n,"darkred")
            return true
        end
        local k = fontfeatures[f].keepligatures
        if k == v_auto then
            report("font %!font:name!, glyph %a, slot %X -> ligature %s, by %s feature %a",f,d,c,"kept","static","keepligatures")
            setcolor(n,"darkgreen")
            return true
        end
        if not k then
            report("font %!font:name!, glyph %a, slot %X -> ligature %s, by %s feature %a",f,d,c,"split","static","keepligatures")
            resetcolor(n)
            return false
        end
        local k = fontproperties[f].keptligatures
        if not k then
            report("font %!font:name!, glyph %a, slot %X -> ligature %s, %s goodie specification",f,d,c,"split","no")
            resetcolor(n)
            return false
        end
        if k and k[c] then
            report("font %!font:name!, glyph %a, slot %X -> ligature %s, %s goodie specification",f,d,c,"kept","by")
            setcolor(n,"darkblue")
            return true
        else
            report("font %!font:name!, glyph %a, slot %X -> ligature %s, %s goodie specification",f,d,c,"split","by")
            resetcolor(n)
            return false
        end
    else
        if a > 0 and contextsetups[a].keepligatures == v_auto then
            return true
        end
        local k = fontfeatures[f].keepligatures
        if k == v_auto then
            return true
        end
        if not k then
            return false
        end
        local k = fontproperties[f].keptligatures
        if not k then
            return false
        end
        if k and k[c] then
            return true
        end
    end
end

-- can be optimized .. the prev thing .. but hardly worth the effort

local function kern_injector(fillup,kern)
    if fillup then
        local g = new_glue(kern)
        local s = g.spec
        s.stretch = kern
        s.stretch_order = 1
        return g
    else
        return new_kern(kern)
    end
end

local function spec_injector(fillup,width,stretch,shrink)
    if fillup then
        local s = new_gluespec(width,2*stretch,2*shrink)
        s.stretch_order = 1
        return s
    else
        return new_gluespec(width,stretch,shrink)
    end
end

-- needs checking ... base mode / node mode -- also use insert_before/after etc

local function do_process(head,force) -- todo: glue so that we can fully stretch
    local start, done, lastfont = head, false, nil
    local keepligature = kerns.keepligature
    local keeptogether = kerns.keeptogether
    local fillup = false
    while start do
        -- faster to test for attr first
        local attr = force or start[a_kerns]
        if attr and attr > 0 then
            start[a_kerns] = unsetvalue
            local krn = mapping[attr]
            if krn == v_max then
                krn = .25
                fillup = true
            else
                fillup = false
            end
            if krn and krn ~= 0 then
                local id = start.id
                if id == glyph_code then
                    lastfont = start.font
                    local c = start.components
                    if not c then
                        -- fine
                    elseif keepligature and keepligature(start) then
                        -- keep 'm
                    else
                        c = do_process(c,attr)
                        local s = start
                        local p, n = s.prev, s.next
                        local tail = find_node_tail(c)
                        if p then
                            p.next = c
                            c.prev = p
                        else
                            head = c
                        end
                        if n then
                            n.prev = tail
                        end
                        tail.next = n
                        start = c
                        s.components = nil
                        -- we now leak nodes !
                     -- free_node(s)
                        done = true
                    end
                    local prev = start.prev
                    if not prev then
                        -- skip
                    elseif markdata[lastfont][start.char] then
                            -- skip
                    else
                        local pid = prev.id
                        if not pid then
                            -- nothing
                        elseif pid == kern_code then
                            if prev.subtype == kerning_code or prev[a_fontkern] then
                                if keeptogether and prev.prev.id == glyph_code and keeptogether(prev.prev,start) then -- we could also pass start
                                    -- keep 'm
                                else
                                    -- not yet ok, as injected kerns can be overlays (from node-inj.lua)
                                    prev.subtype = userkern_code
                                    prev.kern = prev.kern + quaddata[lastfont]*krn -- here
                                    done = true
                                end
                            end
                        elseif pid == glyph_code then
                            if prev.font == lastfont then
                                local prevchar, lastchar = prev.char, start.char
                                if keeptogether and keeptogether(prev,start) then
                                    -- keep 'm
                                else
                                    local kerns = chardata[lastfont][prevchar].kerns
                                    local kern = kerns and kerns[lastchar] or 0
                                    krn = kern + quaddata[lastfont]*krn -- here
                                    insert_node_before(head,start,kern_injector(fillup,krn))
                                    done = true
                                end
                            else
                                krn = quaddata[lastfont]*krn -- here
                                insert_node_before(head,start,kern_injector(fillup,krn))
                                done = true
                            end
                        elseif pid == disc_code then
                            -- a bit too complicated, we can best not copy and just calculate
                            -- but we could have multiple glyphs involved so ...
                            local disc = prev -- disc
                            local prv, nxt = disc.prev, disc.next
                            if disc.subtype == discretionary_code then
                                -- maybe we should forget about this variant as there is no glue
                                -- possible
                                local pre, post, replace = disc.pre, disc.post, disc.replace
                                if pre and prv then -- must pair with start.prev
                                    -- this one happens in most cases
                                    local before = copy_node(prv)
                                    pre.prev = before
                                    before.next = pre
                                    before.prev = nil
                                    pre = do_process(before,attr)
                                    pre = pre.next
                                    pre.prev = nil
                                    disc.pre = pre
                                    free_node(before)
                                end
                                if post and nxt then  -- must pair with start
                                    local after = copy_node(nxt)
                                    local tail = find_node_tail(post)
                                    tail.next = after
                                    after.prev = tail
                                    after.next = nil
                                    post = do_process(post,attr)
                                    tail.next = nil
                                    disc.post = post
                                    free_node(after)
                                end
                                if replace and prv and nxt then -- must pair with start and start.prev
                                    local before = copy_node(prv)
                                    local after = copy_node(nxt)
                                    local tail = find_node_tail(replace)
                                    replace.prev = before
                                    before.next = replace
                                    before.prev = nil
                                    tail.next = after
                                    after.prev = tail
                                    after.next = nil
                                    replace = do_process(before,attr)
                                    replace = replace.next
                                    replace.prev = nil
                                    after.prev.next = nil
                                    disc.replace = replace
                                    free_node(after)
                                    free_node(before)
                                elseif prv and prv.id == glyph_code and prv.font == lastfont then
                                    local prevchar, lastchar = prv.char, start.char
                                    local kerns = chardata[lastfont][prevchar].kerns
                                    local kern = kerns and kerns[lastchar] or 0
                                    krn = kern + quaddata[lastfont]*krn -- here
                                    disc.replace = kern_injector(false,krn) -- only kerns permitted, no glue
                                else
                                    krn = quaddata[lastfont]*krn -- here
                                    disc.replace = kern_injector(false,krn) -- only kerns permitted, no glue
                                end
                            else
                                -- this one happens in most cases: automatic (-), explicit (\-), regular (patterns)
                                if prv and prv.id == glyph_code and prv.font == lastfont then
                                    local prevchar, lastchar = prv.char, start.char
                                    local kerns = chardata[lastfont][prevchar].kerns
                                    local kern = kerns and kerns[lastchar] or 0
                                    krn = kern + quaddata[lastfont]*krn -- here
                                else
                                    krn = quaddata[lastfont]*krn -- here
                                end
                                insert_node_before(head,start,kern_injector(fillup,krn))
                            end
                        end
                    end
                elseif id == glue_code then
                    local subtype = start.subtype
                    if subtype == userskip_code or subtype == xspaceskip_code or subtype == spaceskip_code then
                        local s = start.spec
                        local w = s.width
                        if w > 0 then
                            local width, stretch, shrink = w+gluefactor*w*krn, s.stretch, s.shrink
                            start.spec = spec_injector(fillup,width,stretch*width/w,shrink*width/w)
                            done = true
                        end
                    end
                elseif id == kern_code then
                 -- if start.subtype == kerning_code then -- handle with glyphs
                 --     local sk = start.kern
                 --     if sk > 0 then
                 --         start.kern = sk*krn
                 --         done = true
                 --     end
                 -- end
                elseif lastfont and (id == hlist_code or id == vlist_code) then -- todo: lookahead
                    local p = start.prev
                    if p and p.id ~= glue_code then
                        insert_node_before(head,start,kern_injector(fillup,quaddata[lastfont]*krn))
                        done = true
                    end
                    local n = start.next
                    if n and n.id ~= glue_code then
                        insert_node_after(head,start,kern_injector(fillup,quaddata[lastfont]*krn))
                        done = true
                    end
                elseif id == math_code then
                    start = end_of_math(start)
                end
            end
        end
        if start then
            start = start.next
        end
    end
    return head, done
end

local enabled = false

function kerns.set(factor)
    if factor ~= v_max then
        factor = tonumber(factor) or 0
    end
    if factor == v_max or factor ~= 0 then
        if not enabled then
            tasks.enableaction("processors","typesetters.kerns.handler")
            enabled = true
        end
        local a = factors[factor]
        if not a then
            a = #mapping + 1
            factors[factors], mapping[a] = a, factor
        end
        factor = a
    else
        factor = unsetvalue
    end
    texsetattribute(a_kerns,factor)
    return factor
end

function kerns.handler(head)
    return do_process(head)  -- no direct map, because else fourth argument is tail == true
end

-- interface

commands.setcharacterkerning = kerns.set