GNU TeXmacsUser manualReferenceAboutEnglish
Concatenation, line breaking and paragraph formatting

1.The formatter data structures

The intermediate results of the typesetter are described by a few small classes in

Typeset/Format/

and Kernel/Types/.

1.1.Spaces

A space (

Kernel/Types/space.hpp

) is a triple of lengths min, def and max: the minimal, default and maximal extent of a stretchable space, in the internal unit SI. Spaces can be added, subtracted, multiplied by scalars and compared with max. They are used both for horizontal glue between the items on a line and for vertical glue between lines and paragraphs.

1.2.Line items

The concater produces arrays of line_items (

Typeset/Format/line_item.hpp

):

class line_item_rep: public concrete_struct {
public:
  int        type;      // the type of the line item
  int        op_type;   // operator type for mathematical symbols
  box        b;         // the box
  space      spc;       // separation space
  int        penalty;   // penalty for a linebreak after this line_item
  bool       limits;    // line items has limits
  language   lan;       // language for hyphenating strings
  tree       t;         // for control items
  …
};

Each item holds a box together with the space which follows it and the penalty for breaking the line after it. Penalties are integers; the constants HYPH_STD (\(10^4\)), HYPH_PANIC (\(10^6\)) and HYPH_INVALID (\(10^8\), meaning forbidden) are defined in

System/Language/language.hpp

. The main item types are:

STRING_ITEM

A piece of text in a single font (a text_box), which may be hyphenated using the language lan.

STD_ITEM

Any other box (an inline formula, an image, a fraction, a table, …).

MARKER_ITEM

An invisible zero-width box which marks a source position, for instance the border of an inline tag; it gives the cursor a place to stand.

CONTROL_ITEM

A zero-width item carrying a command in its field t: forced line breaks (next-line, line-break, new-line), tabulations (htab), vertical spaces, page-break directives, local changes of paragraph or page parameters (tuples env_par and env_page), and decorations (datoms).

FLOAT_ITEM

A float, footnote or if-page-break content; its box is a control_box wrapping a lazy vertical stream which will be handed to the page breaker.

NOTE_LINE_ITEM, NOTE_PAGE_ITEM

Marginal notes.

LEFT_BRACKET_ITEM, MIDDLE_BRACKET_ITEM, RIGHT_BRACKET_ITEM

Large delimiters whose size is determined after the whole line has been concatenated.

LSUB_ITEM, LSUP_ITEM, RSUB_ITEM, RSUP_ITEM

Scripts, which are glued to their neighbours during post-processing, producing GLUE_LSUBS_ITEM, GLUE_RSUBS_ITEM, GLUE_LEFT_ITEM, GLUE_RIGHT_ITEM or GLUE_BOTH_ITEM.

OBSOLETE_ITEM

An item which has been absorbed by another one and will be removed.

1.3.Page items and stack borders

After line breaking, each line becomes a page_item (

Typeset/Format/page_item.hpp

):

class page_item_rep: public concrete_struct {
public:
  int          type;    // the type of the page item
  box          b;       // the box
  space        spc;     // separation space
  int          penalty; // penalty for a linebreak after this page_item
  array<lazy>  fl;      // floating objects attached to this item
  int          nr_cols; // number of columns
  tree         t;       // for page control items
  …
};

The type is PAGE_LINE_ITEM for ordinary lines, PAGE_HIDDEN_ITEM for invisible material of height zero, PAGE_CONTROL_ITEM for page commands (page-break, new-page, new-dpage and env_page tuples, stored in t) and PAGE_NOTE_ITEM. The space spc is the vertical glue between the bottom of this line and the top of the next one; the penalty is the cost of a page break after the line. Floats and footnotes whose anchor lies on the line are attached in fl.

A stack_border (

Typeset/Format/stack_border.hpp

) describes how a block of page items interacts with the blocks above and below it: the default baseline distance height, the separation parameters sep, hor_sep, ver_sep, the corresponding values for the first line (height_before etc.), the pending vertical spaces vspc_before and vspc_after, and the flags nobr_before and nobr_after forbidding page breaks at the borders. It allows the typesetter to combine the page items of consecutive paragraphs without re-typesetting them (merge_stack).

1.4.Formats and lazy structures

The file

Typeset/formatter.hpp

defines a small protocol for material which cannot be typeset before its width is known, such as the contents of floats, of multi-paragraph table cells and of GUI containers. A lazy is a partially typeset object of a certain lazy_type (LAZY_PARAGRAPH, LAZY_DOCUMENT, LAZY_TABLE, LAZY_VSTREAM, LAZY_BOX, …). It supports two operations:

