Debian Codegraph @

texmf-dist/tex/luatex/luaotfload/luaotfload-letterspace.lua

raw
1 -----------------------------------------------------------------------
2 -- FILE: luaotfload-letterspace.lua
3 -- DESCRIPTION: part of luaotfload / letterspacing
4 -----------------------------------------------------------------------
5
6 assert(luaotfload_module, "This is a part of luaotfload and should not be loaded independently") {
7 name = "luaotfload-letterspace",
8 version = "3.29", --TAGVERSION
9 date = "2024-12-03", --TAGDATE
10 description = "luaotfload submodule / letterspacing",
11 license = "GPL v2.0",
12 copyright = "PRAGMA ADE / ConTeXt Development Team",
13 author = "Hans Hagen, PRAGMA-ADE, Hasselt NL; adapted by Philipp Gesang, Ulrike Fischer, Marcel Krüger"
14 }
15
16 --- This code diverged quite a bit from its origin in Context. Please
17 --- do *not* report bugs on the Context list.
18
19 local logreport = luaotfload.log.report
20
21 local getmetatable = getmetatable
22 local setmetatable = setmetatable
23 local tonumber = tonumber
24 local unpack = table.unpack
25
26 local next = next
27 local node, fonts = node, fonts
28
29 local nodedirect = node.direct
30
31 local getfield = nodedirect.getfield
32 local setfield = nodedirect.setfield
33
34 local getfont = nodedirect.getfont
35 local getid = nodedirect.getid
36
37 local getnext = nodedirect.getnext
38 local setnext = nodedirect.setnext
39
40 local getprev = nodedirect.getprev
41 local setprev = nodedirect.setprev
42
43 local getboth = nodedirect.getboth
44
45 local setlink = nodedirect.setlink
46
47 local getdisc = nodedirect.getdisc
48 local setdisc = nodedirect.setdisc
49
50 local getsubtype = nodedirect.getsubtype
51 local setsubtype = nodedirect.setsubtype
52
53 local getchar = nodedirect.getchar
54 local setchar = nodedirect.setchar
55
56 local getkern = nodedirect.getkern
57 local setkern = nodedirect.setkern
58
59 local getglue = nodedirect.getglue
60 local setglue = nodedirect.setglue
61
62 local hasattribute = nodedirect.has_attribute
63 local setattribute = nodedirect.set_attribute
64
65 local getattributelist = nodedirect.getattributelist
66 local setattributelist = nodedirect.setattributelist
67
68 local find_node_tail = nodedirect.tail
69 local todirect = nodedirect.todirect
70 local tonode = nodedirect.tonode
71
72 local insert_node_before = nodedirect.insert_before
73 local real_free_node = nodedirect.free
74 local copy_node = nodedirect.copy
75 local new_node = nodedirect.new
76
77 local glyph_code = node.id"glyph"
78 local kern_code = node.id"kern"
79 local disc_code = node.id"disc"
80 local glue_code = node.id"glue"
81 local whatsit_code = node.id"whatsit"
82
83 local fonthashes = fonts.hashes
84 local identifiers = fonthashes.identifiers
85 local chardata = fonthashes.characters
86 local otffeatures = fonts.constructors.newfeatures "otf"
87 local markdata
88
89 -- For every attribute list cached in attribute_table, we have to make
90 -- sure that it doesn't get deleted. Therefore attribute_cleanup maps
91 -- from a node which has the attribute_list referenced in
92 -- attribute_table to the key from attribute_table.
93 -- Whenever a node which has an entry in attribute_cleanup is deleted,
94 -- we delete the corresponding entry from attribute_table since we can
95 -- no longer guarantee that it's references somewhere.
96 local attribute_table = {}
97 local attribute_cleanup = {}
98 local attr = luatexbase.new_attribute("luaotfload.letterspace_done")
99
100 local function free_node(n)
101 local k = attribute_cleanup[n]
102 if k then
103 attribute_cleanup[n], attribute_table[k] = nil
104 end
105 return real_free_node(n)
106 end
107
108 local function getprevreal(n)
109 repeat
110 n = getprev(n)
111 until not n or getid(n) ~= whatsit_code
112 return n
113 end
114 local function getnextreal(n)
115 repeat
116 n = getnext(n)
117 until not n or getid(n) ~= whatsit_code
118 return n
119 end
120
121 --[[doc--
122
123 Since the letterspacing method was derived initially from Context’s
124 typo-krn.lua we keep the sub-namespace “letterspace” inside the
125 “luaotfload” table.
126
127 --doc]]--
128
129 luaotfload.letterspace = luaotfload.letterspace or { }
130 local letterspace = luaotfload.letterspace
131
132 local lectured = false
133 letterspace.keepligature = true
134 letterspace.keeptogether = false
135 letterspace.keepwordspacing = false
136
137 ---=================================================================---
138 --- preliminary definitions
139 ---=================================================================---
140 -- We set up a layer emulating some Context internals that are needed
141 -- for the letterspacing callback.
142 -----------------------------------------------------------------------
143 --- node-ini
144 -----------------------------------------------------------------------
145
146 local kerning_code = 0
147 local userkern_code = 1
148 local userskip_code = 0
149 local spaceskip_code = 13
150 local xspaceskip_code = 14
151
152 if not chardata then
153 chardata = { }
154 table.setmetatableindex(chardata, function(t, k)
155 if k == true then
156 return chardata[currentfont()]
157 else
158 local tfmdata = font.getfont(k) or font.fonts[k]
159 if tfmdata then
160 local characters = tfmdata.characters
161 t[k] = characters
162 return characters
163 end
164 end
165 end)
166 fonthashes.characters = chardata
167 end
168
169 if not markdata then
170 markdata = setmetatable({}, {__index = function(t, k)
171 if k == true then
172 return t[currentfont()]
173 else
174 local tfmdata = font.getfont(k) or font.fonts[k]
175 if tfmdata then
176 local marks = tfmdata.resources.marks or {}
177 t[k] = marks
178 return marks
179 end
180 end
181 end})
182 end
183
184 ---=================================================================---
185 --- character kerning functionality
186 ---=================================================================---
187
188 -- UF changed 2017-07-14
189 local function kern_injector (fillup, kern)
190 if fillup then
191 local g = new_node(glue_code)
192 setglue(g, 0, kern, 0, 1, 0)
193 return g
194 end
195 local g = new_node(kern_code)
196 setkern(g,kern)
197 return g
198 end
199 -- /UF
200
201 local function kernable_skip (n)
202 local st = getsubtype (n)
203 return st == userskip_code
204 or st == spaceskip_code
205 or st == xspaceskip_code
206 end
207
208 --[[doc--
209
210 Caveat lector.
211 This is an adaptation of the Context character kerning mechanism
212 that emulates XeTeX-style fontwise letterspacing. Note that in its
213 present state it is far inferior to the original, which is
214 attribute-based and ignores font-boundaries. Nevertheless, due to
215 popular demand the following callback has been added.
216
217 --doc]]--
218
219 local kernamounts = table.setmetatableindex(function (t, f) --- fontid -> {kern, fill}
220 local tfmdata = font.getfont(f) or font.fonts[f]
221 if tfmdata then
222 local fontproperties = tfmdata.properties
223 local fontparameters = tfmdata.parameters
224 if fontproperties and fontparameters then
225 local r
226 if fontproperties.kerncharacters == "max" then
227 r = {fontparameters.quad/4, true}
228 elseif fontproperties.kerncharacters then
229 r = {fontproperties.kerncharacters * fontparameters.quad, false}
230 else
231 r = {}
232 end
233 t[f] = r
234 return r
235 end
236 end
237 return {}
238 end)
239
240 local kerncharacters
241 kerncharacters = function (head)
242 local start = head
243 local lastfont = nil
244 local keeptogether = letterspace.keeptogether --- function
245 local keepligature = letterspace.keepligature
246 -- if not lectured and keepligature ~= true then
247 -- logreport ("both", 0, "letterspace",
248 -- "Breaking ligatures through letterspacing is deprecated and "
249 -- .. "will be removed soon. Please disable unwanted ligatures through "
250 -- .. "font features instead and reset luaotfload.letterspace.keepligature "
251 -- .. "to true to maintain compatibility with future versions of luaotfload.")
252 -- lectured = true
253 -- end
254 if type(keepligature) ~= "function" then
255 local savedligature = keepligature
256 keepligature = function() return savedligature end
257 end
258 local keepwordspacing = letterspace.keepwordspacing
259 if type(keepwordspacing) ~= "function" then
260 local savedwordspacing = keepwordspacing
261 keepwordspacing = function() return savedwordspacing end
262 end
263
264 local kernamounts = kernamounts
265 local firstkern = true
266
267 while start do
268 local id = getid(start)
269 if id == glyph_code then
270 --- 1) look up kern factor (slow, but cached rudimentarily)
271 if hasattribute(start, attr, 1) then -- We already kerned this node
272 firstkern = false -- TODO: I'm not sure about this one yet
273 goto nextnode
274 end
275 local fontid = getfont(start)
276 local krn, fillup = unpack(kernamounts[fontid])
277 if not krn or krn == 0 then
278 firstkern = true
279 goto nextnode
280 elseif firstkern then
281 firstkern = false
282 if (id ~= disc_code) and (not getfield(start, "components")) then
283 --- not a ligature, skip node
284 goto nextnode
285 end
286 end
287
288 lastfont = fontid
289
290 --- 2) resolve ligatures
291 local c = getfield(start, "components")
292
293 if c then
294 if keepligature(start) then
295 -- keep 'm
296 c = nil
297 else
298 while c do
299 local s = start
300 local p, n = getboth (s)
301 if p then
302 setlink (p, c)
303 else
304 head = c
305 end
306 if n then
307 local tail = find_node_tail(c)
308 setlink (tail, n)
309 end
310 start = c
311 setfield(s, "components", nil)
312 free_node(s) --> double free with multipart components
313 c = getfield (start, "components")
314 end
315 end
316 end -- kern ligature
317
318 --- 3) apply the extra kerning
319 local prev = getprevreal(start)
320 if prev then
321 local pid = getid(prev)
322
323 if not pid then
324 -- nothing
325
326 elseif pid == glue_code and kernable_skip(prev)
327 and not keepwordspacing(prev, lastfont) then
328 local wd, stretch, shrink = getglue(prev)
329 if wd > 0 then
330 local newwd = wd + krn
331 local stretched = (stretch * newwd) / wd
332 local shrunk = (shrink * newwd) / wd
333 if fillup then
334 setglue(prev, newwd, 2 * stretched, 2 * shrunk, 1, 0)
335 else
336 setglue(prev, newwd, stretched, shrunk, 0, 0)
337 end
338 end
339
340 elseif pid == kern_code then
341 local prev_subtype = getsubtype(prev)
342 if prev_subtype == kerning_code --- context does this by means of an
343 or prev_subtype == userkern_code --- attribute; we may need a test
344 then
345
346 local pprev = getprevreal(prev)
347 local pprev_id = getid(pprev)
348
349 if keeptogether
350 and pprev_id == glyph_code
351 and keeptogether(pprev, start)
352 then
353 -- keep
354 else
355 local prev_kern = getkern(prev)
356 prev_kern = prev_kern + krn
357 setkern (prev, prev_kern)
358 end
359 end
360
361 elseif pid == glyph_code then
362 if getfont(prev) == lastfont then
363 local prevchar = getchar(prev)
364 local lastchar = getchar(start)
365 if keeptogether and keeptogether(prev, start) then
366 -- keep 'm
367 elseif identifiers[lastfont] then
368 local lastfontchars = chardata[lastfont]
369 if lastfontchars then
370 local prevchardata = lastfontchars[prevchar]
371 if not prevchardata then
372 --- font doesn’t contain the glyph
373 else
374 local kern = 0
375 local kerns = prevchardata.kerns
376 if kerns then kern = kerns[lastchar] or kern end
377 krn = kern + (markdata[lastfont][lastchar] and 0 or krn) -- here
378 insert_node_before(head,start,kern_injector(fillup,krn))
379 end
380 end
381 end
382 else
383 insert_node_before(head,start,kern_injector(fillup,krn))
384 end
385
386 elseif pid == disc_code then
387 local disc = prev -- disc
388 local pre, post, replace = getdisc (disc)
389 local prv = getprevreal(disc)
390 local nxt = getnextreal(disc)
391
392 if pre and prv then -- must pair with start.prev
393 -- this one happens in most cases
394 local before = copy_node(prv)
395 setprev(pre, before)
396 setnext(before, pre)
397 setprev(before, nil)
398 pre = kerncharacters (before)
399 pre = getnext(pre)
400 setprev(pre, nil)
401 setfield(disc, "pre", pre)
402 free_node(before)
403 end
404
405 if post and nxt then -- must pair with start
406 local after = copy_node(nxt)
407 local tail = find_node_tail(post)
408 setnext(tail, after)
409 setprev(after, tail)
410 post = kerncharacters (post)
411 setnext(getprev(after), nil)
412 setfield(disc, "post", post)
413 free_node(after)
414 end
415
416 if replace and prv and nxt then -- must pair with start and start.prev
417 local before = copy_node(prv)
418 local after = copy_node(nxt)
419 local tail = find_node_tail(replace)
420 setprev(replace, before)
421 setnext(before, replace)
422 setprev(before, nil)
423 setnext(tail, after)
424 setprev(after, tail)
425 setnext(after, nil)
426 replace = kerncharacters (before)
427 replace = getnext(replace)
428 setprev(replace, nil)
429 setnext(getprev(after), nil)
430 setfield(disc, "replace", replace)
431 free_node(after)
432 free_node(before)
433
434 elseif identifiers[lastfont] then
435 if prv
436 and getid(prv) == glyph_code
437 and getfont(prv) == lastfont
438 then
439 local kern = 0
440 local prevchar = getchar(prv)
441 local lastchar = getchar(start)
442 local lastfontchars = chardata[lastfont]
443 if lastfontchars then
444 local prevchardata = lastfontchars[prevchar]
445 if not prevchardata then
446 --- font doesn’t contain the glyph
447 else
448 local kerns = prevchardata.kerns
449 if kerns then kern = kerns[lastchar] or kern end
450 end
451 end
452 krn = kern + (markdata[lastfont][lastchar] and 0 or krn) -- here
453 end
454 setfield(disc, "replace", kern_injector(false, krn))
455 end --[[if replace and prv and nxt]]
456 end --[[if not pid]]
457 local attr_list = getattributelist(start)
458 local new_attr_list = attribute_table[attr_list]
459 if new_attr_list then
460 setattributelist(start, new_attr_list)
461 else
462 setattribute(start, attr, 1)
463 attribute_cleanup[start] = attr_list
464 attribute_table[attr_list] = getattributelist(start)
465 end
466 end --[[if prev]]
467 end --[[if id == glyph_code]]
468
469 ::nextnode::
470 if start then
471 start = getnext(start)
472 end
473 end
474 return head
475 end
476
477 ---=================================================================---
478 --- integration
479 ---=================================================================---
480
481 --- · callback: kerncharacters
482 --- · enabler: enablefontkerning
483
484 --- callback wrappers
485
486 --- (node_t -> node_t) -> string -> string list -> bool
487 local registered_as = { } --- procname -> callbacks
488 local function add_processor (processor, name, ...)
489 local callbacks = { ... }
490 for i=1, #callbacks do
491 luatexbase.add_to_callback(callbacks[i], processor, name)
492 end
493 registered_as[name] = callbacks --- for removal
494 return true
495 end
496
497 --- When font kerning is requested, usually by defining a font with the
498 --- ``letterspace`` parameter, we inject a wrapper for the
499 --- ``kerncharacters()`` node processor in the relevant callbacks. This
500 --- wrapper initially converts the received head node into its “direct”
501 --- counterpart. Likewise, the callback result is converted back to an
502 --- ordinary node prior to returning. Internally, ``kerncharacters()``
503 --- performs all node operations on direct nodes.
504
505 --- unit -> bool
506 local function enablefontkerning ( )
507
508 local function handler (hd)
509 local direct_hd = todirect (hd)
510 logreport ("term", 5, "letterspace",
511 "kerncharacters() invoked with node.direct interface \z
512 (``%s`` -> ``%s``)", tostring (hd), tostring (direct_hd))
513 local direct_hd = kerncharacters (direct_hd)
514 if not direct_hd then --- bad
515 logreport ("both", 0, "letterspace",
516 "kerncharacters() failed to return a valid new head")
517 end
518
519 for k, v in next, attribute_cleanup do attribute_cleanup[k], attribute_table[v] = nil end
520 assert(not next(attribute_table))
521
522 return tonode (direct_hd)
523 end
524
525 return add_processor( handler
526 , "luaotfload.letterspace"
527 , "pre_linebreak_filter"
528 , "hpack_filter")
529 end
530
531 --[[doc--
532
533 Fontwise kerning is enabled via the “kernfactor” option at font
534 definition time. Unlike the Context implementation which relies on
535 Luatex attributes, it uses a font property for passing along the
536 letterspacing factor of a node.
537
538 The callback is activated the first time a letterspaced font is
539 requested and stays active until the end of the run. Since the font
540 is a property of individual glyphs, every glyph in the entire
541 document must be checked for the kern property. This is quite
542 inefficient compared to Context’s attribute based approach, but Xetex
543 compatibility reduces our options significantly.
544
545 --doc]]--
546
547
548 local fontkerning_enabled = false --- callback state
549
550 --- fontobj -> float -> unit
551 local function initializefontkerning (tfmdata, factor)
552 if factor ~= "max" then
553 factor = tonumber (factor) or 0
554 end
555 if factor == "max" or factor ~= 0 then
556 local fontproperties = tfmdata.properties
557 if fontproperties then
558 --- hopefully this field stays unused otherwise
559 fontproperties.kerncharacters = factor
560 end
561 if not fontkerning_enabled then
562 fontkerning_enabled = enablefontkerning ()
563 end
564 end
565 end
566
567 --- like the font colorization, fontwise kerning is hooked into the
568 --- feature mechanism
569
570 otffeatures.register {
571 name = "kernfactor",
572 description = "kernfactor",
573 initializers = {
574 base = initializefontkerning,
575 node = initializefontkerning,
576 plug = initializefontkerning,
577 }
578 }
579
580 --[[doc--
581
582 The “letterspace” feature is essentially identical with the above
583 “kernfactor” method, but scales the factor to percentages to match
584 Xetex’s behavior. (See the Xetex reference, page 5, section 1.2.2.)
585
586 Since Xetex doesn’t appear to have a (documented) “max” keyword, we
587 assume all input values are numeric.
588
589 --doc]]--
590
591 local function initializecompatfontkerning (tfmdata, percentage)
592 local factor = tonumber (percentage)
593 if not factor then
594 logreport ("both", 0, "letterspace",
595 "Invalid argument to letterspace: %s (type %q), " ..
596 "was expecting percentage as Lua number instead.",
597 percentage, type (percentage))
598 return
599 end
600 return initializefontkerning (tfmdata, factor * 0.01)
601 end
602
603 otffeatures.register {
604 name = "letterspace",
605 description = "letterspace",
606 initializers = {
607 base = initializecompatfontkerning,
608 node = initializecompatfontkerning,
609 plug = initializecompatfontkerning,
610 }
611 }
612
613 --[[example--
614
615 See https://bitbucket.org/phg/lua-la-tex-tests/src/tip/pln-letterspace-8-compare.tex
616 for an example.
617
618 --example]]--
619
620 --- vim:sw=2:ts=2:expandtab:tw=71
621