linebreak

package module
v1.13.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: BSD-3-Clause Imports: 3 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

linebreak

License Go Coverage

Optimal line breaking for Go — pure Go, no cgo, no dependencies.

Give it a sequence of boxes, glue and penalties and a line width; it returns the breakpoints that minimise the total cost of the paragraph.

Why not just fill lines greedily

A greedy breaker decides each line without looking ahead, so one tight line early forces a bad one later, and the ragged edge wanders. This one treats the paragraph as a whole: every legal breakpoint is a node, every candidate line is an edge weighted by how far its spaces had to stretch or shrink, and the answer is the path of least total cost. Hyphenation points, forced breaks and discouraged breaks all enter as penalties, so a caller controls the outcome without special cases.

The algorithm is Knuth and Plass, Breaking Paragraphs into Lines (1981) — the same one behind the paragraphs people find noticeably even.

Useful wherever text is laid out and the result is looked at: PDF generation, e-book rendering, terminal and console formatting, SVG text, a UI toolkit's text layout.

Use

import "github.com/go-typeset/linebreak"

items := []linebreak.Item{
    linebreak.Box(30),                  // a word, 30 units wide
    linebreak.Glue(10, 5, 3),           // a space: 10 wide, may stretch 5, shrink 3
    linebreak.Box(45),
    // End a paragraph the way TeX does (tex.web §16077-16084): an INFINITE penalty,
    // then the finishing glue, then the forced break. The infinite penalty is not
    // decoration — §16070 says the \parfillskip "is preceded by an infinite penalty,
    // so it will never be considered as a potential breakpoint". Leave it out and that
    // glue IS a legal breakpoint (a glue after a box), which offers one break TeX never
    // offers, right at the end. A trailing glue should be REPLACED by the penalty
    // rather than kept, since "spaces usually precede blank lines" (§16068).
    linebreak.Penalty(0, linebreak.InfPenalty, false),
    // \parfillskip = 0pt plus 1fil. Since v1.5.0 say `fil` and mean it:
    // GlueOrder(0, 1, linebreak.OrderFil, 0). `Glue(0, 1e6, 0)` still works and
    // is still a large FINITE stretch, which is not the same thing — see below.
    linebreak.GlueOrder(0, 1, linebreak.OrderFil, 0),
    linebreak.Penalty(0, -linebreak.InfPenalty, false), // forced break: end of paragraph
}

lines, ok := linebreak.KnuthPlass(items, 100 /*line width*/, 1 /*tolerance*/, 10 /*line penalty*/)
if !ok {
    // no set of breaks fits within the tolerance; retry with linebreak.MaxBadRatio
}
for _, l := range lines {
    // l.Start, l.End index into items; l.Ratio is the space adjustment
    // (>0 stretched, <0 shrunk, 0 exact).
}

Glyph(r, w, h, d) is a box that also carries its rune and vertical metrics, for callers that draw what they measure.

Units are yours. The algorithm never looks at what a width means — points, pixels, ems or terminal columns all work, as long as one paragraph is consistent.

Glue orders, and the background every line carries (v1.5.0)

TeX keeps stretch in four separate columns — points, fil, fill, filll (tex.web §16781-16782) — and Item.StretchOrder now says which one a glue is in. GlueOrder(w, stretch, order, shrink) is the constructor; Glue is order OrderPt, so nothing written before this changes.

⛔ An order is a class, not a large number. Any amount of fil beats every amount of points, and §16790-16793 is unconditional about what that does to a line:

if (cur_active_width[3]<>0)or(cur_active_width[4]<>0)or(cur_active_width[5]<>0)
  then begin b:=0; fit_class:=decent_fit; {infinite stretch} end
else … b:=badness(shortfall,cur_active_width[2]) …

No badness is computed at all: a line carrying any infinite stretch is perfect, however short it is, and therefore feasible at every tolerance — including 0. Flattening plus 1fil into the finite column instead gives a large but finite badness, so a line TeX calls perfect comes out merely tolerable. That was this package's item (1) in #12, and the visible cost was in its consumer: under \raggedright the first pass failed and a paragraph came out with the hyphens of a justified one.

⚠ Shrink has no orders, and that is tex.web's own sentence (§16806): "Shrinkability is never infinite in a paragraph". fil can only pull a line wider, so an overfull line reports OrderPt and a negative Ratio whatever infinite stretch it also carries.

Params.Background is \leftskip + \rightskip, added to every line before its own material, exactly as §16307-16315 seeds active_width:

p := linebreak.DefaultParams(200, 10)
p.Background.Stretch[linebreak.OrderFil] = 1   // \raggedright
p.Background.Width = 20                        // a 20-wide \leftskip narrows every line

That is what makes \raggedright work rather than merely look right: with \rightskip = 0pt plus 1fil every line has badness 0, so TeX's first pass — which has no hyphenation at all — succeeds and no word is ever broken. A caller that breaks the paragraph justified and adds the skips afterwards gets ragged glue painted over justified breaks.

⚠ Line.Ratio is read together with Line.StretchOrder. The order is the highest one present on that line, and it alone takes up the slack. Ratio = 0.3 at OrderPt means "stretch every glue by 0.3 of its stretch"; at OrderFil it means "stretch the fil glues by 0.3 of their fil and leave every finite glue at its natural width". Distributing it over all the glues would spread a \raggedright line's slack through its interword spaces — the one thing \raggedright exists to prevent.

A forced break is mandatory. A Penalty of −InfPenalty is not a strong preference: every active node is deactivated there (tex.web §16769), so no line spans it. The paragraph's last line ends at the last forced penalty in the list.

But mandatory is not unconditional, and a pass can fail at one. tex.web §16769 reads, in full:

if (b>inf_bad)or(pi=eject_penalty) then
  begin if final_pass and (minimum_demerits=awful_bad) and
     (link(r)=last_active) and (prev_r=active) then
    artificial_demerits:=true
  else if b>threshold then goto deactivate;
  node_r_stays_active:=false;
  end
else begin prev_r:=r; if b>threshold then goto continue; … end;

goto deactivate skips the recording. A forced break whose line is past the tolerance is therefore not taken, and a pass that has no other break fails — which is how TeX reaches its next pass. Up to v1.3.0 this package recorded every forced break however badly its line fitted, so such a pass returned ok with a bad line in it and a caller had to inspect the lines to find out. ⛔ A caller that relied on that must now run the next pass, which is what tex.web does and what the parameters are for.

A line a \\ ends carries \hfil (LaTeX's \\ is \unskip \nobreak \hfil \break), so in real input a forced break's line is feasible at any tolerance. Emit that glue: a forced penalty after rigid material is input TeX would not set either.

An overfull line's ratio is negative. Ratio below −1 means the line is longer than the measure by more than its shrink can absorb, and −Inf means it cannot shrink at all. The sign is the contract: r >= -1 is the test for "this line can be set", and an unshrinkable overfull line must fail it. An underfull line with nothing to stretch is MaxBadRatio, deliberately finite — TeX gives it b := inf_bad, which does not exceed inf_bad, so such a line is bad but still usable.

Params.FinalPass arms TeX's artificial_demerits (§16824-16831): the break is taken at zero cost instead of the node being deactivated, when all four of these hold — and the first is the one that is easy to drop:

  1. the line is hopeless or the break is forced (b > inf_bad, here Ratio < −1, or pi = eject_penalty). The clause lives inside that branch. At an ordinary breakpoint merely past the tolerance tex.web says goto continue: do not record, keep the node active;
  2. nothing feasible has been recorded at this breakpoint;
  3. it is the only active node;
  4. FinalPass is set.

⛔ Set it only on a genuine final pass, after the earlier passes failed, and keep the tolerance as it was — raising the tolerance makes a hopeless line feasible at its full cost, which defeats the clause. A caller that arms it on every pass, or that drops condition (1), will see breaks TeX never takes.

⚠ And "final" may be the second pass. tex.web §863 sets final_pass := (emergency_stretch <= 0) when it enters the second pass: with no \emergencystretch there is no third pass and the clause is live on the second. A caller that keeps FinalPass for a pass it never runs has no final pass at all.

⚠ What the clause does is permit an overfull line, not prefer short ones. On both fixtures in finalpass_test.go, tectonic 0.17.0 sets one overfull line rather than breaking: 33.0pt too wide on the first, 21.5pt on the second. The README said the opposite up to v1.3.0, on an argument from demerits that was never put to the reference.

tex.web's integer badness (v1.13.0)

By default a line's badness is the float 100·|r|³. tex.web §108 computes it in integers from the shortfall t and the stretch s in scaled points — r = t·297 div s, (r³ + 2¹⁷) div 2¹⁸, capped at 10000 — and the two decide differently on a band of shortfalls around every boundary (fitness 12 and 99, \tolerance): at badness 12 the float flips to "loose" at t/s = 0.4932, §108 at 0.5007. TeXBadness(t, s int) int is §108, transcribed; Params.ScaledPointsPerUnit says how many scaled points one unit of every width, stretch and shrink is (1 for sp, 65536 for TeX points) and makes the breaker use §108 for feasibility, fitness and demerits. Zero, the default, changes nothing.

\tracingparagraphs (v1.7.0)

Params.Trace is an io.Writer that receives TeX's own paragraph log, in tex.web's format to the character — because its whole value is being diffable against the reference:

@ via @@0 b=10000 p=0 d=100010000
@@1: line 1.0 t=100010000 -> @@0
@\discretionary via @@0 b=1 p=50 d=2633
@@2: line 1.2- t=2633 -> @@0
@\penalty via @@1 b=10000 p=100 d=100010000
@\par via @@3 b=0 p=-10000 d=10100

A line-breaking divergence is otherwise inferred from glyph positions three layers downstream. With this, both engines state their own reasons — the badness b, the penalty p, the demerits d of every break considered, and the surviving active nodes with their totals — and the first line that differs is the divergence. Fitness digits are TeX's: 0 very loose, 1 loose, 2 decent, 3 tight; - marks a hyphenated break.

⛔ b=* is not "badness ≥ 10000". §108 caps badness at inf_bad, so a computed badness reaches 10000 and never passes it. TeX reaches inf_bad+1 by assignment in exactly one case — a line that "cannot shrink enough to fit the necessary width" (§16753-16756) — so the star means overfull, and d=* means artificial_demerits: the break was taken because the paragraph had no other way out, not because it was cheap.

⚠ Three things it deliberately does not do. No short_display of the text between breaks (§16877): this package is handed items, never the words, so a diff against a real log must ignore those lines. \kern and \math are two of TeX's five break kinds and cannot arise here. And the pass markers — @firstpass, @secondpass, @emergencypass — are the caller's to print, since it is the caller that runs the passes.

⚠ The format is validated against tex.web's printing statements, not against a captured log. Every tracing_paragraphs site in tex.web sits inside the @!stat … tats conditional, so a TeX built without that section emits nothing — which is the case for the tectonic used as this project's reference. A tex or pdftex built with statistics would close that gap.

Tests

go test ./... — 100% statement coverage, run on six 64-bit architectures (amd64, arm64, riscv64, loong64, ppc64le, s390x), three operating systems, and both wasm targets.

Licence

BSD-3-Clause.

Documentation

Index

Constants

View Source
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.

View Source
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).