lazy lazy_rep::produce (lazy_type request, format fm)
(continue formatting)

Formats the structure further according to fm and returns a lazy structure of type request. For instance, a paragraph asked for a LAZY_VSTREAM with a format_vstream of a given width breaks its lines and returns a lazy_vstream of page items; a vertical stream asked for a LAZY_BOX stacks its lines into a box.

format lazy_rep::query (lazy_type request, format fm)
(ask for formatting information)

Returns information needed before production. The only query currently in use is QUERY_VSTREAM_WIDTH, answered by a format_width holding the natural width of a paragraph or table; it is used to size table columns.

The format classes (

Typeset/Format/format.hpp

) are format_none, format_width, format_cell (width, vertical alignment, depth and height of a cell), format_vstream (width plus line items to put before and after) and query_vstream_width. The function make_lazy in

Typeset/Line/lazy_typeset.cpp

plays for lazy structures the role that make_bridge plays for bridges: it dispatches on the tag and builds a lazy_document, lazy_surround, lazy_table, a lazy paragraph, etc. Lazy structures are built from scratch each time: they are not incremental.

2.The concater

2.1.Entry points

The concater (

Typeset/Concat/concater.hpp

) turns a tree into an array of line items. A concater_rep holds the environment, the array a of items being produced and a flag rigid which is set when the result will surely not be broken into lines. It is used through the following functions:

array<line_item> typeset_concat (edit_env env, tree t, path ip)
(line items of a paragraph)

Typesets t and post-processes the result (finish). This is the input of the paragraph formatter.

box typeset_as_concat (edit_env env, tree t, path ip)
(typeset on a single line)

Uses a rigid concater and joins the items into a concat_box, using the default width of the separating spaces. This is used for all inline material which is not broken into lines: arguments of fractions, scripts, table cells in text mode, headers and footers, etc. The variant typeset_as_box wraps the result in a composite_box; typeset_as_atomic also handles with and locus at the top level.

array<line_item> typeset_marker (edit_env env, path ip)
(a marker item)

Returns a single MARKER_ITEM for the source position ip. Used by the bridges to add cursor positions around structural tags.

2.2.Traversal

concater_rep::typeset (tree t, path ip) in

Typeset/Concat/concater.cpp

is a large switch on the label of t. Strings are handled according to the current mode (env->mode): text, mathematics or program code. Compound trees are dispatched to specialized methods, spread over several files:

concat_text.cpp

Strings, concat, document and para nested inside a line (typeset as a stacked box with typeset_as_stack resp. typeset_as_paragraph), spaces, moves and resizes, floats, notes, datoms/dlines/dpages.

concat_math.cpp

Brackets, big operators, scripts, fractions, roots, wide accents, trees and inline tables.

concat_macro.cpp

The macro primitives: assign, with, compound (macro application), arg, value, mark, eval, …

concat_active.cpp
,
concat_inactive.cpp

Other active markup (conditionals, loci, references, specific, flags) and source-mode rendering.

concat_graphics.cpp
,
concat_animate.cpp
,
concat_gui.cpp

Graphics, animations, and GUI containers.

Inline macro applications are expanded by the concater itself: typeset_compound looks up the macro, pushes the argument bindings onto env->macro_arg and env->macro_src, and typesets the body attach_right (f[n], ip), surrounded by markers for descend (ip, 0) and descend (ip, 1). When an arg is met in the body, typeset_argument typesets the argument value with its original inverse path, so that it remains editable. Similarly, typeset_with changes the environment with write_update, typesets the body between two markers and restores the old values. The evaluation machinery itself is the subject of macro expansion.

2.3.Strings, spacing and penalties

Strings are cut into words and spaces by the language of the environment. language_rep::advance (tree t, int& pos) advances pos over the next token and returns a text_property which describes it: the kind of space to insert before and after (spc_before, spc_after, as indices SPC_* into a table of spaces obtained from the font), the penalties for breaking before and after (pen_before, pen_after), and, in mathematics, the operator type op_type, the limits behaviour and an optional macro for rendering.

In text mode, typeset_text_string emits a STRING_ITEM per word (typeset_substring). Spaces do not become items: they are added to the spc field of the previous item (print (space) takes the maximum of the old and new space), and the penalty of that item is lowered to the one of the space with penalty_min, which makes the space a legal breakpoint. The table of spaces is env->fn->get_normal_spacing (env->spacing_policy).

