Documentation
¶
Index ¶
Constants ¶
const ( OrderPt uint8 = 0 // finite, in whatever unit the caller uses OrderFil uint8 = 1 OrderFill uint8 = 2 OrderFilll uint8 = 3 )
The glue orders TeX keeps apart (tex.web §16781-16782: "the available stretchability can be found in the subarray cur_active_width[2..5], in units of points, fil, fill, and filll").
⛔ THEY ARE NOT MAGNITUDES, THEY ARE CLASSES. A `plus 1fil` is not "a very large number of points": any amount of fil beats every amount of points, and a line carrying any of them has badness 0 (§16790-16793). A consumer that flattens fil to 1e6 points gets a large but FINITE badness, so a line TeX calls perfect comes out merely tolerable — and under \raggedright the whole first pass then fails and the hyphens appear (go-typeset/linebreak#12 item 1, seen from go-tex/engine).
⚠ SHRINK HAS NO ORDERS HERE, and that is tex.web's own word: §16806, "Shrinkability is never infinite in a paragraph". A \hskip 0pt minus 1fil does exist, but line_break never sees one in the background and the shrink column stays a single total.
const InfPenalty = 10000.0
InfPenalty is the "infinite" penalty: +InfPenalty forbids a break, −InfPenalty forces one (the end of a paragraph is a forced break).
const MaxBadRatio = 1e4
MaxBadRatio is the worst finite badness ratio the optimiser will consider: a line that is underfull with no stretch at all. Callers pass it as the tolerance for a last-resort pass that must return SOMETHING rather than fail. MaxBadRatio caps the adjustment ratio of a short line that has no stretch (the worst finite badness): the line is very bad but still finite, so an emergency pass with a large tolerance can accept it instead of collapsing the whole paragraph onto one line.
Variables ¶
This section is empty.
Functions ¶
func TeXBadness ¶ added in v1.13.0
TeXBadness is tex.web §108's badness(t,s): how hard glue of stretchability (or shrinkability) s must work to take up a shortfall (or excess) t, as an integer from 0 to inf_bad (10000). t and s are scaled points.
function badness(t,s:scaled):halfword; {compute badness, given t>=0}
begin if t=0 then badness:=0
else if s<=0 then badness:=inf_bad
else begin if t<=7230584 then r:=(t*297) div s
else if s>=1663497 then r:=t div (s div 297)
else r:=t;
if r>1290 then badness:=inf_bad
else badness:=(r*r*r+@'400000) div @'1000000;
end;
end;
The three branches are overflow guards for 32-bit Pascal integers, and they change results, so they are kept: 297³ = 99.94·2¹⁸ scales the cube to 100·(t/s)³, 7230584 is where t·297 would overflow, 1290³ < 2³¹ < 1291³. @'400000 and @'1000000 are OCTAL: 2¹⁷ (the rounding half) and 2¹⁸. A negative t is the caller's error (§108 says "given t>=0"), and answers inf_bad rather than a plausible number.
Types ¶
type Background ¶ added in v1.5.0
type Background struct {
Width float64 // widths, summed
Stretch [numOrders]float64 // stretch by order, as §16307-16315 sums them
Shrink float64 // shrink, summed (never infinite: §16806)
}
Background is the glue every line carries before its own material: in TeX, \leftskip + \rightskip. The zero value adds nothing, which is a justified paragraph with both skips at 0pt.
type Item ¶
type Item struct {
Kind ItemKind
Width float64
Height, Depth float64 // box only (glyph metrics)
R rune // box only (the glyph, 0 if none)
Stretch, Shrink float64 // glue only
StretchOrder uint8 // glue only: 0 = pt, 1 = fil, 2 = fill, 3 = filll
Penalty float64 // penalty only
Flagged bool // penalty only (e.g. a hyphen) — consecutive flags are penalised
}
Item is one element of a horizontal list.
func GlueOrder ¶ added in v1.5.0
GlueOrder is Glue whose stretch is of the given order: GlueOrder(0, 1, OrderFil, 0) is TeX's `\hskip 0pt plus 1fil`. Order OrderPt is exactly Glue.
type Line ¶
type Line struct {
Start, End int // item index range [Start, End) actually set on the line
Ratio float64 // glue adjustment ratio r (−1 fully shrunk … +tolerance stretched)
// Indent is the line's left margin, from the Measure the paragraph was
// broken with: 0 for every line of a uniform paragraph, and the hanging or
// \parshape margin otherwise.
//
// ⚠ IT IS NOT DERIVABLE FROM THE WIDTH. A negative \hangindent shortens
// the line and leaves the margin at ZERO — it indents from the right — so a
// consumer computing "hsize minus the width" would place those lines wrong
// (tex.web:16723-16724, :16729-16730). It is reported here so the rule
// lives once, in HangIndent, rather than once per caller.
Indent float64
// StretchOrder is the order Ratio is measured against: the HIGHEST order
// present on the line, since that one absorbs all of the slack and the
// lower ones are set at their natural width (tex.web §16620-16632, the same
// rule hpack uses).
//
// ⛔ A CONSUMER MUST READ IT TO SET THE LINE. `Ratio = 0.3` means "stretch
// every glue by 0.3 of its stretch" only when StretchOrder is OrderPt. At
// OrderFil it means "stretch the FIL glues by 0.3 of their fil and leave
// every finite glue alone" — distributing it over all the glues instead
// would spread a \raggedright line's slack through its interword spaces,
// which is precisely what \raggedright exists to prevent.
StretchOrder uint8
}
Line describes one output line of a broken paragraph.
func KnuthPlass ¶
KnuthPlass breaks items into lines of the given width, minimising total cost (linePenalty is charged once per line, which discourages breaking a paragraph into many short ones). It returns the chosen lines in order and ok=false if no sequence of feasible breaks exists within tolerance.
func KnuthPlassShaped ¶ added in v1.10.0
func KnuthPlassWith ¶ added in v1.1.0
KnuthPlassWith is KnuthPlass with the costs stated explicitly, for a caller that threads a document's own \adjdemerits and friends.
The measure is one width for the whole paragraph, which is right for the overwhelmingly common case. A paragraph with \hangindent or \parshape needs a width PER LINE: see KnuthPlassShaped.
type Measure ¶ added in v1.10.0
type Measure interface {
// LineShape reports the left margin and the width available to line n of
// the paragraph, numbered from 1.
//
// ⚠ ONE METHOD RETURNING BOTH, deliberately. tex.web computes them
// together from the same three parameters and the sign rules couple them:
// a negative \hangindent shortens the line and leaves the margin at zero,
// so a caller that derived the margin separately would have to restate
// that rule and could get it wrong on its own. Breaking needs only the
// width; the margin is here so the caller that places the line does not
// have to re-derive it.
LineShape(n int) (indent, width float64)
}
A Measure gives a paragraph its shape: the left margin and the width available to each line. TeX recomputes both FOR EVERY LINE — the width is an input to the badness of every candidate break, not a constant of the paragraph — which is what makes \hangindent and \parshape line-breaking parameters rather than placement ones (tex.web §847-850, lines 16676-16748).
⛔ A SCALAR MEASURE CANNOT EXPRESS EITHER OF THEM, and the consequence is not only a missing indent: four ems more text on the first line re-breaks the whole paragraph, so a phrase that lands on the reference's line 4 lands on line 3 instead. Lines gained or lost at the end of a paragraph become pages gained or lost (go-typeset/linebreak#11, from a consumer measuring against tectonic).
func HangIndent ¶ added in v1.10.0
HangIndent is \hangindent with \hangafter, read from tex.web:16719-16732 rather than from the usual description of it:
last_special_line:=abs(hang_after); if hang_after<0 then begin first_width:=hsize-abs(hang_indent); if hang_indent>=0 then first_indent:=hang_indent else first_indent:=0; second_width:=hsize; second_indent:=0; end else begin first_width:=hsize; first_indent:=0; second_width:=hsize-abs(hang_indent); if hang_indent>=0 then second_indent:=hang_indent else second_indent:=0; end;
So two rules that are easy to get wrong, and are therefore encoded once here:
- ⛔ THE SIGN OF indent IS NOT THE SIGN OF THE MARGIN. The line is always shortened by |indent|; the margin is indent only when it is positive, and 0 when it is negative. A negative \hangindent indents from the RIGHT.
- ⛔ after < 0 MEANS "THE FIRST |after| LINES", not "after none of them": the indented lines are 1..|after|, where a non-negative after indents lines after+1, after+2, …
tex.web:16689 also notes that "if hang_indent=0, the value of hang_after is irrelevant", which falls out of the arithmetic here rather than being special-cased.
func ParShape ¶ added in v1.10.0
ParShape is \parshape: an explicit margin and width per line.
⛔ THE LAST PAIR REPEATS FOR EVERY LINE BEYOND THE LIST, which is why a Measure is an interface and not a slice — the sequence is unbounded. tex.web:16680-16681: "the other 2n words contain the left margins and line lengths for the first n lines of the paragraph; the specifications for line n apply to all subsequent lines."
An empty list is Uniform(0): \parshape=0 is how TeX turns the shape off, and the caller that means "no shape" should say Uniform.
type Params ¶ added in v1.1.0
type Params struct {
// ScaledPointsPerUnit asks for tex.web §108's integer badness (TeXBadness)
// instead of the float 100·r³, and says how many scaled points one unit of
// every width, stretch and shrink handed in is: 1 when they are already
// scaled points, 65536 when they are TeX points. Each is multiplied by it
// and rounded to an integer sp before §108 sees it, which is exact for any
// value that is a whole number of sp (a power-of-two division like
// sp/65536 round-trips). Zero, the default, is the unit-free float that
// non-TeX consumers have always had.
ScaledPointsPerUnit float64
Tolerance float64 // \tolerance: the worst BADNESS a line may have (100·ratio³)
LinePenalty float64 // \linepenalty: charged once per line, so fewer lines cost less
AdjDemerits float64 // \adjdemerits: adjacent lines two fitness classes apart
DoubleHyph float64 // \doublehyphendemerits: two hyphenated lines in a row
FinalHyph float64 // \finalhyphendemerits: a hyphen on the last line but one
// Trace receives TeX's own \tracingparagraphs log, or nothing when nil.
//
// ⛔ THE FORMAT IS tex.web's, TO THE CHARACTER, BECAUSE ITS WHOLE VALUE IS
// BEING DIFFABLE AGAINST THE REFERENCE. A divergence in line breaking is
// otherwise inferred from glyph positions three layers downstream; with this
// the two engines state their own reasons — the badness, the penalty and the
// demerits of every break each one considered — and the first line that
// differs is the divergence.
//
// Two line kinds, and a caller writes the pass markers (@firstpass,
// @secondpass, @emergencypass) around its own passes, since it is the caller
// that runs them:
//
// @\discretionary via @@0 b=131 p=50 d=11781 a feasible break (:16854-16875)
// @@1: line 1.2- t=11781 -> @@0 a new active node (:16664-16674)
//
// `*` stands for "past inf_bad" in b and for artificial_demerits in d, as in
// TeX. The fitness digit is TeX's own numbering, which this package already
// shares: 0 very loose, 1 loose, 2 decent, 3 tight (:16099-16105). The `-`
// after it marks a hyphenated break.
//
// ⚠ What it does NOT reproduce is §16877's short_display of the material
// between breaks: this package is handed items and never the text, so the
// words TeX prints above each break line have no counterpart here. A diff
// against a real TeX log has to ignore those, which is why they are left out
// rather than approximated.
Trace io.Writer
// FinalPass turns on TeX's last resort: artificial_demerits.
//
// ⛔⛔ WITHOUT IT AN OVERFULL SINGLE LINE BEATS TWO INFEASIBLE SHORT ONES, and TeX
// chooses the other way. tex.web §16769-16771: the deactivation at an impossible
// line is guarded by "and |goto deactivate| UNLESS there is a reason to consider
// lines of text from |r| to |cur_p|", and the reason is
//
// if final_pass and (minimum_demerits=awful_bad) and
// (link(r)=last_active) and (prev_r=active) then
// artificial_demerits:=true {set demerits zero, this break is forced}
// else if b>threshold then goto deactivate;
//
// — when nothing feasible has been recorded at this breakpoint and r is the ONLY
// active node, the break is recorded at ZERO cost. Zero is what makes it win:
// badness past inf_bad costs 1e8 per line, so two hopeless lines (2e8) otherwise
// lose to one overfull line (1e8).
//
// Measured in go-tex/engine: two unbreakable 35pt words with a 3pt rigid space on
// a 40pt measure. Neither line can be set — each is 5pt short with nothing to
// stretch — and the reference puts them on TWO lines. Without this flag the
// breaker returned ONE line 33pt over the margin, because it cost half as much.
//
// It is the caller's business because the PASSES are: \pretolerance, then
// \tolerance, then the emergency pass. Only the last one may fall back, and only
// the caller knows which pass it is running.
FinalPass bool
// EmergencyStretch is \emergencystretch: extra FINITE stretch given to every
// line, and only on the final pass (tex.web §863 adds it to background[2],
// the finite slot, when that pass is entered).
//
// ⛔⛔ IT IS NOT A LOOSER TOLERANCE, AND SUBSTITUTING ONE IS A DIFFERENT
// ALGORITHM. A consumer without this knob raises \tolerance instead — go-tex's
// paragraph.go:251-258 sets it to its maximum — which ACCEPTS arbitrarily bad
// lines at the original glue. This makes the lines GOOD instead: the same
// paragraph that was infeasible at ratio 5 (badness 12500) is set at ratio 1
// (badness 100) once the stretch is actually there. Both "succeed"; they
// choose different breaks and charge different demerits, because badness is
// cubic in the ratio and the ratio is what changed.
//
// ⚠ FINITE, order 0, deliberately. Infinite stretch would make every line
// badness 0 (§16790-16793) and the emergency pass would stop discriminating
// between breaks at all — which is \raggedright, not an emergency pass.
//
// It is added once per line rather than as an item because that is what a
// background is: §16307-16315 seeds active_width with it before any item is
// walked. A caller running the first two passes leaves this zero.
EmergencyStretch float64
// Looseness is \looseness: how many lines longer (or, negative, shorter) the
// paragraph should come out than the breaking would otherwise make it
// (tex.web:17197-17237).
//
// ⛔⛔ IT DOES NOT RE-BREAK THE PARAGRAPH. Every feasible way of ending the
// paragraph is already an active node when the last break is tried; TeX picks
// the one with fewest demerits, calls its line count best_line, and then — only
// if \looseness is non-zero — walks the SAME nodes again looking for one whose
// line count differs from best_line in the direction asked for:
//
// line_diff:=line_number(r)-best_line;
// if ((line_diff<actual_looseness)and(looseness<=line_diff))or
// ((line_diff>actual_looseness)and(looseness>=line_diff)) then
// begin best_bet:=r; actual_looseness:=line_diff; … end
// else if (line_diff=actual_looseness)and(total_demerits(r)<fewest_demerits)…
//
// So it is a CHOICE among breakings that already exist, not a second search,
// and a paragraph with only one feasible ending cannot be loosened at all.
//
// ⛔ AND WHEN THE LOOSENESS CANNOT BE MATCHED, THE PASS FAILS. tex.web:17203 is
// `if (actual_looseness=looseness)or final_pass then goto done` — otherwise the
// pass ends without a result and the next, looser one runs, because a looser
// threshold admits more active nodes and therefore more line counts to choose
// between. That is reported here the way this package reports any failed pass:
// ok=false, with FinalPass accepting whatever was achieved. A caller that runs
// only one pass and sets Looseness must set FinalPass with it, or a paragraph
// it cannot loosen comes back as no paragraph.
Looseness int
// Background is what every line carries before its own material: TeX's
// \leftskip and \rightskip, which are added to EVERY line rather than
// appearing in the item list (tex.web §16307-16315, verbatim):
//
// q:=left_skip; r:=right_skip; background[1]:=width(q)+width(r);
// background[2+stretch_order(q)]:=stretch(q);
// background[2+stretch_order(r)]:=background[2+stretch_order(r)]+stretch(r);
// background[6]:=shrink(q)+shrink(r);
//
// ⛔ THIS IS WHAT MAKES \raggedright WORK, and it has to be here rather
// than in the caller. \raggedright is \rightskip = 0pt plus 1fil: every
// line then carries fil stretch, every line has badness 0 (§16790-16793),
// and TeX's FIRST pass — no hyphenation, at \pretolerance — succeeds
// outright. A consumer that breaks the paragraph justified and adds the
// skips afterwards gets the hyphens of a justified paragraph with ragged
// glue painted on top (go-tex/engine#583 and its paragraph.go:215-241,
// which had to guess at this by opening the tolerance instead).
Background Background
}
Params carries the costs TeX charges besides the line's own badness. The zero value is not useful; DefaultParams holds the values every LaTeX document runs with (latex.ltx:498-514).
func DefaultParams ¶ added in v1.1.0
DefaultParams are LaTeX's own settings (latex.ltx:498-514): \tolerance=200, \linepenalty=10, \adjdemerits=10000, \doublehyphendemerits=10000, \finalhyphendemerits=5000.