View Source
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

func TeXBadness(t, s int) int

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 Box

func Box(w float64) Item

Box, Glue and Penalty are constructors.

func Glue

func Glue(w, stretch, shrink float64) Item

func GlueOrder added in v1.5.0

func GlueOrder(w, stretch float64, order uint8, shrink float64) Item

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.

func Glyph

func Glyph(r rune, w, h, d float64) Item

Glyph is a box carrying a rune and its height/depth (used by the typesetter).

func Penalty

func Penalty(w, p float64, flagged bool) Item

type ItemKind

type ItemKind uint8

ItemKind classifies a horizontal-list item.

const (
	KBox     ItemKind = iota // a box of fixed width
	KGlue                    // stretchable/shrinkable space (a legal breakpoint after a box)
	KPenalty                 // a penalty (a legal breakpoint; ±InfPenalty = forbidden/forced)
)

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

func KnuthPlass(items []Item, lineWidth, tolerance, linePenalty float64) ([]Line, bool)

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 KnuthPlassShaped(items []Item, m Measure, p Params) ([]Line, bool)

func KnuthPlassWith added in v1.1.0

func KnuthPlassWith(items []Item, lineWidth float64, p Params) ([]Line, bool)

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

func HangIndent(hsize, indent float64, after int) Measure

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

func ParShape(lines []Shape) Measure

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.

func Uniform added in v1.10.0

func Uniform(hsize float64) Measure

Uniform is TeX's normal setting — par_shape_ptr null, hang_indent 0 — where every line has the same width and no margin (tex.web:16706-16710: "last_special_line:=0; second_width:=hsize; second_indent:=0").

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

func DefaultParams(tolerance, linePenalty float64) Params

DefaultParams are LaTeX's own settings (latex.ltx:498-514): \tolerance=200, \linepenalty=10, \adjdemerits=10000, \doublehyphendemerits=10000, \finalhyphendemerits=5000.

type Shape added in v1.10.0

type Shape struct{ Indent, Width float64 }

A Shape is one \parshape pair: a left margin and a width.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址