In math mode, typeset_math_string in addition consults the table succession_status to suppress spaces between operators that should not be separated (for instance a prefix minus after an infix operator), forbids breaks after infix operators when their space is removed, and uses narrow or wide spacing in condensed and display style. Program mode (typeset_prog_string) colors tokens according to the syntax highlighting of the language.

Other commands influence penalties directly: line-break sets the penalty of the previous item to 0, no-break sets it to HYPH_INVALID, and typeset_hgroup temporarily replaces the language by hyphenless_language (env->lan) and forbids breaks inside the group.

2.4.Post-processing

When the traversal is over, concater_rep::finish in

Typeset/Concat/concat_post.cpp

performs four passes over the item array:

  1. kill_spaces removes the spaces adjacent to control items at the borders, around forced line breaks and around env_par and env_page controls.

  2. pre_glue merges a subscript immediately followed by a superscript (or conversely) into a single script item.

  3. handle_brackets matches left and right bracket items. For each matching pair, handle_scripts glues scripts to their base (the item before or after them) and handle_matching computes the vertical extent of the enclosed material, resizes the brackets accordingly, and increments the penalties of all enclosed items. As a consequence, line breaks are more expensive inside nested brackets.

  4. clean_and_correct removes obsolete items and inserts italic corrections between adjacent boxes.

3.Paragraph formatting

3.1.From line items to page items

A paragraph of the document is formatted by typeset_stack in

Typeset/Line/lazy_paragraph.cpp

:

array<page_item>
typeset_stack (edit_env env, tree t, path ip,
               array<line_item> a, array<line_item> b,
               stack_border& sb)
{
  lazy_paragraph par (env, ip);
  par->a= a;
  par->a << typeset_concat_or_table (env, t, ip);
  par->a << b;
  par->format_paragraph ();
  sb= par->sss->sb;
  return par->sss->l;
}

The arrays a and b are the surroundings accumulated by the bridges (markers, parts of surround). The function typeset_concat_or_table calls the concater, except for a top-level table, which is typeset row by row with typeset_as_var_table so that it can be broken across pages (each row becomes an item followed by a next-line control).

The constructor of lazy_paragraph_rep reads all paragraph parameters from the environment: par-mode (mode: justify, left, center, right), par-flexibility, par-hyphen, the width and margins (width, left, right, first indentation), the line and paragraph separations (line_sep, par_sep), the shoving parameters (sep, hor_sep, ver_sep), the number of columns, and the micro-typographic parameters kreduce, kstretch, contraction, expansion and protrusion. The lines produced are sent to a stacker_rep, stored in the field sss.

3.2.Units and lines

lazy_paragraph_rep::format_paragraph splits the item array into paragraph units at every new-line control. For each unit it determines the style parameters in force (local changes of par-first or par-no-first are passed as env_par control items), formats the unit with format_paragraph_unit, ends the last line with penalty 0 and calls sss->new_paragraph (par_sep).

format_paragraph_unit further splits the unit at next-line controls, which force a line break without starting a new paragraph, and calls line_units on each part. The latter computes the optimal break points with line_breaks (see below), and then produces the lines one by one:

The phrase boxes produced here are the ones used to detect changed regions of the screen; see incremental typesetting.

4.The line breaking algorithm

4.1.Break points

The line breaker lives in

Typeset/Line/line_breaker.cpp

. Its interface is:

array<path> line_breaks (array<line_item> a, int start, int end, SI line_width, SI large_width, SI first_spc, SI last_spc, bool ragged)
(compute line breaks)

Returns the sequence of break points for the items a[start], …, a[end-1], starting with path (start) and ending with path (end). The parameter first_spc is the indentation of the first line and last_spc a space to be reserved at the end of the last line. large_width is a width beyond which no line may extend even with maximal shrinking of glyphs and kerning.

A break point is represented by a path. The path (i) means a break before item i. A longer path (i, j) means a break inside the string item i, after hyphenation position j; further elements denote successive hyphenations of the remainder of the same item (a very long word may be broken more than once). The helper hyphenate (item, pos, item1, item2) splits a string item at a hyphenation position into the part before the break (including the hyphen, with the hyphenation penalty) and the part after it.

4.2.The optimal algorithm

By default (par-hyphen is professional), the breaks are computed by line_breaker_rep::compute_breaks, a dynamic programming algorithm in the spirit of the one of TeX. For each reachable break point p, the hashmap best stores an lb_info: the best previous break prev, the accumulated penalty pen and the accumulated spacing cost pen_spc. Solutions are compared lexicographically (test_better): a smaller total penalty always wins, and the spacing cost only decides between solutions with equal penalties.

