Debian Codegraph @

texmf-dist/tex/lualatex/linebreaker/linebreaker.lua

raw
1 -- linebreaker.lua
2 --
3 -- (c) Michal Hoftich <[email protected]>
4 --
5 -- This program can be redistributed and/or modified under the terms
6 -- of the LaTeX Project Public License Distributed from CTAN archives
7 -- in directory macros/latex/base/lppl.txt.
8
9 local linebreaker = {}
10
11 local hlist_id = node.id "hlist"
12 local glyph_id = node.id "glyph"
13 local glue_id = node.id "glue"
14 local vlist_id = node.id "vlist"
15 local maxval = 0x10FFFF
16
17 local fonts = fonts or {}
18 fonts.hashes = fonts.hashes or {}
19 local font_identifiers = fonts.hashes.identifiers or {}
20
21
22 -- debugging function, it can be redefined to print debug info if needed
23 -- it discards arguments by default
24 function linebreaker.debug_print(...)
25 if linebreaker.debug then
26 print(table.concat({...}, "\t"))
27 end
28 end
29
30 linebreaker.debug = false
31
32 -- max allowed value of tolerance
33 linebreaker.max_tolerance = 8189 -- maximal possible value of tolerance (thanks to Jan Šustek for pointing that out)
34 -- maximal allowed emergencystretch
35 linebreaker.max_emergencystretch = tex.sp("3em")
36 -- line breaking function is customizable
37 linebreaker.breaker = tex.linebreak -- linebreak function
38 linebreaker.max_cycles = 30 -- max # of attempts to find best solution
39 -- the number is totally arbitrary
40
41 linebreaker.boxsize = 65536 -- it is used in river detection. default box size is 1pt.
42 -- value is in scaled points
43 linebreaker.vertical_point = tex.baselineskip.width -- vertical matrix
44 linebreaker.previous_points = linebreaker.vertical_point / linebreaker.boxsize
45 -- number of
46 -- points which will be taken into account in
47 -- calculating river value. these points will
48 -- be processed in both directions
49 -- factor which will multiply the parindent value to get the minimal allowed width
50 -- of a last line in a paragraph
51 linebreaker.width_factor = 1.5
52 -- will be linebreaker active?
53 linebreaker.active = true
54
55 -- use cubic method for tolerance calculation
56 linebreaker.use_cubic = false
57 -- return array with default parameters
58 function linebreaker.parameters()
59 return {
60 pardir = tex.pardir
61 ,pretolerance = tex.pretolerance
62 ,tracingparagraphs=tex.tracingparagraphs
63 ,tolerance=tex.tolerance
64 ,looseness=tex.looseness
65 ,hyphenpenalty=tex.hyphenpenalty
66 ,exhyphenpenalty=tex.exhyphenpenalty
67 ,pdfadjustspacing=tex.pdfadjustspacing
68 ,adjdemerits=tex.adjdemerits
69 ,pdfprotrudechars=tex.pdfprotrudechars
70 ,linepenalty=tex.linepenalty
71 ,lastlinefit=tex.lastlinefit
72 ,doublehyphendemerits=tex.doublehyphendemerits
73 ,finalhyphendemerits=tex.finalhyphendemerits
74 ,hangafter=tex.hangafter
75 ,interlinepenalty=tex.interlinepenalty
76 ,clubpenalty=tex.clubpenalty
77 ,widowpenalty=tex.widowpenalty
78 ,brokenpenalty=tex.brokenpenalty
79 ,emergencystretch=tex.emergencystretch
80 ,hangindent=tex.hangindent
81 ,hsize=tex.hsize
82 ,leftskip=tex.leftskip
83 ,rightskip=tex.rightskip
84 ,parshape=tex.parshape
85 }
86 end
87
88 -- diagnostic function for traversing nodes returned by linebreaking
89 -- function. only top level nodes are processed, not sublists
90 function linebreaker.traverse(head)
91 --for n in node.traverse(node.tail(head).head) do
92 for n in node.traverse(head) do
93 linebreaker.debug_print(n.id, n.subtype)
94 if n.id == 10 then
95 local x = n.spec or {}
96 --x.shrink = 111222
97 linebreaker.debug_print("glue", x.shrink,x.stretch)
98 end
99 end
100 linebreaker.debug_print "****************"
101 return head
102 end
103
104
105 local utfchar = unicode.utf8.char
106
107 local getchar = function(n)
108 local t = {}
109 local xchar = font_identifiers[n.font].characters[n.char].unicode
110
111 if type(xchar) == "table" then
112 for k,v in pairs(xchar) do
113 t[#t+1] = utfchar(v)
114 end
115 else
116 -- 8-bit fonts don't contain the unicode value, so just return the char
117 -- value of node. In some cases it will be good, for math it will be mostly wrong
118 return utfchar(xchar or n.char)
119 end
120 return table.concat(t)
121 end
122
123 -- get text content of node list
124 local function get_text(line)
125 local t = {}
126 for n in node.traverse(line) do
127 if n.id == glue_id then t[#t+1] = " "
128 elseif n.id == glyph_id then t[#t+1] = getchar(n)
129 elseif n.id == hlist_id or n.id == vlist_id then t[#t+1] = get_text(n.head)
130 end
131 end
132 return table.concat(t)
133 end
134
135 -- find badness of a line
136 function linebreaker.par_badness(head)
137 local n = 0
138 for line in node.traverse_id(hlist_id, head) do
139 -- print(get_text(line.head), line.glue_order, line.glue_sign, line.glue_set)
140 -- glue_sign: > 0 = normal, 1 = stretch, 2 = shrink
141 -- we count only shrink, but stretch may result in overfull box as well
142 -- I just don't know, how to detect which value of glue_set means error
143 if line.glue_sign == 2 and line.glue_set >= 1 then n = n + 1 end
144 end;
145 return n
146 end
147
148 -- we have table with guessed param tables. we loop over them and find one with
149 -- lowest value of badness. this situation shouldn't happen, as at the moment
150 -- tolerance may be as high as 9999 and this should fix all overfulls
151 -- this code is remain of older method of guessing right value of tolerance
152 local function find_best(params)
153 local min = 10000 -- arbitrary high value
154 local n = params[1] or {}
155 for _, p in ipairs(params) do
156 local badness = p.badness or min
157 if badness <= min then
158 n = p
159 min = badness
160 end
161 end
162 linebreaker.debug_print "best solution"
163 local ignored_types = {userdata=true, table = true}
164 for k,v in pairs(n) do
165 -- we must ignore some properties in the params table,
166 -- as they produce errors when used in debug_print,
167 -- and they are not interesting for debugging anyway
168 if not ignored_types[type(v)] then
169 linebreaker.debug_print(k,v)
170 end
171 end
172 return n
173 end
174
175 -- all glue_spec nodes has .width key, but it is the same all the time. real
176 -- width depends on line shrink and stretch
177 -- this will be used in river detection
178 local function glue_calc(n, sign,set)
179 -- function for calculating glue width
180 local size
181 if sign ==2 then
182 size=n.spec.width - n.spec.shrink*set
183 else
184 size=n.spec.width + n.spec.stretch*set
185 end
186 return size
187 end
188
189
190 local function cube_root(num)
191 return num ^(1/3)
192 end
193
194
195 -- calculate new tolerance using method suggested by Jan Šustek
196 local function calc_tolerance_cubic(previous, step)
197 local previous = previous or tex.tolerance
198 local max_cycles = linebreaker.max_cycles
199 local max_tolerance = linebreaker.max_tolerance
200 local new = 100 * (cube_root(previous / 100) + (cube_root(max_tolerance/100) - cube_root(previous/100)) * (step/max_cycles))^3
201 -- local new = previous + (max_tolerance / max_cycles)-- + math.sqrt(previous * 4)
202 return (new < max_tolerance) and new or max_tolerance
203 end
204
205 -- max_tolerance / max_cycles is added to the current tolerance value
206 local function calc_tolerance(previous, step)
207 local previous = previous or tex.tolerance
208 local max_cycles = linebreaker.max_cycles
209 local max_tolerance = linebreaker.max_tolerance
210 local new = previous + (max_tolerance / max_cycles)-- + math.sqrt(previous * 4)
211 return (new < max_tolerance) and new or max_tolerance
212 end
213
214 -- river detection -- it doesn't work at the moment, maybe in the future?
215 -- idea is following:
216 -- 1. count widths of words and spaces
217 -- 2. divide widths to segments of some width (1pt?)
218 -- 3. assign number to segments: full glyph in the midle of a word:0
219 -- full glue: 1
220 -- edges of words: fraction depending on glyph dimensions
221 -- (it would be nice to incorporate glyph shapes, but it is
222 -- unrealistic, we don't have access)
223 -- 4. add numbers from previous line, probably sum of segments in some
224 -- distance (baselineskip / segments per sp = 45°?)
225 -- 5. sum segments for a glue / glue width = river ratio?
226 -- 6. find right threshold for telling which value of river ratio is a real
227 -- river
228 -- 7. calculate river ratio for whole paragraph (sum of over threshold
229 -- river ratios?)
230 -- I am not a mathematician, so I don't know whether this method is accurate,
231 -- correct, or efficient,
232 --
233 --
234 function linebreaker.detect_rivers(head)
235 local lines = {} --
236 local boxsize = linebreaker.boxsize
237 local vertical_point = linebreaker.vertical_point
238 local previous_points = math.ceil(linebreaker.previous_points)
239 -- calculate river for current node `n` and insert values to
240 local calc_river = function(line,n, lines)
241 -- get previous line
242 local previous = lines and lines[#lines] or {}
243 local get_point = function(i)
244 return previous[i] or 0
245 end
246 local x = #line
247 --print("soucasna delka line", x)
248 local sum = 0
249 for i = 1, #n do
250 local v = n[i] or 0
251 if v > 0 then
252 v = v + get_point(i)
253 -- ve add values from previous line
254 --for c = 1, previous_points do
255 local c = previous_points
256 v = v + (get_point(i+x+c)) + (get_point(i+x-c))
257 --print("adding",v)
258 --end
259 end
260 line[i+x] = v
261 sum = sum + v
262 --print("Calculate for", i,v)
263 --print("celkem v", i+x,v)
264 end
265 return line, sum / #n
266 end
267 for n in node.traverse_id(0, head) do
268 local line = {}
269 -- glue parameters
270 local set = n.glue_set
271 local sign = n.glue_sign
272 local order = n.glue_order
273 local first_node = n.head
274 local first_glyph = nil
275 local first = true
276 local word_count = 0
277 local last_glyph = nil
278 local last_glue = n.head
279 local position = 0
280 local remain = 0
281 local get_glyph_black = function(glyph)
282 -- only calculate blackness for glyphs
283 if glyph and glyph.id == glyph_id then
284 local w,h,d = node.dimensions(glyph, glyph.next)
285 -- 1 is maximal white
286 local blackness = 1 - ((h+d) / vertical_point)
287 -- print(char(glyph.char), blackness) return w / boxsize or 0, blackness
288 end
289 return 0,0
290 end
291 -- get width of nodes
292 local get_width = function(start,fin)
293 local w = node.dimensions(set,sign,order,start, fin)
294 return w / boxsize -- get width in pt
295 end
296 local add_word = function(start,fin)
297 word_count = word_count + 1
298 local t = {}
299 local width = get_width(start,fin)
300 -- first and last glyph are taken into account for blackness calculation
301 local w1, f = get_glyph_black(first_glyph)
302 local w2, l = get_glyph_black(last_glyph)
303 w1 = math.ceil(w1 + remain)
304 w2 = math.ceil(w2)
305 if word_count <= 1 then
306 w1 = 0
307 end
308 width = width + remain
309 remain = width - math.floor(width)
310 width = width - remain
311 for i=1, w1 do
312 t[#t+1] = f/i -- add more black at the end of glyph
313 end
314 -- middle of the word
315 for i=1, (width-w1-w2) do
316 t[#t+1] = 0
317 end
318 -- last glyph
319 for i=1, w2 do
320 t[#t+1] = l/(w2-i+1)
321 end
322 line = calc_river(line, t, lines)
323 --print("black", f,l)
324 end
325 add_glue = function(x)
326 local t = {}
327 local r
328 local width = get_width(x,x.next) + remain
329 remain = width - math.floor(width)
330 width = width - remain
331 for i=1, width do
332 t[#t+1] = 1
333 end
334 --print("glue",#t)
335 line, r = calc_river(line,t, lines)
336 if r > 1 then
337 local w = node.new("whatsit","pdf_literal")
338 local color = 1 / r
339 w.data = string.format("q 1 %f 1 rg 0 0 m 0 5 l 5 5 l 5 0 l f Q", color)
340 -- print("color",w.data)
341 node.insert_before(n.head,x,w)
342 end
343 return r
344 end
345 for x in node.traverse(n.head) do
346 if x.id == glue_id and x.subtype == 0 then
347 --print("glue width", get_width(x,x.next))
348 add_word(last_glue, x, first_glyph,last_glyph)
349 local river_value = add_glue(x)
350 -- print("riverness", river_value)
351 first = true
352 last_glue = x.next -- calculate width of next word from here
353 elseif x.id == glyph_id then
354 if first then
355 first_glyph = x
356 end
357 first = false
358 last_glyph = x
359 end
360 end
361 add_word(last_glue, x, first_glyph, last_glyph)
362 --table.insert(lines, calc_river(t,lines))
363 --for k,v in pairs(line) do print(k,v) end
364 table.insert(lines,line)
365 -- print(table.concat(lines[#lines],","))
366 -- local width, h, d = node.dimensions(set, sign, order, n.head, node.tail(n.head))
367 -- print(width,table.concat(t))
368 end
369 return 0
370 end
371
372 -- End of river detection
373
374
375 function linebreaker.last_line_width(head)
376 -- measure length of the last line in a paragraph
377 local w, w1
378 local last = node.tail(head)
379 local n = node.copy(last)
380 -- last node is not node list, return negative number
381 if not n.head then return -1 end
382 n.head = node.remove(n.head, node.tail(n.head))
383 for x in node.traverse(n.head) do
384 if x.id == glue_id then
385 if x.subtype == 15 then
386 n.head = node.remove(n.head, x)
387 end
388 end
389 end
390 -- something went wrong, so discard this solution
391 if not n.head or not n.glue_set then return 0 end
392 w, _, _ = node.dimensions(n.glue_set, n.glue_sign, n.glue_order, n.head)
393 w1, _, _ = node.dimensions(n.glue_set, n.glue_sign, n.glue_order, n)
394 return w
395 end
396
397
398 -- try to linebreak current paragraph with increasing tolerance and
399 -- emergencystretch
400 function linebreaker.best_solution(par, parameters, step)
401 -- step is used in the tolerance calculation
402 local step = (step or 0) + 1
403 -- save current node list, because call to the linebreaker modifies it
404 -- and we wouldn't be able to run it multiple times
405 local head = node.copy_list(par)
406 -- this shouldn't happen
407 if #parameters > linebreaker.max_cycles then
408 -- we couldn't find a solution without badness
409 -- break paragraph with the least bad parameters
410 return linebreaker.breaker(head,find_best(parameters))
411 end
412 local params = parameters[#parameters] -- newest parameters are last in the
413 -- table that will be used in recursive invocations of this function
414 -- it holds updated parameters
415 local newparams = linebreaker.parameters()
416 -- this value is set by hpack_quality callback that is executed by
417 -- tex.linebreak when overflow or underflow happens
418 linebreaker.badness = 0
419 -- break paragraph
420 local newhead, info = linebreaker.breaker(head, params)
421 -- calc badness -- we don't use this anymore, badness of the currently
422 -- processed node list is set by hpack_filter
423 local badness = linebreaker.badness or 0
424 -- don't allow lines shorter than the paragraph indent
425 local last_line_width = linebreaker.last_line_width(newhead)
426 linebreaker.debug_print("last line width", last_line_width, "parindent:", tex.parindent * linebreaker.width_factor)
427 if last_line_width > 0 and last_line_width < tex.parindent * linebreaker.width_factor then
428 linebreaker.debug_print "too short last line"
429 badness = 10000
430 end
431
432 params.badness = badness
433 if badness > 0 then
434 -- calc new value of tolerance
435 local tolerance
436 if linebreaker.use_cubic then
437 tolerance = calc_tolerance_cubic(params.tolerance, step) -- or 10000
438 else
439 tolerance = calc_tolerance(params.tolerance, step) -- or 10000
440 end
441 -- save tolerance to newparams so this value will be used in next run
442 newparams.tolerance = math.floor(tolerance)
443 newparams.emergencystretch = (params.emergencystretch or 0) + linebreaker.max_emergencystretch / linebreaker.max_cycles
444 table.insert(parameters, newparams)
445 -- run linebreaker again
446 return linebreaker.best_solution(par, parameters)
447 end
448 -- river detection doesn't work, so we don't execute ths code anymore
449 -- detect rivers only for paragraphs without overflow boxes
450 -- local rivers = linebreaker.detect_rivers(newhead)
451 -- print("rivers", rivers)
452 -- print "normal return"
453 --]]
454 return newhead, info
455 end
456
457 -- this is just reporting function which print lines with glue widths.
458 -- this may be useful in river detection
459 local function glue_width(head)
460 for n in node.traverse_id(hlist_id, head) do
461 local t = {}
462 local set = n.glue_set
463 local sign = n.glue_sign
464 local order = n.glue_order
465 for x in node.traverse(n.head) do
466 if x.id == glue_id then
467 local g = x.spec
468 local size = glue_calc(x, sign, set)
469 t[#t+1] = ":"..size.."."
470 elseif x.id == glyph_id then
471 t[#t+1] = getchar(x)
472 end
473 end
474 local width, h, d = node.dimensions(set, sign, order, n.head, node.tail(n.head))
475 end
476 end
477
478 local function fix_nest(info)
479 tex.nest[tex.nest.ptr].prevdepth=info.prevdepth
480 tex.nest[tex.nest.ptr].prevgraf=info.prevgraf
481 end
482
483
484 -- test whether the current overfull box message occurs inside our linebreaker function
485 local is_inside_linebreaker = false
486 function linebreaker.linebreak(head,is_display)
487 local parameters = linebreaker.parameters()
488 -- we can disable linebreaker processing
489 if linebreaker.active == false then
490 local newhead, info = linebreaker.breaker(head, parameters)
491 fix_nest(info)
492 return newhead
493 end
494 is_inside_linebreaker = true
495 local newhead, info = linebreaker.best_solution(head, {parameters})
496 is_inside_linebreaker = false
497 fix_nest(info)
498 return newhead
499 end
500
501 function linebreaker.hpack_quality(incl, detail, head, first, last)
502 if not is_inside_linebreaker then
503 local detail_msg = incl=="overfull" and "overflow" or "badness"
504 linebreaker.debug_print( incl .. " box at lines: " .. first .." -- " .. last ..". " .. detail_msg .. ": " .. detail .."\n text:" .. get_text(head) )
505 end
506 linebreaker.badness = (linebreaker.badness or 0) + detail
507 end
508
509 -- It seems necessary to call the post_linebreak filter in order to support floats
510 -- Even if it does nothing but to return the node list. I don't understand why...
511 function linebreaker.post_linebreak(head)
512 return true
513 end
514
515 linebreaker.get_text = get_text
516
517 return linebreaker
518