Debian Codegraph @

texk/web2c/luatexdir/tex/linebreak.c

raw
1 /*
2
3 Copyright 2006-2008 Taco Hoekwater <[email protected]>
4
5 This file is part of LuaTeX.
6
7 LuaTeX is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2 of the License, or (at your
10 option) any later version.
11
12 LuaTeX is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 License for more details.
16
17 You should have received a copy of the GNU General Public License along
18 with LuaTeX; if not, see <http://www.gnu.org/licenses/>.
19
20 */
21
22 #include "ptexlib.h"
23
24 /*tex
25
26 We come now to what is probably the most interesting algorithm of \TeX: the
27 mechanism for choosing the ``best possible'' breakpoints that yield the
28 individual lines of a paragraph. \TeX's line-breaking algorithm takes a given
29 horizontal list and converts it to a sequence of boxes that are appended to
30 the current vertical list. In the course of doing this, it creates a special
31 data structure containing three kinds of records that are not used elsewhere
32 in \TeX. Such nodes are created while a paragraph is being processed, and
33 they are destroyed afterwards; thus, the other parts of \TeX\ do not need to
34 know anything about how line-breaking is done.
35
36 The method used here is based on an approach devised by Michael F. Plass and
37 the author in 1977, subsequently generalized and improved by the same two
38 people in 1980. A detailed discussion appears in {\sl SOFTWARE---Practice
39 \AM\ Experience \bf11} (1981), 1119--1184, where it is shown that the
40 line-breaking problem can be regarded as a special case of the problem of
41 computing the shortest path in an acyclic network. The cited paper includes
42 numerous examples and describes the history of line breaking as it has been
43 practiced by printers through the ages. The present implementation adds two
44 new ideas to the algorithm of 1980: Memory space requirements are
45 considerably reduced by using smaller records for inactive nodes than for
46 active ones, and arithmetic overflow is avoided by using ``delta distances''
47 instead of keeping track of the total distance from the beginning of the
48 paragraph to the current point.
49
50 The |line_break| procedure should be invoked only in horizontal mode; it
51 leaves that mode and places its output into the current vlist of the
52 enclosing vertical mode (or internal vertical mode). There is one explicit
53 parameter: |d| is true for partial paragraphs preceding display math mode; in
54 this case the amount of additional penalty inserted before the final line is
55 |display_widow_penalty| instead of |widow_penalty|.
56
57 There are also a number of implicit parameters: The hlist to be broken starts
58 at |vlink(head)|, and it is nonempty. The value of |prev_graf| in the
59 enclosing semantic level tells where the paragraph should begin in the
60 sequence of line numbers, in case hanging indentation or \.{\\parshape} are
61 in use; |prev_graf| is zero unless this paragraph is being continued after a
62 displayed formula. Other implicit parameters, such as the |par_shape_ptr| and
63 various penalties to use for hyphenation, etc., appear in |eqtb|.
64
65 After |line_break| has acted, it will have updated the current vlist and the
66 value of |prev_graf|. Furthermore, the global variable |just_box| will point
67 to the final box created by |line_break|, so that the width of this line can
68 be ascertained when it is necessary to decide whether to use
69 |above_display_skip| or |above_display_short_skip| before a displayed
70 formula.
71
72 */
73
74 /*tex The |hlist_node| for the last line of the new paragraph: */
75
76 halfword just_box;
77
78 /*tex
79
80 In it's complete form, |line_break| is a rather lengthy procedure---sort of a
81 small world unto itself---we must build it up little by little. Below you see
82 only the general outline.
83
84 The main task performed here is to move the list from |head| to |temp_head|
85 and go into the enclosing semantic level. We also append the
86 \.{\\parfillskip} glue to the end of the paragraph, removing a space (or
87 other glue node) if it was there, since spaces usually precede blank lines
88 and instances of `\.{\$\$}'. The |par_fill_skip| is preceded by an infinite
89 penalty, so it will never be considered as a potential breakpoint.
90
91 That code assumes that a |glue_node| and a |penalty_node| occupy the same
92 number of |mem|~words.
93
94 Most other processing is delegated to external functions.
95
96 */
97
98 void line_break(boolean d, int line_break_context)
99 {
100 /*tex Main direction of paragraph: */
101 int paragraph_dir = 0;
102 halfword final_par_glue;
103 halfword start_of_par;
104 int callback_id;
105 /*tex this is for over/underfull box messages */
106 pack_begin_line = cur_list.ml_field;
107 alink(temp_head) = null;
108 vlink(temp_head) = vlink(cur_list.head_field);
109 new_hyphenation(temp_head, cur_list.tail_field);
110 cur_list.tail_field = new_ligkern(temp_head, cur_list.tail_field);
111 if (is_char_node(cur_list.tail_field)) {
112 tail_append(new_penalty(inf_penalty,line_penalty));
113 } else if (type(cur_list.tail_field) != glue_node) {
114 tail_append(new_penalty(inf_penalty,line_penalty));
115 } else {
116 halfword t = alink(cur_list.tail_field);
117 flush_node(cur_list.tail_field);
118 cur_list.tail_field = t;
119 tail_append(new_penalty(inf_penalty,line_penalty));
120 }
121 final_par_glue = new_param_glue(par_fill_skip_code);
122 couple_nodes(cur_list.tail_field, final_par_glue);
123 cur_list.tail_field = vlink(cur_list.tail_field);
124 lua_node_filter(pre_linebreak_filter_callback, line_break_context, temp_head, addressof(cur_list.tail_field));
125 last_line_fill = cur_list.tail_field;
126 pop_nest();
127 start_of_par = cur_list.tail_field;
128 callback_id = callback_defined(linebreak_filter_callback);
129 if (callback_id > 0) {
130 callback_id = lua_linebreak_callback(d, temp_head, addressof(cur_list.tail_field));
131 if (callback_id > 0) {
132 /*tex find the correct value for the |just_box| */
133 halfword box_search = cur_list.tail_field;
134 just_box = null;
135 if (box_search != null) {
136 do {
137 if (type(box_search) == hlist_node) {
138 just_box = box_search;
139 }
140 box_search = vlink(box_search);
141 } while (box_search != null);
142 }
143 if (just_box == null) {
144 help3(
145 "A linebreaking routine should return a non-empty list of nodes",
146 "and at least one of those has to be a \\hbox.",
147 "Sorry, I cannot recover from this."
148 );
149 print_err("Invalid linebreak_filter");
150 succumb();
151 }
152 } else {
153 if (tracing_paragraphs_par > 0) {
154 begin_diagnostic();
155 print_int(line);
156 end_diagnostic(true);
157 }
158 }
159 }
160 if (callback_id == 0) {
161 if ((!is_char_node(vlink(temp_head))) && ((type(vlink(temp_head)) == local_par_node))) {
162 paragraph_dir = local_par_dir(vlink(temp_head));
163 } else {
164 confusion("weird par dir");
165 }
166 ext_do_line_break(
167 paragraph_dir,
168 pretolerance_par,
169 tracing_paragraphs_par,
170 tolerance_par,
171 emergency_stretch_par,
172 looseness_par,
173 adjust_spacing_par,
174 par_shape_par_ptr,
175 adj_demerits_par,
176 protrude_chars_par,
177 line_penalty_par,
178 last_line_fit_par,
179 double_hyphen_demerits_par,
180 final_hyphen_demerits_par,
181 hang_indent_par,
182 hsize_par,
183 hang_after_par,
184 left_skip_par,
185 right_skip_par,
186 inter_line_penalties_par_ptr,
187 inter_line_penalty_par,
188 club_penalty_par,
189 club_penalties_par_ptr,
190 (d ? display_widow_penalties_par_ptr : widow_penalties_par_ptr),
191 (d ? display_widow_penalty_par : widow_penalty_par),
192 broken_penalty_par,
193 final_par_glue
194 );
195 }
196 lua_node_filter(post_linebreak_filter_callback, line_break_context, start_of_par, addressof(cur_list.tail_field));
197 pack_begin_line = 0;
198 }
199
200 /*tex
201
202 Glue nodes in a horizontal list that is being paragraphed are not supposed to
203 include ``infinite'' shrinkability; that is why the algorithm maintains four
204 registers for stretching but only one for shrinking. If the user tries to
205 introduce infinite shrinkability, the shrinkability will be reset to finite
206 and an error message will be issued. A boolean variable |no_shrink_error_yet|
207 prevents this error message from appearing more than once per paragraph.
208
209 */
210
211 #define check_shrinkage(a) \
212 if ((shrink_order((a))!=normal)&&(shrink((a))!=0)) \
213 a=finite_shrink((a))
214
215 /*tex Have we complained about infinite shrinkage? */
216
217 static boolean no_shrink_error_yet;
218
219 /*tex Recovers from infinite shrinkage. */
220
221 static halfword finite_shrink(halfword p)
222 {
223 const char *hlp[] = {
224 "The paragraph just ended includes some glue that has",
225 "infinite shrinkability, e.g., `\\hskip 0pt minus 1fil'.",
226 "Such glue doesn't belong there---it allows a paragraph",
227 "of any length to fit on one line. But it's safe to proceed,",
228 "since the offensive shrinkability has been made finite.",
229 NULL
230 };
231 if (no_shrink_error_yet) {
232 no_shrink_error_yet = false;
233 tex_error("Infinite glue shrinkage found in a paragraph", hlp);
234 }
235 shrink_order(p) = normal;
236 return p;
237 }
238
239 /*tex
240
241 A pointer variable |cur_p| runs through the given horizontal list as we look
242 for breakpoints. This variable is global, since it is used both by
243 |line_break| and by its subprocedure |try_break|.
244
245 Another global variable called |threshold| is used to determine the
246 feasibility of individual lines: breakpoints are feasible if there is a way
247 to reach them without creating lines whose badness exceeds |threshold|. (The
248 badness is compared to |threshold| before penalties are added, so that
249 penalty values do not affect the feasibility of breakpoints, except that no
250 break is allowed when the penalty is 10000 or more.) If |threshold| is 10000
251 or more, all legal breaks are considered feasible, since the |badness|
252 function specified above never returns a value greater than~10000.
253
254 Up to three passes might be made through the paragraph in an attempt to find
255 at least one set of feasible breakpoints. On the first pass, we have
256 |threshold=pretolerance| and |second_pass=final_pass=false|. If this pass
257 fails to find a feasible solution, |threshold| is set to |tolerance|,
258 |second_pass| is set |true|, and an attempt is made to hyphenate as many
259 words as possible. If that fails too, we add |emergency_stretch| to the
260 background stretchability and set |final_pass=true|.
261
262 */
263
264 /*tex is this our second attempt to break this paragraph? */
265
266 static boolean second_pass;
267
268 /*tex is this our final attempt to break this paragraph? */
269
270 static boolean final_pass;
271
272 /*tex maximum badness on feasible lines */
273
274 static int threshold;
275
276 /*tex
277
278 The maximum fill level for |hlist_stack|. Maybe good if larger than |2 *
279 max_quarterword|, so that box nesting level would overflow first.
280
281 */
282
283 #define max_hlist_stack 512
284
285 /*tex stack for |find_protchar_left()| and |find_protchar_right()| */
286
287 static halfword hlist_stack[max_hlist_stack];
288
289 /*tex fill level for |hlist_stack| */
290
291 static short hlist_stack_level = 0;
292
293 static void push_node(halfword p)
294 {
295 if (hlist_stack_level >= max_hlist_stack)
296 normal_error("push_node","stack overflow");
297 hlist_stack[hlist_stack_level++] = p;
298 }
299
300 static halfword pop_node(void)
301 {
302 if (hlist_stack_level <= 0) {
303 /*tex This can point to some bug. */
304 normal_error("pop_node","stack underflow (internal error)");
305 }
306 return hlist_stack[--hlist_stack_level];
307 }
308
309 /*tex maximal stretch ratio of expanded fonts */
310
311 static int max_stretch_ratio = 0;
312
313 /*tex maximal shrink ratio of expanded fonts */
314
315 static int max_shrink_ratio = 0;
316
317 /*tex the current step of expanded fonts */
318
319 static int cur_font_step = 0;
320
321 static boolean check_expand_pars(internal_font_number f)
322 {
323 int m;
324 if ((font_step(f) == 0) || ((font_max_stretch(f) == 0) && (font_max_shrink(f) == 0)))
325 return false;
326 if (cur_font_step < 0)
327 cur_font_step = font_step(f);
328 else if (cur_font_step != font_step(f))
329 normal_error("font expansion","using fonts with different step of expansion in one paragraph is not allowed");
330 m = font_max_stretch(f);
331 if (m != 0) {
332 if (max_stretch_ratio < 0)
333 max_stretch_ratio = m;
334 else if (max_stretch_ratio != m)
335 normal_error("font expansion","using fonts with different limit of expansion in one paragraph is not allowed");
336 }
337 m = font_max_shrink(f);
338 if (m != 0) {
339 if (max_shrink_ratio < 0)
340 max_shrink_ratio = -m;
341 else if (max_shrink_ratio != -m)
342 normal_error("font expansion","using fonts with different limit of expansion in one paragraph is not allowed");
343 }
344 return true;
345 }
346
347 /*tex Search left to right from list head |l|, returns 1st non-skipable item */
348
349 halfword find_protchar_left(halfword l, boolean d)
350 {
351 halfword t;
352 boolean run;
353 boolean done = false ;
354 while ((vlink(l) != null) && (type(l) == hlist_node) && zero_dimensions(l) && (list_ptr(l) == null)) {
355 /*tex For paragraph start with \.{\\parindent} = 0pt or any empty hbox. */
356 l = vlink(l);
357 done = true ;
358 }
359 if ((!done) && (type(l) == local_par_node)) {
360 l = vlink(l);
361 done = true ;
362 }
363 if ((!done) && d) {
364 while ((vlink(l) != null) && (!(is_char_node(l) || non_discardable(l)))) {
365 /*tex standard discardables at line break, \TeX book, p 95 */
366 l = vlink(l);
367 }
368 }
369 if (type(l) != glyph_node) {
370 hlist_stack_level = 0;
371 run = true;
372 do {
373 t = l;
374 while (run && (type(l) == hlist_node) && (list_ptr(l) != null)) {
375 push_node(l);
376 l = list_ptr(l);
377 }
378 while (run && cp_skipable(l)) {
379 while ((vlink(l) == null) && (hlist_stack_level > 0)) {
380 /*tex Don't visit this node again. */
381 l = pop_node();
382 run = false;
383 }
384 if ((vlink(l) != null) && (type(l) == boundary_node) && (subtype(l) == protrusion_boundary) &&
385 ((boundary_value(l) == 1) || (boundary_value(l) == 3))) {
386 /*tex Skip next node. */
387 l = vlink(l);
388 }
389 if (vlink(l) != null) {
390 l = vlink(l);
391 } else if (hlist_stack_level == 0) {
392 run = false;
393 }
394 }
395 } while (t != l);
396 }
397 return l;
398 }
399
400 /*tex
401
402 Search right to left from list tail |r| to head |l|, returns 1st non-skipable
403 item.
404
405 */
406
407 halfword find_protchar_right(halfword l, halfword r)
408 {
409 halfword t;
410 boolean run = true;
411 if (r == null)
412 return null;
413 hlist_stack_level = 0;
414 do {
415 t = r;
416 while (run && (type(r) == hlist_node) && (list_ptr(r) != null)) {
417 push_node(l);
418 push_node(r);
419 l = list_ptr(r);
420 r = l;
421 while (vlink(r) != null) {
422 halfword s = r;
423 r = vlink(r);
424 alink(r) = s;
425 }
426 }
427 while (run && cp_skipable(r)) {
428 while ((r == l) && (hlist_stack_level > 0)) {
429 /*tex Don't visit this node again. */
430 r = pop_node();
431 l = pop_node();
432 }
433 if ((r != l) && (r != null)) {
434 if ((alink(r) != null) && (type(r) == boundary_node) && (subtype(r) == protrusion_boundary) &&
435 ((boundary_value(r) == 2) || (boundary_value(r) == 3))) {
436 /*tex Skip next node. */
437 r = alink(r);
438 }
439 if (alink(r) != null) {
440 r = alink(r);
441 } else {
442 /*tex This is the input: \.{\\leavevmode\\penalty-10000\\penalty-10000} (bug \#268). */
443 run = false;
444 }
445 } else if ((r == l) && (hlist_stack_level == 0))
446 run = false;
447 }
448 } while (t != r);
449 return r;
450 }
451
452 #define left_pw(a) char_pw((a), left_side)
453 #define right_pw(a) char_pw((a), right_side)
454
455 /*tex
456
457 When looking for optimal line breaks, \TeX\ creates a ``break node'' for each
458 break that is {\sl feasible}, in the sense that there is a way to end a line
459 at the given place without requiring any line to stretch more than a given
460 tolerance. A break node is characterized by three things: the position of the
461 break (which is a pointer to a |glue_node|, |math_node|, |penalty_node|, or
462 |disc_node|); the ordinal number of the line that will follow this
463 breakpoint; and the fitness classification of the line that has just ended,
464 i.e., |tight_fit|, |decent_fit|, |loose_fit|, or |very_loose_fit|.
465
466 */
467
468 typedef enum {
469 /*tex fitness classification for lines stretching more than their stretchability */
470 very_loose_fit = 0,
471 /*tex fitness classification for lines stretching 0.5 to 1.0 of their stretchability */
472 loose_fit,
473 /*tex fitness classification for all other lines */
474 decent_fit,
475 /*tex fitness classification for lines shrinking 0.5 to 1.0 of their shrinkability */
476 tight_fit
477 } fitness_value;
478
479 /*tex
480
481 The algorithm essentially determines the best possible way to achieve each
482 feasible combination of position, line, and fitness. Thus, it answers
483 questions like, ``What is the best way to break the opening part of the
484 paragraph so that the fourth line is a tight line ending at such-and-such a
485 place?'' However, the fact that all lines are to be the same length after a
486 certain point makes it possible to regard all sufficiently large line numbers
487 as equivalent, when the looseness parameter is zero, and this makes it
488 possible for the algorithm to save space and time.
489
490 An ``active node'' and a ``passive node'' are created in |mem| for each
491 feasible breakpoint that needs to be considered. Active nodes are three words
492 long and passive nodes are two words long. We need active nodes only for
493 breakpoints near the place in the paragraph that is currently being examined,
494 so they are recycled within a comparatively short time after they are
495 created.
496
497 An active node for a given breakpoint contains six fields:
498
499 \startitemize[n]
500
501 \startitem
502 |vlink| points to the next node in the list of active nodes; the last
503 active node has |vlink=active|.
504 \stopitem
505
506 \startitem
507 |break_node| points to the passive node associated with this
508 breakpoint.
509 \stopitem
510
511 \startitem
512 |line_number| is the number of the line that follows this breakpoint.
513 \stopitem
514
515 \startitem
516 |fitness| is the fitness classification of the line ending at this
517 breakpoint.
518 \stopitem
519
520 \startitem
521 |type| is either |hyphenated_node| or |unhyphenated_node|, depending
522 on whether this breakpoint is a |disc_node|.
523 \stopitem
524
525 \startitem
526 |total_demerits| is the minimum possible sum of demerits over all
527 lines leading from the beginning of the paragraph to this breakpoint.
528 \stopitem
529
530 \stopitemize
531
532 The value of |vlink(active)| points to the first active node on a vlinked
533 list of all currently active nodes. This list is in order by |line_number|,
534 except that nodes with |line_number>easy_line| may be in any order relative
535 to each other.
536
537 */
538
539 void initialize_active(void)
540 {
541 type(active) = hyphenated_node;
542 line_number(active) = max_halfword;
543 /*tex The |subtype| is never examined. */
544 subtype(active) = 0;
545 }
546
547 /*tex
548
549 The passive node for a given breakpoint contains eight fields:
550
551 \startitemize
552
553 \startitem
554 |vlink| points to the passive node created just before this one, if
555 any, otherwise it is |null|.
556 \stopitem
557
558 \startitem
559 |cur_break| points to the position of this breakpoint in the
560 horizontal list for the paragraph being broken.
561 \stopitem
562
563 \startitem
564 |prev_break| points to the passive node that should precede this one
565 in an optimal path to this breakpoint.
566 \stopitem
567
568 \startitem
569 |serial| is equal to |n| if this passive node is the |n|th one
570 created during the current pass. (This field is used only when
571 printing out detailed statistics about the line-breaking
572 calculations.)
573 \stopitem
574
575 \startitem
576 |passive_pen_inter| holds the current \.{\\localinterlinepenalty}
577 \stopitem
578
579 \startitem
580 |passive_pen_broken| holds the current \.{\\localbrokenpenalty}
581 \stopitem
582
583 \stopitemize
584
585 There is a global variable called |passive| that points to the most recently
586 created passive node. Another global variable, |printed_node|, is used to
587 help print out the paragraph when detailed information about the
588 line-breaking computation is being displayed.
589
590 */
591
592 /*tex most recent node on passive list */
593
594 static halfword passive;
595
596 /*tex most recent node that has been printed */
597
598 static halfword printed_node;
599
600 /*tex the number of passive nodes allocated on this pass */
601
602 static halfword pass_number;
603
604 /*tex
605
606 The active list also contains ``delta'' nodes that help the algorithm compute
607 the badness of individual lines. Such nodes appear only between two active
608 nodes, and they have |type=delta_node|. If |p| and |r| are active nodes and
609 if |q| is a delta node between them, so that |vlink(p)=q| and |vlink(q)=r|,
610 then |q| tells the space difference between lines in the horizontal list that
611 start after breakpoint |p| and lines that start after breakpoint |r|. In
612 other words, if we know the length of the line that starts after |p| and ends
613 at our current position, then the corresponding length of the line that
614 starts after |r| is obtained by adding the amounts in node~|q|. A delta node
615 contains seven scaled numbers, since it must record the net change in glue
616 stretchability with respect to all orders of infinity. The natural width
617 difference appears in |mem[q+1].sc|; the stretch differences in units of pt,
618 sfi, fil, fill, and filll appear in |mem[q+2..q+6].sc|; and the shrink
619 difference appears in |mem[q+7].sc|. The |subtype| field of a delta node is
620 not used.
621
622 Actually, we have two more fields that are used by |pdftex|.
623
624 As the algorithm runs, it maintains a set of seven delta-like registers for
625 the length of the line following the first active breakpoint to the current
626 position in the given hlist. When it makes a pass through the active list, it
627 also maintains a similar set of seven registers for the length following the
628 active breakpoint of current interest. A third set holds the length of an
629 empty line (namely, the sum of \.{\\leftskip} and \.{\\rightskip}); and a
630 fourth set is used to create new delta nodes.
631
632 When we pass a delta node we want to do operations like:
633
634 \starttyping
635 for k := 1 to 7 do
636 cur_active_width[k] := cur_active_width[k] + mem[q+k].sc|};
637 \stoptyping
638
639 and we want to do this without the overhead of |for| loops. The |do_all_six|
640 macro makes such six-tuples convenient.
641
642 */
643
644 /*tex distance from first active node to~|cur_p| */
645
646 static scaled active_width[10] = { 0 };
647
648 /*tex length of an ``empty'' line */
649
650 static scaled background[10] = { 0 };
651
652 /*tex length being computed after current break */
653
654 static scaled break_width[10] = { 0 };
655
656 /*tex Make |auto_breaking| accessible out of |line_break|: */
657
658 static boolean auto_breaking;
659
660 /*tex
661
662 Let's state the principles of the delta nodes more precisely and concisely,
663 so that the following programs will be less obscure. For each legal
664 breakpoint~|p| in the paragraph, we define two quantities $\alpha(p)$ and
665 $\beta(p)$ such that the length of material in a line from breakpoint~|p| to
666 breakpoint~|q| is $\gamma+\beta(q)-\alpha(p)$, for some fixed $\gamma$.
667 Intuitively, $\alpha(p)$ and $\beta(q)$ are the total length of material from
668 the beginning of the paragraph to a point ``after'' a break at |p| and to a
669 point ``before'' a break at |q|; and $\gamma$ is the width of an empty line,
670 namely the length contributed by \.{\\leftskip} and \.{\\rightskip}.
671
672 Suppose, for example, that the paragraph consists entirely of alternating
673 boxes and glue skips; let the boxes have widths $x_1\ldots x_n$ and let the
674 skips have widths $y_1\ldots y_n$, so that the paragraph can be represented
675 by $x_1y_1\ldots x_ny_n$. Let $p_i$ be the legal breakpoint at $y_i$; then
676 $\alpha(p_i)=x_1+y_1+\cdots+x_i+y_i$, and $\beta(p_i)= x_1+y_1+\cdots+x_i$.
677 To check this, note that the length of material from $p_2$ to $p_5$, say, is
678 $\gamma+x_3+y_3+x_4+y_4+x_5=\gamma+\beta(p_5) -\alpha(p_2)$.
679
680 The quantities $\alpha$, $\beta$, $\gamma$ involve glue stretchability and
681 shrinkability as well as a natural width. If we were to compute $\alpha(p)$
682 and $\beta(p)$ for each |p|, we would need multiple precision arithmetic, and
683 the multiprecise numbers would have to be kept in the active nodes. \TeX\
684 avoids this problem by working entirely with relative differences or
685 ``deltas.'' Suppose, for example, that the active list contains
686 $a_1\,\delta_1\,a_2\,\delta_2\,a_3$, where the |a|'s are active breakpoints
687 and the $\delta$'s are delta nodes. Then $\delta_1=\alpha(a_1)-\alpha(a_2)$
688 and $\delta_2=\alpha(a_2)-\alpha(a_3)$. If the line breaking algorithm is
689 currently positioned at some other breakpoint |p|, the |active_width| array
690 contains the value $\gamma+\beta(p)-\alpha(a_1)$. If we are scanning through
691 the list of active nodes and considering a tentative line that runs from
692 $a_2$ to~|p|, say, the |cur_active_width| array will contain the value
693 $\gamma+\beta(p)-\alpha(a_2)$. Thus, when we move from $a_2$ to $a_3$, we
694 want to add $\alpha(a_2)-\alpha(a_3)$ to |cur_active_width|; and this is just
695 $\delta_2$, which appears in the active list between $a_2$ and $a_3$. The
696 |background| array contains $\gamma$. The |break_width| array will be used to
697 calculate values of new delta nodes when the active list is being updated.
698
699 The heart of the line-breaking procedure is `|try_break|', a subroutine that
700 tests if the current breakpoint |cur_p| is feasible, by running through the
701 active list to see what lines of text can be made from active nodes
702 to~|cur_p|. If feasible breaks are possible, new break nodes are created. If
703 |cur_p| is too far from an active node, that node is deactivated.
704
705 The parameter |pi| to |try_break| is the penalty associated with a break at
706 |cur_p|; we have |pi=eject_penalty| if the break is forced, and
707 |pi=inf_penalty| if the break is illegal.
708
709 The other parameter, |break_type|, is set to |hyphenated_node| or
710 |unhyphenated_node|, depending on whether or not the current break is at a
711 |disc_node|. The end of a paragraph is also regarded as `|hyphenated_node|';
712 this case is distinguishable by the condition |cur_p=null|.
713
714 */
715
716 /*tex running \.{\\localinterlinepenalty} */
717
718 static int internal_pen_inter;
719
720 /*tex running \.{\\localbrokenpenalty} */
721
722 static int internal_pen_broken;
723
724 /*tex running \.{\\localleftbox} */
725
726 static halfword internal_left_box;
727
728 /*tex running \.{\\localleftbox} width */
729
730 static int internal_left_box_width;
731
732 /*tex running \.{\\localleftbox} */
733
734 static halfword init_internal_left_box;
735
736 /*tex running \.{\\localleftbox} width */
737
738 static int init_internal_left_box_width;
739
740 /*tex running \.{\\localrightbox} */
741
742 static halfword internal_right_box;
743
744 /*tex running \.{\\localrightbox} width */
745
746 static int internal_right_box_width;
747
748 /*tex the length of discretionary material preceding a break */
749
750 static scaled disc_width[10] = { 0 };
751
752 /*tex
753
754 As we consider various ways to end a line at |cur_p|, in a given line number
755 class, we keep track of the best total demerits known, in an array with one
756 entry for each of the fitness classifications. For example,
757 |minimal_demerits[tight_fit]| contains the fewest total demerits of feasible
758 line breaks ending at |cur_p| with a |tight_fit| line;
759 |best_place[tight_fit]| points to the passive node for the break
760 before~|cur_p| that achieves such an optimum; and |best_pl_line[tight_fit]|
761 is the |line_number| field in the active node corresponding to
762 |best_place[tight_fit]|. When no feasible break sequence is known, the
763 |minimal_demerits| entries will be equal to |awful_bad|, which is $2^{30}-1$.
764 Another variable, |minimum_demerits|, keeps track of the smallest value in
765 the |minimal_demerits| array.
766
767 */
768
769 /*tex best total demerits known for current line class and position, given the fitness */
770
771 static int minimal_demerits[4];
772
773 /*tex best total demerits known for current line class and position */
774
775 static int minimum_demerits;
776
777 /*tex how to achieve |minimal_demerits| */
778
779 static halfword best_place[4];
780
781 /*tex corresponding line number */
782
783 static halfword best_pl_line[4];
784
785 /*tex
786
787 The length of lines depends on whether the user has specified \.{\\parshape}
788 or \.{\\hangindent}. If |par_shape_ptr| is not null, it points to a
789 $(2n+1)$-word record in |mem|, where the |vinfo| in the first word contains
790 the value of |n|, and the other $2n$ words contain the left margins and line
791 lengths for the first |n| lines of the paragraph; the specifications for line
792 |n| apply to all subsequent lines. If |par_shape_ptr=null|, the shape of the
793 paragraph depends on the value of |n=hang_after|; if |n>=0|, hanging
794 indentation takes place on lines |n+1|, |n+2|, \dots, otherwise it takes
795 place on lines 1, \dots, $\vert n\vert$. When hanging indentation is active,
796 the left margin is |hang_indent|, if |hang_indent>=0|, else it is 0; the line
797 length is $|hsize|-\vert|hang_indent|\vert$. The normal setting is
798 |par_shape_ptr=null|, |hang_after=1|, and |hang_indent=0|. Note that if
799 |hang_indent=0|, the value of |hang_after| is irrelevant.
800
801 */
802
803 /*tex line numbers |>easy_line| are equivalent in break nodes */
804
805 static halfword easy_line;
806
807 /*tex line numbers |>last_special_line| all have the same width */
808
809 static halfword last_special_line;
810
811 /*tex the width of all lines |<=last_special_line|, if no \.{\\parshape} has been specified */
812
813 static scaled first_width;
814
815 /*tex the width of all lines |>last_special_line| */
816
817 static scaled second_width;
818
819 /*tex left margin to go with |first_width| */
820
821 static scaled first_indent;
822
823 /*tex left margin to go with |second_width| */
824
825 static scaled second_indent;
826
827 /*tex use this passive node and its predecessors */
828
829 static halfword best_bet;
830
831 /*tex the demerits associated with |best_bet| */
832
833 static int fewest_demerits;
834
835 /*tex line number following the last line of the new paragraph */
836
837 static halfword best_line;
838
839 /*tex the difference between |line_number(best_bet)| and the optimum |best_line| */
840
841 static int actual_looseness;
842
843 /*tex the difference between the current line number and the optimum |best_line| */
844
845 static int line_diff;
846
847 /*tex
848
849 \TeX\ makes use of the fact that |hlist_node|, |vlist_node|, |rule_node|,
850 |ins_node|, |mark_node|, |adjust_node|, |disc_node|, |whatsit_node|, and
851 |math_node| are at the low end of the type codes, by permitting a break at
852 glue in a list if and only if the |type| of the previous node is less than
853 |math_node|. Furthermore, a node is discarded after a break if its type is
854 |math_node| or~more.
855
856 */
857
858 #define do_all_six(a) a(1);a(2);a(3);a(4);a(5);a(6);a(7)
859 #define do_seven_eight(a) if (adjust_spacing > 1) { a(8);a(9); }
860 #define do_all_eight(a) do_all_six(a); do_seven_eight(a)
861 #define do_one_seven_eight(a) a(1); do_seven_eight(a)
862
863 #define store_background(a) {active_width[a]=background[a];}
864
865 #define kern_break() { \
866 if ((!is_char_node(vlink(cur_p))) && auto_breaking) \
867 if (type(vlink(cur_p))==glue_node) \
868 ext_try_break(\
869 0, \
870 unhyphenated_node, \
871 line_break_dir, \
872 adjust_spacing, \
873 par_shape_ptr, \
874 adj_demerits, \
875 tracing_paragraphs, \
876 protrude_chars, \
877 line_penalty, \
878 last_line_fit, \
879 double_hyphen_demerits, \
880 final_hyphen_demerits, \
881 first_p, \
882 cur_p \
883 ); \
884 if (type(cur_p)!=math_node) \
885 active_width[1] += width(cur_p); \
886 else \
887 active_width[1] += surround(cur_p); \
888 }
889
890 #define clean_up_the_memory() { \
891 q=vlink(active); \
892 while (q!=active) { \
893 cur_p = vlink(q); \
894 if (type(q)==delta_node) \
895 flush_node(q); \
896 else \
897 flush_node(q); \
898 q = cur_p; \
899 } \
900 q = passive; \
901 while (q!=null) { \
902 cur_p = vlink(q); \
903 flush_node(q); \
904 q = cur_p; \
905 } \
906 }
907
908 /*tex special algorithm for last line of paragraph? */
909
910 static boolean do_last_line_fit;
911
912 /*tex infinite stretch components of |par_fill_skip| */
913
914 static scaled fill_width[4];
915
916 /*tex |shortfall| corresponding to |minimal_demerits| */
917
918 static scaled best_pl_short[4];
919
920 /*tex corresponding glue stretch or shrink */
921
922 static scaled best_pl_glue[4];
923
924 #define reset_disc_width(a) disc_width[(a)] = 0
925
926 #define add_disc_width_to_break_width(a) break_width[(a)] += disc_width[(a)]
927 #define sub_disc_width_from_active_width(a) active_width[(a)] -= disc_width[(a)]
928
929 #define add_char_shrink(a,b) a += char_shrink((b))
930 #define add_char_stretch(a,b) a += char_stretch((b))
931 #define sub_char_shrink(a,b) a -= char_shrink((b))
932 #define sub_char_stretch(a,b) a -= char_stretch((b))
933
934 #define add_kern_shrink(a,b) a += kern_shrink((b))
935 #define add_kern_stretch(a,b) a += kern_stretch((b))
936 #define sub_kern_shrink(a,b) a -= kern_shrink((b))
937 #define sub_kern_stretch(a,b) a -= kern_stretch((b))
938
939 /*tex
940
941 This function is used to add the width of a list of nodes (from a
942 discretionary) to one of the width arrays.
943
944 Replacement texts and discretionary texts are supposed to contain only
945 character nodes, kern nodes, and box or rule nodes.
946
947 */
948
949 #define bad_node_in_disc_error(p) { \
950 if (type(p) == whatsit_node) { \
951 formatted_error("linebreak","invalid node with type %s and subtype %i found in discretionary",node_data[type(p)].name,subtype(p)); \
952 } else { \
953 formatted_error("linebreak","invalid node with type %s found in discretionary",node_data[type(p)].name); \
954 } \
955 }
956
957 static void add_to_widths(halfword s, int line_break_dir, int adjust_spacing, scaled * widths)
958 {
959 while (s != null) {
960 if (is_char_node(s)) {
961 if (tracing_lost_chars_par > 3 && ! char_exists(font(s), character(s))) {
962 char_warning(font(s), character(s));
963 }
964 widths[1] += pack_width(line_break_dir, dir_TRT, s, true);
965 if ((adjust_spacing > 1) && check_expand_pars(font(s))) {
966 set_prev_char_p(s);
967 add_char_stretch(widths[8], s);
968 add_char_shrink(widths[9], s);
969 };
970 } else {
971 switch (type(s)) {
972 case hlist_node:
973 case vlist_node:
974 widths[1] += pack_width(line_break_dir, box_dir(s), s, false);
975 break;
976 case kern_node:
977 if ((adjust_spacing == 2) && (subtype(s) == normal)) {
978 add_kern_stretch(widths[8], s);
979 add_kern_shrink(widths[9], s);
980 }
981 /*tex fall through */
982 case rule_node:
983 widths[1] += width(s);
984 break;
985 case disc_node:
986 break;
987 default:
988 bad_node_in_disc_error(s);
989 break;
990 }
991 }
992 s = vlink(s);
993 }
994 }
995
996 /*tex
997
998 This function is used to substract the width of a list of nodes (from a
999 discretionary) from one of the width arrays. It is used only once, but
1000 deserves it own function because of orthogonality with the |add_to_widths|
1001 function.
1002
1003 */
1004
1005 static void sub_from_widths(halfword s, int line_break_dir, int adjust_spacing, scaled * widths)
1006 {
1007 while (s != null) {
1008 /*tex Subtract the width of node |s| from |break_width|; */
1009 if (is_char_node(s)) {
1010 if (tracing_lost_chars_par > 3 && ! char_exists(font(s), character(s))) {
1011 char_warning(font(s), character(s));
1012 }
1013 widths[1] -= pack_width(line_break_dir, dir_TRT, s, true);
1014 if ((adjust_spacing > 1) && check_expand_pars(font(s))) {
1015 set_prev_char_p(s);
1016 sub_char_stretch(widths[8], s);
1017 sub_char_shrink(widths[9], s);
1018 }
1019 } else {
1020 switch (type(s)) {
1021 case hlist_node:
1022 case vlist_node:
1023 widths[1] -= pack_width(line_break_dir, box_dir(s), s, false);
1024 break;
1025 case kern_node:
1026 if ((adjust_spacing == 2) && (subtype(s) == normal)) {
1027 sub_kern_stretch(widths[8], s);
1028 sub_kern_shrink(widths[9], s);
1029 }
1030 /*tex fall through */
1031 case rule_node:
1032 widths[1] -= width(s);
1033 break;
1034 case disc_node:
1035 break;
1036 default:
1037 bad_node_in_disc_error(s);
1038 break;
1039 }
1040 }
1041 s = vlink(s);
1042 }
1043 }
1044
1045 /*tex
1046
1047 When we insert a new active node for a break at |cur_p|, suppose this new
1048 node is to be placed just before active node |a|; then we essentially want to
1049 insert `$\delta\,|cur_p|\,\delta^\prime$' before |a|, where
1050 $\delta=\alpha(a)-\alpha(|cur_p|)$ and
1051 $\delta^\prime=\alpha(|cur_p|)-\alpha(a)$ in the notation explained above.
1052 The |cur_active_width| array now holds $\gamma+\beta(|cur_p|)-\alpha(a)$; so
1053 $\delta$ can be obtained by subtracting |cur_active_width| from the quantity
1054 $\gamma+\beta(|cur_p|)- \alpha(|cur_p|)$. The latter quantity can be regarded
1055 as the length of a line ``from |cur_p| to |cur_p|''; we call it the
1056 |break_width| at |cur_p|.
1057
1058 The |break_width| is usually negative, since it consists of the background
1059 (which is normally zero) minus the width of nodes following~|cur_p| that are
1060 eliminated after a break. If, for example, node |cur_p| is a glue node, the
1061 width of this glue is subtracted from the background; and we also look ahead
1062 to eliminate all subsequent glue and penalty and kern and math nodes,
1063 subtracting their widths as well.
1064
1065 Kern nodes do not disappear at a line break unless they are |explicit|.
1066
1067 */
1068
1069 static void compute_break_width(int break_type, int line_break_dir, int adjust_spacing, halfword p)
1070 {
1071 /*tex
1072
1073 Glue and other 'whitespace' to be skipped after a break; used if
1074 unhyphenated, or |post_break==empty|.
1075
1076 */
1077 halfword s = p;
1078 if (break_type > unhyphenated_node && p != null) {
1079 /*tex
1080
1081 Compute the discretionary |break_width| values.
1082
1083 When |p| is a discretionary break, the length of a line ``from |p| to
1084 |p|'' has to be defined properly so that the other calculations work
1085 out. Suppose that the pre-break text at |p| has length $l_0$, the
1086 post-break text has length $l_1$, and the replacement text has length
1087 |l|. Suppose also that |q| is the node following the replacement
1088 text. Then length of a line from |p| to |q| will be computed as
1089 $\gamma+\beta(q)-\alpha(|p|)$, where $\beta(q)=\beta(|p|)-l_0+l$. The
1090 actual length will be the background plus $l_1$, so the length from
1091 |p| to |p| should be $\gamma+l_0+l_1-l$. If the post-break text of
1092 the discretionary is empty, a break may also discard~|q|; in that
1093 unusual case we subtract the length of~|q| and any other nodes that
1094 will be discarded after the discretionary break.
1095
1096 The value of $l_0$ need not be computed, since |line_break| will put
1097 it into the global variable |disc_width| before calling |try_break|.
1098
1099 In case of nested discretionaries, we always follow the no-break
1100 path, as we are talking about the breaking on {\it this} position.
1101
1102 */
1103 sub_from_widths(vlink_no_break(p), line_break_dir, adjust_spacing, break_width);
1104 add_to_widths(vlink_post_break(p), line_break_dir, adjust_spacing, break_width);
1105 do_one_seven_eight(add_disc_width_to_break_width);
1106 if (vlink_post_break(p) == null) {
1107 /*tex no |post_break|: 'skip' any 'whitespace' following */
1108 s = vlink(p);
1109 } else {
1110 s = null;
1111 }
1112 }
1113 while (s != null) {
1114 switch (type(s)) {
1115 case math_node:
1116 /*tex begin mathskip code */
1117 if (glue_is_zero(s)) {
1118 break_width[1] -= surround(s);
1119 break;
1120 } else {
1121 /*tex fall through */
1122 }
1123 /*tex end mathskip code */
1124 case glue_node:
1125 /*tex Subtract glue from |break_width|; */
1126 break_width[1] -= width(s);
1127 break_width[2 + stretch_order(s)] -= stretch(s);
1128 break_width[7] -= shrink(s);
1129 break;
1130 case penalty_node:
1131 break;
1132 case kern_node:
1133 if (subtype(s) != explicit_kern && subtype(s) != italic_kern)
1134 return;
1135 else
1136 break_width[1] -= width(s);
1137 break;
1138 default:
1139 return;
1140 };
1141 s = vlink(s);
1142 }
1143 }
1144
1145 static void print_break_node(halfword q, fitness_value fit_class, quarterword break_type, halfword cur_p)
1146 {
1147 /*tex Print a symbolic description of the new break node. */
1148 tprint_nl("@@");
1149 print_int(serial(passive));
1150 tprint(": line ");
1151 print_int(line_number(q) - 1);
1152 print_char('.');
1153 print_int(fit_class);
1154 if (break_type == hyphenated_node)
1155 print_char('-');
1156 tprint(" t=");
1157 print_int(total_demerits(q));
1158 if (do_last_line_fit) {
1159 /*tex Print additional data in the new active node. */
1160 tprint(" s=");
1161 print_scaled(active_short(q));
1162 if (cur_p == null)
1163 tprint(" a=");
1164 else
1165 tprint(" g=");
1166 print_scaled(active_glue(q));
1167 }
1168 tprint(" -> @");
1169 if (prev_break(passive) == null)
1170 print_char('0');
1171 else
1172 print_int(serial(prev_break(passive)));
1173 }
1174
1175 static void print_feasible_break(halfword cur_p, pointer r, halfword b, int pi, int d, boolean artificial_demerits)
1176 {
1177 /*tex
1178
1179 Print a symbolic description of this feasible break.
1180
1181 */
1182 if (printed_node != cur_p) {
1183 /*tex
1184
1185 Print the list between |printed_node| and |cur_p|, then set
1186 |printed_node:=cur_p|.
1187
1188 */
1189 tprint_nl("");
1190 if (cur_p == null) {
1191 short_display(vlink(printed_node));
1192 } else {
1193 halfword save_link = vlink(cur_p);
1194 vlink(cur_p) = null;
1195 tprint_nl("");
1196 short_display(vlink(printed_node));
1197 vlink(cur_p) = save_link;
1198 }
1199 printed_node = cur_p;
1200 }
1201 tprint_nl("@");
1202 if (cur_p == null) {
1203 tprint_esc("par");
1204 } else if (type(cur_p) != glue_node) {
1205 if (type(cur_p) == penalty_node)
1206 tprint_esc("penalty");
1207 else if (type(cur_p) == disc_node)
1208 tprint_esc("discretionary");
1209 else if (type(cur_p) == kern_node)
1210 tprint_esc("kern");
1211 else
1212 tprint_esc("math");
1213 }
1214 tprint(" via @");
1215 if (break_node(r) == null)
1216 print_char('0');
1217 else
1218 print_int(serial(break_node(r)));
1219 tprint(" b=");
1220 if (b > inf_bad)
1221 print_char('*');
1222 else
1223 print_int(b);
1224 tprint(" p=");
1225 print_int(pi);
1226 tprint(" d=");
1227 if (artificial_demerits)
1228 print_char('*');
1229 else
1230 print_int(d);
1231 }
1232
1233 #define add_disc_width_to_active_width(a) active_width[a] += disc_width[a]
1234 #define update_width(a) cur_active_width[a] += varmem[(r+(a))].cint
1235
1236 #define set_break_width_to_background(a) break_width[a]=background[(a)]
1237
1238 #define convert_to_break_width(a) \
1239 varmem[(prev_r+(a))].cint = varmem[(prev_r+(a))].cint-cur_active_width[(a)]+break_width[(a)]
1240
1241 #define store_break_width(a) active_width[(a)]=break_width[(a)]
1242
1243 #define new_delta_to_break_width(a) \
1244 varmem[(q+(a))].cint=break_width[(a)]-cur_active_width[(a)]
1245
1246 #define new_delta_from_break_width(a) \
1247 varmem[(q+(a))].cint=cur_active_width[(a)]-break_width[(a)]
1248
1249 #define copy_to_cur_active(a) cur_active_width[(a)]=active_width[(a)]
1250
1251 #define combine_two_deltas(a) varmem[(prev_r+(a))].cint += varmem[(r+(a))].cint
1252 #define downdate_width(a) cur_active_width[(a)] -= varmem[(prev_r+(a))].cint
1253 #define update_active(a) active_width[(a)]+=varmem[(r+(a))].cint
1254
1255 #define total_font_stretch cur_active_width[8]
1256 #define total_font_shrink cur_active_width[9]
1257
1258 #define cal_margin_kern_var(a) { \
1259 character(cp) = character((a)); \
1260 font(cp) = font((a)); \
1261 do_subst_font(cp, 1000); \
1262 if (font(cp) != font((a))) \
1263 margin_kern_stretch += (left_pw((a)) - left_pw(cp)); \
1264 font(cp) = font((a)); \
1265 do_subst_font(cp, -1000); \
1266 if (font(cp) != font((a))) \
1267 margin_kern_shrink += (left_pw(cp) - left_pw((a))); \
1268 }
1269
1270 static void ext_try_break(
1271 int pi,
1272 quarterword break_type,
1273 int line_break_dir,
1274 int adjust_spacing,
1275 int par_shape_ptr,
1276 int adj_demerits,
1277 int tracing_paragraphs,
1278 int protrude_chars,
1279 int line_penalty,
1280 int last_line_fit,
1281 int double_hyphen_demerits,
1282 int final_hyphen_demerits, halfword first_p, halfword cur_p
1283 )
1284 {
1285 /*tex runs through the active list */
1286 pointer r;
1287 scaled margin_kern_stretch;
1288 scaled margin_kern_shrink;
1289 halfword lp, rp, cp;
1290 /*tex stays a step behind |r| */
1291 halfword prev_r = active;
1292 /*tex a step behind |prev_r|, if |type(prev_r)=delta_node| */
1293 halfword prev_prev_r = null;
1294 /*tex maximum line number in current equivalence class of lines */
1295 halfword old_l = 0;
1296 /*tex have we found a feasible break at |cur_p|? */
1297 boolean no_break_yet = true;
1298 /*tex points to a new node being created */
1299 halfword q;
1300 /*tex line number of current active node */
1301 halfword l;
1302 /*tex should node |r| remain in the active list? */
1303 boolean node_r_stays_active;
1304 /*tex the current line will be justified to this width */
1305 scaled line_width = 0;
1306 /*tex possible fitness class of test line */
1307 fitness_value fit_class;
1308 /*tex badness of test line */
1309 halfword b;
1310 /*tex demerits of test line */
1311 int d;
1312 /*tex has |d| been forced to zero? */
1313 boolean artificial_demerits;
1314 /*tex used in badness calculations */
1315 scaled shortfall;
1316 /*tex glue stretch or shrink of test line, adjustment for last line */
1317 scaled g = 0;
1318 /*tex distance from current active node */
1319 scaled cur_active_width[10] = { 0 };
1320 /*tex Make sure that |pi| is in the proper range; */
1321 if (pi >= inf_penalty) {
1322 /*tex this breakpoint is inhibited by infinite penalty */
1323 return;
1324 } else if (pi <= -inf_penalty) {
1325 /*tex this breakpoint will be forced */
1326 pi = eject_penalty;
1327 }
1328
1329 do_all_eight(copy_to_cur_active);
1330
1331 while (1) {
1332 r = vlink(prev_r);
1333 /*tex
1334
1335 If node |r| is of type |delta_node|, update |cur_active_width|, set
1336 |prev_r| and |prev_prev_r|, then |goto continue|. The following code
1337 uses the fact that |type(active)<>delta_node|.
1338
1339 */
1340 if (type(r) == delta_node) {
1341 /*tex implicit */
1342 do_all_eight(update_width);
1343 prev_prev_r = prev_r;
1344 prev_r = r;
1345 continue;
1346 }
1347 /*tex
1348
1349 If a line number class has ended, create new active nodes for the
1350 best feasible breaks in that class; then |return| if |r=active|,
1351 otherwise compute the new |line_width|.
1352
1353 The first part of the following code is part of \TeX's inner loop, so
1354 we don't want to waste any time. The current active node, namely node
1355 |r|, contains the line number that will be considered next. At the
1356 end of the list we have arranged the data structure so that
1357 |r=active| and |line_number(active)>old_l|.
1358
1359 */
1360 l = line_number(r);
1361 if (l > old_l) {
1362 /*tex now we are no longer in the inner loop */
1363 if ((minimum_demerits < awful_bad)
1364 && ((old_l != easy_line) || (r == active))) {
1365 /*tex
1366
1367 Create new active nodes for the best feasible breaks just
1368 found. It is not necessary to create new active nodes having
1369 |minimal_demerits| greater than
1370 |minimum_demerits+abs(adj_demerits)|, since such active nodes
1371 will never be chosen in the final paragraph breaks. This
1372 observation allows us to omit a substantial number of
1373 feasible breakpoints from further consideration.
1374
1375 */
1376 if (no_break_yet) {
1377 no_break_yet = false;
1378 do_all_eight(set_break_width_to_background);
1379 compute_break_width(break_type, line_break_dir, adjust_spacing, cur_p);
1380 }
1381 /*tex
1382
1383 Insert a delta node to prepare for breaks at |cur_p|. We use
1384 the fact that |type(active)<>delta_node|.
1385
1386 */
1387 if (type(prev_r) == delta_node) {
1388 /*tex modify an existing delta node */
1389 do_all_eight(convert_to_break_width);
1390 } else if (prev_r == active) {
1391 /*tex no delta node needed at the beginning */
1392 do_all_eight(store_break_width);
1393 } else {
1394 q = new_node(delta_node, 0);
1395 vlink(q) = r;
1396 do_all_eight(new_delta_to_break_width);
1397 vlink(prev_r) = q;
1398 prev_prev_r = prev_r;
1399 prev_r = q;
1400 }
1401 if (abs(adj_demerits) >= awful_bad - minimum_demerits)
1402 minimum_demerits = awful_bad - 1;
1403 else
1404 minimum_demerits += abs(adj_demerits);
1405 for (fit_class = very_loose_fit; fit_class <= tight_fit;
1406 fit_class++) {
1407 if (minimal_demerits[fit_class] <= minimum_demerits) {
1408 /*tex
1409
1410 Insert a new active node from |best_place[fit_class]|
1411 to |cur_p|. When we create an active node, we also
1412 create the corresponding passive node.
1413
1414 */
1415 q = new_node(passive_node, 0);
1416 vlink(q) = passive;
1417 passive = q;
1418 cur_break(q) = cur_p;
1419 incr(pass_number);
1420 serial(q) = pass_number;
1421 prev_break(q) = best_place[fit_class];
1422 /*tex
1423
1424 Here we keep track of the subparagraph penalties in
1425 the break nodes.
1426
1427 */
1428 passive_pen_inter(q) = internal_pen_inter;
1429 passive_pen_broken(q) = internal_pen_broken;
1430 passive_last_left_box(q) = internal_left_box;
1431 passive_last_left_box_width(q) =
1432 internal_left_box_width;
1433 if (prev_break(q) != null) {
1434 passive_left_box(q) = passive_last_left_box(prev_break(q));
1435 passive_left_box_width(q) = passive_last_left_box_width(prev_break(q));
1436 } else {
1437 passive_left_box(q) = init_internal_left_box;
1438 passive_left_box_width(q) = init_internal_left_box_width;
1439 }
1440 passive_right_box(q) = internal_right_box;
1441 passive_right_box_width(q) = internal_right_box_width;
1442 q = new_node(break_type, fit_class);
1443 break_node(q) = passive;
1444 line_number(q) = best_pl_line[fit_class] + 1;
1445 total_demerits(q) = minimal_demerits[fit_class];
1446 if (do_last_line_fit) {
1447 /*tex
1448
1449 Store additional data in the new active node.
1450 Here we save these data in the active node
1451 representing a potential line break.
1452
1453 */
1454 active_short(q) = best_pl_short[fit_class];
1455 active_glue(q) = best_pl_glue[fit_class];
1456 }
1457 vlink(q) = r;
1458 vlink(prev_r) = q;
1459 prev_r = q;
1460 if (tracing_paragraphs > 0)
1461 print_break_node(q, fit_class, break_type, cur_p);
1462 }
1463 minimal_demerits[fit_class] = awful_bad;
1464 }
1465 minimum_demerits = awful_bad;
1466 /*tex
1467
1468 Insert a delta node to prepare for the next active node. When
1469 the following code is performed, we will have just inserted
1470 at least one active node before |r|, so
1471 |type(prev_r)<>delta_node|.
1472
1473 */
1474 if (r != active) {
1475 q = new_node(delta_node, 0);
1476 vlink(q) = r;
1477 do_all_eight(new_delta_from_break_width);
1478 vlink(prev_r) = q;
1479 prev_prev_r = prev_r;
1480 prev_r = q;
1481 }
1482 }
1483 if (r == active)
1484 return;
1485 /*tex
1486
1487 Compute the new line width. When we come to the following code,
1488 we have just encountered the first active node~|r| whose
1489 |line_number| field contains |l|. Thus we want to compute the
1490 length of the $l\mskip1mu$th line of the current paragraph.
1491 Furthermore, we want to set |old_l| to the last number in the
1492 class of line numbers equivalent to~|l|.
1493
1494 */
1495 if (l > easy_line) {
1496 old_l = max_halfword - 1;
1497 line_width = second_width;
1498 } else {
1499 old_l = l;
1500 if (l > last_special_line) {
1501 line_width = second_width;
1502 } else if (par_shape_ptr == null) {
1503 line_width = first_width;
1504 } else {
1505 line_width = varmem[(par_shape_ptr + 2 * l + 1)].cint;
1506 }
1507 }
1508 }
1509 /*tex
1510
1511 If a line number class has ended, create new active nodes for the
1512 best feasible breaks in that class; then |return| if |r=active|,
1513 otherwise compute the new |line_width|.
1514
1515 Consider the demerits for a line from |r| to |cur_p|; deactivate node
1516 |r| if it should no longer be active; then |goto continue| if a line
1517 from |r| to |cur_p| is infeasible, otherwise record a new feasible
1518 break.
1519
1520 */
1521 artificial_demerits = false;
1522 shortfall = line_width - cur_active_width[1];
1523 if (break_node(r) == null)
1524 shortfall -= init_internal_left_box_width;
1525 else
1526 shortfall -= passive_last_left_box_width(break_node(r));
1527 shortfall -= internal_right_box_width;
1528 if (protrude_chars > 1) {
1529 halfword l1, o;
1530 l1 = (break_node(r) == null) ? first_p : cur_break(break_node(r));
1531 if (cur_p == null) {
1532 o = null;
1533 } else {
1534 o = alink(cur_p);
1535 assert(vlink(o) == cur_p);
1536 }
1537 /*tex
1538
1539 The disc could be a SELECT subtype, to we might need to get the
1540 last character as |pre_break| from either the |pre_break| list
1541 (if the previous INIT disc was taken), or the |no_break| (sic)
1542 list (if the previous INIT disc was not taken).
1543
1544 The last characters (hyphenation character) if these two list
1545 should always be the same anyway, so we just look at |pre_break|.
1546
1547 Let's look at the right margin first.
1548
1549 */
1550 if ((cur_p != null) && (type(cur_p) == disc_node) && (vlink_pre_break(cur_p) != null)) {
1551 /*tex a |disc_node| with non-empty |pre_break|, protrude the last char of |pre_break| */
1552 o = tlink_pre_break(cur_p);
1553 } else {
1554 o = find_protchar_right(l1, o);
1555 }
1556 /*tex now the left margin */
1557 if ((l1 != null) && (type(l1) == disc_node) && (vlink_post_break(l1) != null)) {
1558 /*tex The first char could be a disc! Protrude the first char. */
1559 l1 = vlink_post_break(l1);
1560 } else {
1561 l1 = find_protchar_left(l1, true);
1562 }
1563 shortfall += (left_pw(l1) + right_pw(o));
1564 }
1565 if (shortfall != 0) {
1566 margin_kern_stretch = 0;
1567 margin_kern_shrink = 0;
1568 if (protrude_chars > 1) {
1569 /*tex Calculate variations of marginal kerns. */
1570 lp = last_leftmost_char;
1571 rp = last_rightmost_char;
1572 cp = raw_glyph_node();
1573 if (lp != null) {
1574 cal_margin_kern_var(lp);
1575 }
1576 if (rp != null) {
1577 cal_margin_kern_var(rp);
1578 }
1579 flush_node(cp);
1580 }
1581 if ((shortfall > 0) && ((total_font_stretch + margin_kern_stretch) > 0)) {
1582 if ((total_font_stretch + margin_kern_stretch) > shortfall)
1583 shortfall = ((total_font_stretch + margin_kern_stretch) / (max_stretch_ratio / cur_font_step)) / 2;
1584 else
1585 shortfall -= (total_font_stretch + margin_kern_stretch);
1586 } else if ((shortfall < 0) && ((total_font_shrink + margin_kern_shrink) > 0)) {
1587 if ((total_font_shrink + margin_kern_shrink) > -shortfall)
1588 shortfall = -((total_font_shrink + margin_kern_shrink) / (max_shrink_ratio / cur_font_step)) / 2;
1589 else
1590 shortfall += (total_font_shrink + margin_kern_shrink);
1591 }
1592 }
1593 if (shortfall > 0) {
1594 /*tex
1595
1596 Set the value of |b| to the badness for stretching the line, and
1597 compute the corresponding |fit_class|.
1598
1599 When a line must stretch, the available stretchability can be
1600 found in the subarray |cur_active_width[2..6]|, in units of
1601 points, sfi, fil, fill and filll.
1602
1603 The present section is part of \TeX's inner loop, and it is most
1604 often performed when the badness is infinite; therefore it is
1605 worth while to make a quick test for large width excess and small
1606 stretchability, before calling the |badness| subroutine.
1607
1608 */
1609 if ((cur_active_width[3] != 0) || (cur_active_width[4] != 0) ||
1610 (cur_active_width[5] != 0) || (cur_active_width[6] != 0)) {
1611 if (do_last_line_fit) {
1612 if (cur_p == null) {
1613 /*tex
1614
1615 The last line of a paragraph. Perform computations
1616 for last line and |goto found|.
1617
1618 Here we compute the adjustment |g| and badness |b|
1619 for a line from |r| to the end of the paragraph. When
1620 any of the criteria for adjustment is violated we
1621 fall through to the normal algorithm.
1622
1623 The last line must be too short, and have infinite
1624 stretch entirely due to |par_fill_skip|.
1625
1626 */
1627 if ((active_short(r) == 0) || (active_glue(r) <= 0))
1628 /*tex
1629
1630 Previous line was neither stretched nor shrunk,
1631 or was infinitely bad.
1632
1633 */
1634 goto NOT_FOUND;
1635 if ((cur_active_width[3] != fill_width[0]) || (cur_active_width[4] != fill_width[1]) ||
1636 (cur_active_width[5] != fill_width[2]) || (cur_active_width[6] != fill_width[3]))
1637 /*tex
1638
1639 Infinite stretch of this line not entirely due to |par_fill_skip|.
1640
1641 */
1642 goto NOT_FOUND;
1643 if (active_short(r) > 0)
1644 g = cur_active_width[2];
1645 else
1646 g = cur_active_width[7];
1647 if (g <= 0)
1648 /*tex No finite stretch resp.\ no shrink. */
1649 goto NOT_FOUND;
1650 arith_error = false;
1651 g = fract(g, active_short(r), active_glue(r),
1652 max_dimen);
1653 if (last_line_fit < 1000)
1654 g = fract(g, last_line_fit, 1000, max_dimen);
1655 if (arith_error) {
1656 if (active_short(r) > 0)
1657 g = max_dimen;
1658 else
1659 g = -max_dimen;
1660 }
1661 if (g > 0) {
1662 /*tex
1663
1664 Set the value of |b| to the badness of the last
1665 line for stretching, compute the corresponding
1666 |fit_class, and |goto found|. These badness
1667 computations are rather similar to those of the
1668 standard algorithm, with the adjustment amount
1669 |g| replacing the |shortfall|.
1670
1671 */
1672 if (g > shortfall)
1673 g = shortfall;
1674 if (g > 7230584) {
1675 if (cur_active_width[2] < 1663497) {
1676 b = inf_bad;
1677 fit_class = very_loose_fit;
1678 goto FOUND;
1679 }
1680 }
1681 b = badness(g, cur_active_width[2]);
1682 if (b > 99) {
1683 fit_class = very_loose_fit;
1684 } else if (b > 12) {
1685 fit_class = loose_fit;
1686 } else {
1687 fit_class = decent_fit;
1688 }
1689 goto FOUND;
1690 } else if (g < 0) {
1691 /*tex
1692
1693 Set the value of |b| to the badness of the last
1694 line for shrinking, compute the corresponding
1695 |fit_class, and |goto found||.
1696
1697 */
1698 if (-g > cur_active_width[7])
1699 g = -cur_active_width[7];
1700 b = badness(-g, cur_active_width[7]);
1701 if (b > 12)
1702 fit_class = tight_fit;
1703 else
1704 fit_class = decent_fit;
1705 goto FOUND;
1706 }
1707 }
1708 NOT_FOUND:
1709 shortfall = 0;
1710 }
1711 b = 0;
1712 /*tex Infinite stretch. */
1713 fit_class = decent_fit;
1714 } else if (shortfall > 7230584 && cur_active_width[2] < 1663497) {
1715 b = inf_bad;
1716 fit_class = very_loose_fit;
1717 } else {
1718 b = badness(shortfall, cur_active_width[2]);
1719 if (b > 99) {
1720 fit_class = very_loose_fit;
1721 } else if (b > 12) {
1722 fit_class = loose_fit;
1723 } else {
1724 fit_class = decent_fit;
1725 }
1726 }
1727 } else {
1728 /*tex
1729
1730 Set the value of |b| to the badness for shrinking the line, and
1731 compute the corresponding |fit_class|. Shrinkability is never
1732 infinite in a paragraph; we can shrink the line from |r| to
1733 |cur_p| by at most |cur_active_width[7]|.
1734
1735 */
1736 if (-shortfall > cur_active_width[7])
1737 b = inf_bad + 1;
1738 else
1739 b = badness(-shortfall, cur_active_width[7]);
1740 if (b > 12)
1741 fit_class = tight_fit;
1742 else
1743 fit_class = decent_fit;
1744 }
1745 if (do_last_line_fit) {
1746 /*tex Adjust the additional data for last line; */
1747 if (cur_p == null)
1748 shortfall = 0;
1749 if (shortfall > 0) {
1750 g = cur_active_width[2];
1751 } else if (shortfall < 0) {
1752 g = cur_active_width[7];
1753 } else {
1754 g = 0;
1755 }
1756 }
1757 FOUND:
1758 if ((b > inf_bad) || (pi == eject_penalty)) {
1759 /*tex
1760
1761 Prepare to deactivate node~|r|, and |goto deactivate| unless
1762 there is a reason to consider lines of text from |r| to |cur_p|.
1763 During the final pass, we dare not lose all active nodes, lest we
1764 lose touch with the line breaks already found. The code shown
1765 here makes sure that such a catastrophe does not happen, by
1766 permitting overfull boxes as a last resort. This particular part
1767 of \TeX\ was a source of several subtle bugs before the correct
1768 program logic was finally discovered; readers who seek to
1769 ``improve'' \TeX\ should therefore think thrice before daring to
1770 make any changes here.
1771
1772 */
1773 if (final_pass && (minimum_demerits == awful_bad) &&
1774 (vlink(r) == active) && (prev_r == active)) {
1775 /*tex Set demerits zero, this break is forced. */
1776 artificial_demerits = true;
1777 } else if (b > threshold) {
1778 goto DEACTIVATE;
1779 }
1780 node_r_stays_active = false;
1781 } else {
1782 prev_r = r;
1783 if (b > threshold)
1784 continue;
1785 node_r_stays_active = true;
1786 }
1787 /*tex
1788
1789 Record a new feasible break. When we get to this part of the code,
1790 the line from |r| to |cur_p| is feasible, its badness is~|b|, and its
1791 fitness classification is |fit_class|. We don't want to make an
1792 active node for this break yet, but we will compute the total
1793 demerits and record them in the |minimal_demerits| array, if such a
1794 break is the current champion among all ways to get to |cur_p| in a
1795 given line-number class and fitness class.
1796
1797 */
1798 if (artificial_demerits) {
1799 d = 0;
1800 } else {
1801 /*tex Compute the demerits, |d|, from |r| to |cur_p|. */
1802 d = line_penalty + b;
1803 if (abs(d) >= 10000)
1804 d = 100000000;
1805 else
1806 d = d * d;
1807 if (pi != 0) {
1808 if (pi > 0) {
1809 d += (pi * pi);
1810 } else if (pi > eject_penalty) {
1811 d -= (pi * pi);
1812 }
1813 }
1814 if ((break_type == hyphenated_node) && (type(r) == hyphenated_node)) {
1815 if (cur_p != null)
1816 d += double_hyphen_demerits;
1817 else
1818 d += final_hyphen_demerits;
1819 }
1820 /*tex
1821
1822 Direct calculation of the absolute value in ((|fit_class| - |fitness(r)|) > 1)
1823 can lead to unexpected results even if the type of the members of |fit_class|, which is |int|
1824 (see C99 §6.7.2.2), and the integer promotion rules for |fitness(r)|, whose also
1825 give an |int| type, should set the expression as substraction between two |int|.
1826 In this case GCC set the type of |fit_class| to |unsigned int| (perhaps because the members are all positives?)
1827 and hence the expression is converted to a sum of |unsigned int|, leading to a different result.
1828 The choice of type is implementation-defined, as stated in C99 §6.7.2.2.4:
1829
1830 "Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type.
1831 The choice of type is implementation-defined, but shall be capable of representing the values
1832 of all the members of the enumeration."
1833
1834 It's better to use the equivalent expanded expression.
1835 */
1836 if ( (fit_class>(fitness(r)+1)) || (fitness(r)>(fit_class+1)) )
1837 d = d + adj_demerits;
1838
1839 }
1840 if (tracing_paragraphs > 0) {
1841 print_feasible_break(cur_p, r, b, pi, d, artificial_demerits);
1842 }
1843 /*tex This is the minimum total demerits from the beginning to |cur_p| via |r|. */
1844 d += total_demerits(r);
1845 if (d <= minimal_demerits[fit_class]) {
1846 minimal_demerits[fit_class] = d;
1847 best_place[fit_class] = break_node(r);
1848 best_pl_line[fit_class] = l;
1849 if (do_last_line_fit) {
1850 /*tex
1851
1852 Store additional data for this feasible break. For each
1853 feasible break we record the shortfall and glue stretch or
1854 shrink (or adjustment).
1855
1856 */
1857 best_pl_short[fit_class] = shortfall;
1858 best_pl_glue[fit_class] = g;
1859 }
1860 if (d < minimum_demerits)
1861 minimum_demerits = d;
1862 }
1863 /*tex Record a new feasible break. */
1864 if (node_r_stays_active) {
1865 /*tex |prev_r| has been set to |r|. */
1866 continue;
1867 }
1868 DEACTIVATE:
1869 /*tex
1870
1871 Deactivate node |r|. When an active node disappears, we must delete
1872 an adjacent delta node if the active node was at the beginning or the
1873 end of the active list, or if it was surrounded by delta nodes. We
1874 also must preserve the property that |cur_active_width| represents
1875 the length of material from |vlink(prev_r)| to~|cur_p|.
1876
1877 */
1878 vlink(prev_r) = vlink(r);
1879 flush_node(r);
1880 if (prev_r == active) {
1881 /*tex
1882
1883 Update the active widths, since the first active node has been
1884 deleted. The following code uses the fact that
1885 |type(active)<>delta_node|. If the active list has just become
1886 empty, we do not need to update the |active_width| array, since
1887 it will be initialized when an active node is next inserted.
1888
1889 */
1890 r = vlink(active);
1891 if (type(r) == delta_node) {
1892 do_all_eight(update_active);
1893 do_all_eight(copy_to_cur_active);
1894 vlink(active) = vlink(r);
1895 flush_node(r);
1896 }
1897 } else if (type(prev_r) == delta_node) {
1898 r = vlink(prev_r);
1899 if (r == active) {
1900 do_all_eight(downdate_width);
1901 vlink(prev_prev_r) = active;
1902 flush_node(prev_r);
1903 prev_r = prev_prev_r;
1904 } else if (type(r) == delta_node) {
1905 do_all_eight(update_width);
1906 do_all_eight(combine_two_deltas);
1907 vlink(prev_r) = vlink(r);
1908 flush_node(r);
1909 }
1910 }
1911 }
1912 }
1913
1914 void ext_do_line_break(
1915 int paragraph_dir,
1916 int pretolerance,
1917 int tracing_paragraphs,
1918 int tolerance,
1919 scaled emergency_stretch,
1920 int looseness,
1921 int adjust_spacing,
1922 halfword par_shape_ptr,
1923 int adj_demerits,
1924 int protrude_chars,
1925 int line_penalty,
1926 int last_line_fit,
1927 int double_hyphen_demerits,
1928 int final_hyphen_demerits,
1929 int hang_indent,
1930 int hsize,
1931 int hang_after,
1932 halfword left_skip,
1933 halfword right_skip,
1934 halfword inter_line_penalties_ptr,
1935 int inter_line_penalty,
1936 int club_penalty,
1937 halfword club_penalties_ptr,
1938 halfword widow_penalties_ptr,
1939 int widow_penalty,
1940 int broken_penalty,
1941 halfword final_par_glue
1942 )
1943 {
1944 /*tex Miscellaneous nodes of temporary interest. */
1945 halfword cur_p, q, r, s;
1946 int line_break_dir = paragraph_dir;
1947 /*tex Get ready to start */
1948 minimum_demerits = awful_bad;
1949 minimal_demerits[tight_fit] = awful_bad;
1950 minimal_demerits[decent_fit] = awful_bad;
1951 minimal_demerits[loose_fit] = awful_bad;
1952 minimal_demerits[very_loose_fit] = awful_bad;
1953 fewest_demerits = 0;
1954 actual_looseness = 0;
1955 /*tex
1956
1957 We compute the values of |easy_line| and the other local variables
1958 relating to line length when the |line_break| procedure is initializing
1959 itself.
1960
1961 */
1962 if (par_shape_ptr == null) {
1963 if (hang_indent == 0) {
1964 last_special_line = 0;
1965 second_width = hsize;
1966 second_indent = 0;
1967 } else {
1968 halfword used_hang_indent = swap_hang_indent(hang_indent);
1969 /*tex
1970
1971 Set line length parameters in preparation for hanging
1972 indentation. We compute the values of |easy_line| and the other
1973 local variables relating to line length when the |line_break|
1974 procedure is initializing itself.
1975
1976 */
1977 last_special_line = abs(hang_after);
1978 if (hang_after < 0) {
1979 first_width = hsize - abs(used_hang_indent);
1980 if (used_hang_indent >= 0)
1981 first_indent = used_hang_indent;
1982 else
1983 first_indent = 0;
1984 second_width = hsize;
1985 second_indent = 0;
1986 } else {
1987 first_width = hsize;
1988 first_indent = 0;
1989 second_width = hsize - abs(used_hang_indent);
1990 if (used_hang_indent >= 0)
1991 second_indent = used_hang_indent;
1992 else
1993 second_indent = 0;
1994 }
1995 }
1996 } else {
1997 last_special_line = vinfo(par_shape_ptr + 1) - 1;
1998 second_indent = varmem[(par_shape_ptr + 2 * (last_special_line + 1))].cint;
1999 second_width = varmem[(par_shape_ptr + 2 * (last_special_line + 1) + 1)].cint;
2000 second_indent = swap_parshape_indent(second_indent,second_width);
2001 }
2002 if (looseness == 0)
2003 easy_line = last_special_line;
2004 else
2005 easy_line = max_halfword;
2006 no_shrink_error_yet = true;
2007 check_shrinkage(left_skip);
2008 check_shrinkage(right_skip);
2009 q = left_skip;
2010 r = right_skip;
2011 background[1] = width(q) + width(r);
2012 background[2] = 0;
2013 background[3] = 0;
2014 background[4] = 0;
2015 background[5] = 0;
2016 background[6] = 0;
2017 background[2 + stretch_order(q)] = stretch(q);
2018 background[2 + stretch_order(r)] += stretch(r);
2019 background[7] = shrink(q) + shrink(r);
2020 if (adjust_spacing > 1) {
2021 background[8] = 0;
2022 background[9] = 0;
2023 max_stretch_ratio = -1;
2024 max_shrink_ratio = -1;
2025 cur_font_step = -1;
2026 set_prev_char_p(null);
2027 }
2028 /*tex
2029
2030 Check for special treatment of last line of paragraph. The new algorithm
2031 for the last line requires that the stretchability |par_fill_skip| is
2032 infinite and the stretchability of |left_skip| plus |right_skip| is
2033 finite.
2034
2035 */
2036 do_last_line_fit = false;
2037 if (last_line_fit > 0) {
2038 q = last_line_fill;
2039 if ((stretch(q) > 0) && (stretch_order(q) > normal)) {
2040 if ((background[3] == 0) && (background[4] == 0) && (background[5] == 0) && (background[6] == 0)) {
2041 do_last_line_fit = true;
2042 fill_width[0] = 0;
2043 fill_width[1] = 0;
2044 fill_width[2] = 0;
2045 fill_width[3] = 0;
2046 fill_width[stretch_order(q) - 1] = stretch(q);
2047 }
2048 }
2049 }
2050 /*tex Initialize |dir_ptr| for |line_break|. */
2051 if (dir_ptr != null) {
2052 flush_node_list(dir_ptr);
2053 dir_ptr = null;
2054 }
2055 /*tex Find optimal breakpoints. */
2056 threshold = pretolerance;
2057 if (threshold >= 0) {
2058 if (tracing_paragraphs > 0) {
2059 begin_diagnostic();
2060 tprint_nl("@firstpass");
2061 }
2062 second_pass = false;
2063 final_pass = false;
2064 } else {
2065 threshold = tolerance;
2066 second_pass = true;
2067 final_pass = (emergency_stretch <= 0);
2068 if (tracing_paragraphs > 0)
2069 begin_diagnostic();
2070 }
2071 while (1) {
2072 halfword first_p;
2073 halfword nest_stack[10];
2074 int nest_index = 0;
2075 if (threshold > inf_bad)
2076 threshold = inf_bad;
2077 /*tex Create an active breakpoint representing the beginning of the paragraph. */
2078 q = new_node(unhyphenated_node, decent_fit);
2079 vlink(q) = active;
2080 break_node(q) = null;
2081 line_number(q) = cur_list.pg_field + 1;
2082 total_demerits(q) = 0;
2083 active_short(q) = 0;
2084 active_glue(q) = 0;
2085 vlink(active) = q;
2086 do_all_eight(store_background);
2087 passive = null;
2088 printed_node = temp_head;
2089 pass_number = 0;
2090 font_in_short_display = null_font;
2091 /*tex Create an active breakpoint representing the beginning of the paragraph. */
2092 auto_breaking = true;
2093 cur_p = vlink(temp_head);
2094 /*tex Initialize with first |local_paragraph| node. */
2095 if ((cur_p != null) && (type(cur_p) == local_par_node)) {
2096 /*tex This used to be an assert, but may as well force it. */
2097 alink(cur_p) = temp_head;
2098 internal_pen_inter = local_pen_inter(cur_p);
2099 internal_pen_broken = local_pen_broken(cur_p);
2100 init_internal_left_box = local_box_left(cur_p);
2101 init_internal_left_box_width = local_box_left_width(cur_p);
2102 internal_left_box = init_internal_left_box;
2103 internal_left_box_width = init_internal_left_box_width;
2104 internal_right_box = local_box_right(cur_p);
2105 internal_right_box_width = local_box_right_width(cur_p);
2106 } else {
2107 internal_pen_inter = 0;
2108 internal_pen_broken = 0;
2109 init_internal_left_box = null;
2110 init_internal_left_box_width = 0;
2111 internal_left_box = init_internal_left_box;
2112 internal_left_box_width = init_internal_left_box_width;
2113 internal_right_box = null;
2114 internal_right_box_width = 0;
2115 }
2116 /*tex Initialize with first |local_paragraph| node. */
2117 set_prev_char_p(null);
2118 first_p = cur_p;
2119 /*tex
2120
2121 To access the first node of paragraph as the first active node has
2122 |break_node=null|.
2123
2124 */
2125 while ((cur_p != null) && (vlink(active) != active)) {
2126 /*tex
2127
2128 |try_break| if |cur_p| is a legal breakpoint; on the 2nd pass,
2129 also look at |disc_node|s.
2130
2131 */
2132 while (is_char_node(cur_p)) {
2133 /*tex
2134
2135 Advance |cur_p| to the node following the present string of
2136 characters. The code that passes over the characters of words
2137 in a paragraph is part of \TeX's inner loop, so it has been
2138 streamlined for speed. We use the fact that
2139 `\.{\\parfillskip}' glue appears at the end of each
2140 paragraph; it is therefore unnecessary to check if
2141 |vlink(cur_p)=null| when |cur_p| is a character node.
2142
2143 */
2144 if (tracing_lost_chars_par > 3 && ! char_exists(font(cur_p), character(cur_p))) {
2145 char_warning(font(cur_p), character(cur_p));
2146 }
2147 active_width[1] += pack_width(line_break_dir, dir_TRT, cur_p, true);
2148 if ((adjust_spacing > 1) && check_expand_pars(font(cur_p))) {
2149 set_prev_char_p(cur_p);
2150 add_char_stretch(active_width[8], cur_p);
2151 add_char_shrink(active_width[9], cur_p);
2152 }
2153 cur_p = vlink(cur_p);
2154 while (cur_p == null && nest_index > 0) {
2155 cur_p = nest_stack[--nest_index];
2156 }
2157 }
2158 if (cur_p == null) {
2159 normal_error("linebreak","invalid list tail, probably missing glue");
2160 }
2161 /*tex
2162
2163 Determine legal breaks: As we move through the hlist, we need to
2164 keep the |active_width| array up to date, so that the badness of
2165 individual lines is readily calculated by |try_break|. It is
2166 convenient to use the short name |active_width[1]| for the
2167 component of active width that represents real width as opposed
2168 to glue.
2169
2170 */
2171 switch (type(cur_p)) {
2172 case hlist_node:
2173 case vlist_node:
2174 active_width[1] += pack_width(line_break_dir, box_dir(cur_p), cur_p, false);
2175 break;
2176 case rule_node:
2177 active_width[1] += width(cur_p);
2178 break;
2179 case dir_node:
2180 /*tex Adjust the dir stack for the |line_break| routine. */
2181 if (subtype(cur_p) == normal_dir) {
2182 line_break_dir = dir_dir(cur_p);
2183 /* Adds to |dir_ptr|. */
2184 push_dir_node(dir_ptr,cur_p);
2185 } else {
2186 pop_dir_node(dir_ptr);
2187 if (dir_ptr != null) {
2188 line_break_dir = dir_dir(dir_ptr);
2189 }
2190 }
2191 break;
2192 case local_par_node:
2193 /*tex Advance past a |local_paragraph| node. */
2194 internal_pen_inter = local_pen_inter(cur_p);
2195 internal_pen_broken = local_pen_broken(cur_p);
2196 internal_left_box = local_box_left(cur_p);
2197 internal_left_box_width = local_box_left_width(cur_p);
2198 internal_right_box = local_box_right(cur_p);
2199 internal_right_box_width = local_box_right_width(cur_p);
2200 break;
2201 case math_node:
2202 auto_breaking = (subtype(cur_p) == after);
2203 /*tex begin mathskip code */
2204 if (glue_is_zero(cur_p) || ignore_math_skip(cur_p)) {
2205 kern_break();
2206 break;
2207 } else {
2208 /*tex fall through */
2209 }
2210 /*tex end mathskip code */
2211 case glue_node:
2212 /*tex
2213
2214 If node |cur_p| is a legal breakpoint, call |try_break|;
2215 then update the active widths by including the glue in
2216 |glue_ptr(cur_p)|.
2217
2218 When node |cur_p| is a glue node, we look at the previous
2219 to see whether or not a breakpoint is legal at |cur_p|,
2220 as explained above.
2221
2222 We only break after certain nodes (see texnodes.h), a
2223 font related kern and a dir node when
2224 |\breakafterdirmode=1|.
2225
2226 */
2227 if (auto_breaking) {
2228 halfword prev_p = alink(cur_p);
2229 if (prev_p != temp_head && (is_char_node(prev_p)
2230 || precedes_break(prev_p) || precedes_kern(prev_p) || precedes_dir(prev_p))) {
2231 ext_try_break(
2232 0,
2233 unhyphenated_node,
2234 line_break_dir,
2235 adjust_spacing,
2236 par_shape_ptr,
2237 adj_demerits,
2238 tracing_paragraphs,
2239 protrude_chars,
2240 line_penalty,
2241 last_line_fit,
2242 double_hyphen_demerits,
2243 final_hyphen_demerits,
2244 first_p,
2245 cur_p
2246 );
2247 }
2248 }
2249 check_shrinkage(cur_p);
2250 active_width[1] += width(cur_p);
2251 active_width[2 + stretch_order(cur_p)] += stretch(cur_p);
2252 active_width[7] += shrink(cur_p);
2253 break;
2254 case kern_node:
2255 if (subtype(cur_p) == explicit_kern || subtype(cur_p) == italic_kern) {
2256 kern_break();
2257 } else {
2258 active_width[1] += width(cur_p);
2259 if ((adjust_spacing == 2) && (subtype(cur_p) == normal)) {
2260 add_kern_stretch(active_width[8], cur_p);
2261 add_kern_shrink(active_width[9], cur_p);
2262 }
2263 }
2264 break;
2265 case disc_node:
2266 /*tex
2267
2268 |select_disc|s are handled by the leading |init_disc|.
2269
2270 */
2271 if (subtype(cur_p) == select_disc)
2272 break;
2273 /*tex
2274
2275 Try to break after a discretionary fragment, then |goto
2276 done5|. The following code knows that discretionary texts
2277 contain only character nodes, kern nodes, box nodes, and
2278 rule nodes. This branch differs a bit from older engines
2279 because in \LUATEX\ we already have hyphenated the list.
2280 This means that we need to skip automatic disc nodes. Of
2281 better, we need to treat discretionaries and explicit
2282 hyphens always, even in the first pass.
2283
2284 */
2285 if (second_pass || subtype(cur_p) <= automatic_disc) {
2286 int actual_penalty = (int) disc_penalty(cur_p);
2287 s = vlink_pre_break(cur_p);
2288 do_one_seven_eight(reset_disc_width);
2289 if (s == null) {
2290 /*tex trivial pre-break */
2291 ext_try_break(actual_penalty, hyphenated_node,
2292 line_break_dir, adjust_spacing,
2293 par_shape_ptr, adj_demerits,
2294 tracing_paragraphs, protrude_chars,
2295 line_penalty, last_line_fit,
2296 double_hyphen_demerits,
2297 final_hyphen_demerits, first_p, cur_p);
2298 } else {
2299 add_to_widths(s, line_break_dir, adjust_spacing, disc_width);
2300 do_one_seven_eight(add_disc_width_to_active_width);
2301 ext_try_break(actual_penalty, hyphenated_node,
2302 line_break_dir, adjust_spacing,
2303 par_shape_ptr, adj_demerits,
2304 tracing_paragraphs, protrude_chars,
2305 line_penalty, last_line_fit,
2306 double_hyphen_demerits,
2307 final_hyphen_demerits, first_p, cur_p);
2308 if (subtype(cur_p) == init_disc) {
2309 /*tex
2310
2311 We should at two break points after the one
2312 we added above:
2313
2314 \startitemize[n]
2315 \startitem
2316 which does a possible break in INIT's
2317 |post_break|
2318 \stopitem
2319 \startitem
2320 which means the |no_break| actually
2321 was broken just a character later
2322 \stopitem
2323 \stopitemize
2324
2325 Do the select-0 case |f-f-i|:
2326
2327 */
2328 s = vlink_pre_break(vlink(cur_p));
2329 add_to_widths(s, line_break_dir, adjust_spacing, disc_width);
2330 ext_try_break(actual_penalty, hyphenated_node,
2331 line_break_dir, adjust_spacing,
2332 par_shape_ptr, adj_demerits,
2333 tracing_paragraphs,
2334 protrude_chars, line_penalty,
2335 last_line_fit, double_hyphen_demerits,
2336 final_hyphen_demerits, first_p,
2337 vlink(cur_p));
2338 /*tex This does not work. */
2339 #if 0
2340 /*tex Go back to the starting situation. */
2341 do_one_seven_eight(sub_disc_width_from_active_width);
2342 do_one_seven_eight(reset_disc_width);
2343 /*tex Add select |no_break| to |active_width|. */
2344 s = vlink_no_break(vlink(cur_p));
2345 add_to_widths(s, line_break_dir, adjust_spacing, disc_width);
2346 ext_try_break(actual_penalty, hyphenated_node,
2347 line_break_dir, adjust_spacing,
2348 par_shape_ptr, adj_demerits,
2349 tracing_paragraphs,
2350 protrude_chars, line_penalty,
2351 last_line_fit, double_hyphen_demerits,
2352 final_hyphen_demerits, first_p,
2353 vlink(cur_p));
2354 #endif
2355 }
2356 do_one_seven_eight(sub_disc_width_from_active_width);
2357 }
2358 }
2359 s = vlink_no_break(cur_p);
2360 add_to_widths(s, line_break_dir, adjust_spacing, active_width);
2361 break;
2362 case penalty_node:
2363 ext_try_break(penalty(cur_p), unhyphenated_node, line_break_dir,
2364 adjust_spacing, par_shape_ptr, adj_demerits,
2365 tracing_paragraphs, protrude_chars,
2366 line_penalty, last_line_fit,
2367 double_hyphen_demerits, final_hyphen_demerits,
2368 first_p, cur_p);
2369 break;
2370 case boundary_node:
2371 case whatsit_node:
2372 /*tex Advance past a whatsit node in the |line_break| loop. */
2373 case mark_node:
2374 case ins_node:
2375 case adjust_node:
2376 break;
2377 case glue_spec_node:
2378 normal_warning("parbuilder","found a glue_spec in a paragraph");
2379 break;
2380 default:
2381 formatted_error("parbuilder","weird node %d in paragraph",type(cur_p));
2382 }
2383 cur_p = vlink(cur_p);
2384 while (cur_p == null && nest_index > 0) {
2385 cur_p = nest_stack[--nest_index];
2386 }
2387 }
2388 if (cur_p == null) {
2389 /*tex
2390
2391 Try the final line break at the end of the paragraph, and |goto
2392 done| if the desired breakpoints have been found.
2393
2394 The forced line break at the paragraph's end will reduce the list
2395 of breakpoints so that all active nodes represent breaks at
2396 |cur_p=null|. On the first pass, we insist on finding an active
2397 node that has the correct ``looseness.'' On the final pass, there
2398 will be at least one active node, and we will match the desired
2399 looseness as well as we can.
2400
2401 The global variable |best_bet| will be set to the active node for
2402 the best way to break the paragraph, and a few other variables
2403 are used to help determine what is best.
2404
2405 */
2406 ext_try_break(eject_penalty, hyphenated_node, line_break_dir,
2407 adjust_spacing, par_shape_ptr, adj_demerits,
2408 tracing_paragraphs, protrude_chars, line_penalty,
2409 last_line_fit, double_hyphen_demerits,
2410 final_hyphen_demerits, first_p, cur_p);
2411 if (vlink(active) != active) {
2412 /*tex Find an active node with fewest demerits; */
2413 r = vlink(active);
2414 fewest_demerits = awful_bad;
2415 do {
2416 if (type(r) != delta_node) {
2417 if (total_demerits(r) < fewest_demerits) {
2418 fewest_demerits = total_demerits(r);
2419 best_bet = r;
2420 }
2421 }
2422 r = vlink(r);
2423 } while (r != active);
2424 best_line = line_number(best_bet);
2425 /*tex
2426 Find an active node with fewest demerits;
2427 */
2428 if (looseness == 0)
2429 goto DONE;
2430 /*tex
2431
2432 Find the best active node for the desired looseness;
2433
2434 The adjustment for a desired looseness is a slightly more
2435 complicated version of the loop just considered. Note that if
2436 a paragraph is broken into segments by displayed equations,
2437 each segment will be subject to the looseness calculation,
2438 independently of the other segments.
2439
2440 */
2441 r = vlink(active);
2442 actual_looseness = 0;
2443 do {
2444 if (type(r) != delta_node) {
2445 line_diff = line_number(r) - best_line;
2446 if (((line_diff < actual_looseness)
2447 && (looseness <= line_diff))
2448 || ((line_diff > actual_looseness)
2449 && (looseness >= line_diff))) {
2450 best_bet = r;
2451 actual_looseness = line_diff;
2452 fewest_demerits = total_demerits(r);
2453 } else if ((line_diff == actual_looseness) &&
2454 (total_demerits(r) < fewest_demerits)) {
2455 best_bet = r;
2456 fewest_demerits = total_demerits(r);
2457 }
2458 }
2459 r = vlink(r);
2460 } while (r != active);
2461 best_line = line_number(best_bet);
2462 /*tex
2463 Find the best active node for the desired looseness.
2464 */
2465 if ((actual_looseness == looseness) || final_pass)
2466 goto DONE;
2467 }
2468 }
2469 /*tex Clean up the memory by removing the break nodes. */
2470 clean_up_the_memory();
2471 /*tex Clean up the memory by removing the break nodes. */
2472 if (!second_pass) {
2473 if (tracing_paragraphs > 0)
2474 tprint_nl("@secondpass");
2475 threshold = tolerance;
2476 second_pass = true;
2477 final_pass = (emergency_stretch <= 0);
2478 } else {
2479 /*tex If at first you do not succeed, then: */
2480 if (tracing_paragraphs > 0)
2481 tprint_nl("@emergencypass");
2482 background[2] += emergency_stretch;
2483 final_pass = true;
2484 }
2485 }
2486
2487 DONE:
2488 if (tracing_paragraphs > 0) {
2489 end_diagnostic(true);
2490 normalize_selector();
2491 }
2492 if (do_last_line_fit) {
2493 /*tex
2494 Adjust the final line of the paragraph; here we either reset
2495 |do_last_line_fit| or adjust the |par_fill_skip| glue.
2496 */
2497 if (active_short(best_bet) == 0) {
2498 do_last_line_fit = false;
2499 } else {
2500 width(last_line_fill) += (active_short(best_bet) - active_glue(best_bet));
2501 stretch(last_line_fill) = 0;
2502 }
2503 }
2504 /*tex
2505 Break the paragraph at the chosen. Once the best sequence of
2506 breakpoints has been found (hurray), we call on the procedure
2507 |post_line_break| to finish the remainder of the work. By introducing
2508 this subprocedure, we are able to keep |line_break| from getting
2509 extremely long.
2510
2511 the first thing |ext_post_line_break| does is reset |dir_ptr|.
2512
2513 */
2514 flush_node_list(dir_ptr);
2515 dir_ptr = null;
2516 ext_post_line_break(paragraph_dir,
2517 right_skip,
2518 left_skip,
2519 protrude_chars,
2520 par_shape_ptr,
2521 adjust_spacing,
2522 inter_line_penalties_par_ptr,
2523 inter_line_penalty,
2524 club_penalty,
2525 club_penalties_ptr,
2526 widow_penalties_ptr,
2527 widow_penalty,
2528 broken_penalty,
2529 final_par_glue,
2530 best_bet,
2531 last_special_line,
2532 second_width,
2533 second_indent, first_width, first_indent, best_line);
2534 /*tex
2535
2536 Clean up the memory by removing the break nodes.
2537
2538 */
2539 clean_up_the_memory();
2540 }
2541
2542 void get_linebreak_info (int *f, int *a)
2543 {
2544 *f = fewest_demerits;
2545 *a = actual_looseness;
2546 }