process (pos) considers the lines that start at pos. It walks over the subsequent items, accumulating the width of the line as a space (sum of the box widths and the stretchable separating spaces). For each item with a penalty below HYPH_INVALID, and for forced line-breaks, it calls propose_break. When the line becomes too long and the current item is a string of more than four characters, break_string additionally proposes breaks at its hyphenation points. The walk stops at the first proposed break for which the minimal width of the line exceeds large_width. Finally, process recurses into the break points inside the first item which have been reached.

propose_break (new_pos, old_pos, pen, spc) proposes a line from old_pos to new_pos of width spc. During the first pass, a line is acceptable if it can be shrunk or stretched to the line width (spc->min <= line_width <= spc->max); the last line only needs to be short enough. Its cost is the square of the difference between its natural width and the line width, in pixels (zero for the last line), and its penalty is the one of the break. The total penalty is capped at HYPH_INVALID.

compute_breaks runs the first pass over all items. If no acceptable solution reaches the end (best [path (end)]->pen == HYPH_INVALID), a second pass accepts underfull and overfull lines with penalty HYPH_INVALID and a cost growing quadratically with the amount by which they are too short or too long; lines exceeding large_width receive a huge extra cost. The solution is then read back from path (end) through the prev links (get_breaks). A last fix avoids a final line consisting only of empty boxes.

Note that line_breaks adds a tolerance of 5 units to the line width to absorb rounding errors when box widths add up to exactly one par.

4.3.The greedy algorithm

If par-hyphen is normal, ragged is true and compute_ragged_breaks is used instead. Starting from the beginning of the paragraph, next_ragged_break fills the line with as many items as fit, then backtracks to the last position where a break is allowed, trying hyphenation of the overflowing word first. empty_line_fix avoids lines containing only zero-width items.

4.4.Hyphenation hooks

The line breaker never interprets words itself. It relies on two virtual methods of language_rep (

System/Language/language.hpp

):

Natural languages implement them with hyphenation patterns (

System/Language/hyphenate.cpp

); programming languages allow breaks only at certain characters. A new language, or a new hyphenation strategy, therefore only has to implement these methods (together with advance, which determines word boundaries, spaces and break penalties between words). The wrapper hyphenless_language disables hyphenation.

5.Vertical stacking

The stacker_rep (

Typeset/Stack/stacker.hpp

) collects the lines of a paragraph into an array l of page items and maintains the border properties sb. Its methods are called by the paragraph formatter:

print (box b, array<lazy> fl, int nr_cols)

Appends a line. The vertical space between the previous line and the new one is computed by the static function shove (the flag unit_flag, which could suppress this, is never set in the current code).

print (tree t, int nr_cols, bool before)

Appends a page control item (after the current line unless before is true).

print (space spc), penalty (int pen)

Add vertical space or set the penalty after the last real line.

vspace_before, vspace_after, no_page_break_before, no_page_break_after, no_break_start, no_break_end

Record the effect of vspace*, vspace, no-page-break*, no-page-break and of no-break regions.

new_paragraph (space par_sep)

Closes a paragraph unit: adds the paragraph separation and pending vertical spaces, and multiplies the penalties of the first and last lines of the unit by 100 and of the second and next-to-last lines by 10. This implements widow and orphan control: breaking a page one or two lines away from a paragraph border is expensive.

shove determines the distance between two successive lines. If the lines are far enough apart for the default baseline distance height, it simply uses it. Otherwise, it tries to shove the lines into each other: shove_in computes, column by column, the vertical distance needed to keep the ink of the two lines at least ver_sep apart, taking into account a horizontal separation hor_sep. Thus a line with a tall formula only pushes the next line down if the formula actually collides with something below it. The optional swell parameters increase the separation for lines with large mathematical content.

merge_stack (l, sb, l2, sb2) appends the page items l2 of a paragraph to those of the preceding material l, applying shove between the last line of l and the first line of l2, adding the larger of the pending vertical spaces sb->vspc_after and sb2->vspc_before, and forbidding a page break if one of the two sides requires it. This is how typesetter_rep::insert_stack assembles the cached paragraphs into the page items of the whole document.

Two simpler functions are used for vertical material inside lines: typeset_as_stack (in

Typeset/Stack/stacker.cpp

) stacks the children of a document each typeset on a single line, and typeset_as_paragraph (in

Typeset/Line/lazy_vstream.cpp

) formats a paragraph with a lazy_paragraph and returns the lines as a single box with format_vstream_as_box.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".