flm_core/layout/printer.rs
1//! The printer: it turns a layout document into text, and reports where each
2//! marked part of the document was printed.
3//!
4//! [`print()`] and [`print_full`] take a layout document ([`DocBuf`]),
5//! the id of its root node and a [`Profile`] (the target width). They return
6//! the text; [`print_full`] also returns one [`MarkSpan`] per mark
7//! ([`PrintOutput`]).
8//!
9//! The output depends only on the document, the root node and the profile:
10//! the printer makes one pass over the document with one explicit work stack,
11//! uses no hash-map iteration and no floating point, and keeps only a record
12//! of the nodes it has printed apart (table cells, and the children of
13//! `flush_right` and `ruled` nodes), which depends on nothing but the node and
14//! the width, so two runs give the same bytes. The printer calls
15//! itself only for the nodes it prints apart, in separate runs: table cells,
16//! and the children of `flush_right` and `ruled` nodes (section 6).
17//!
18//! The rest of this documentation describes the six mechanisms that make up
19//! the printer's behavior, for a reader who needs to predict the output
20//! exactly or to maintain the printer. The names in code font below that no
21//! link leads to (`Frame`, `Flat`, `Break`, `fits`, `IndentId`, `IndentUnit`,
22//! `Spaces`, `Prefix`) are the printer's internal names, given for
23//! maintainers; the lowercase ones (`group`, `line`, `nest`, …) are the
24//! constructors of [`DocBuf`].
25//!
26//! # 1. The work stack and the two modes
27//!
28//! Each entry of the work stack is a `Frame`: the indentation stack that
29//! applies, a *mode*, and the work to do (a node to print, or "close this
30//! mark"). The mode says what a break opportunity prints: in `Flat` mode a
31//! `line` prints as a space and a `softbreak` as nothing; in `Break` mode both
32//! print as a line break. The root frame starts in `Break` mode when the
33//! profile has a width, and in `Flat` mode when it has none ("no width" means
34//! "never wrap", so a `line` outside any group prints as a space).
35//!
36//! A `group` reached in `Flat` mode stays flat: once a group has been found to
37//! fit on the line, everything inside it is flat too, and nothing more is
38//! tested. A `group` reached in `Break` mode is tested by the fitting scan of
39//! section 2, and its content is printed in `Flat` mode if it fits, in `Break`
40//! mode otherwise.
41//!
42//! # 2. The fitting scan, including what follows the group
43//!
44//! The fitting scan (`fits`) decides whether a group fits. It walks the
45//! group's content in `Flat` mode, adding up widths against the room left on
46//! the current line, **and then keeps walking the rest of the work stack**,
47//! each remaining frame in the mode it was recorded with. It answers *yes* at
48//! the first break opportunity it reaches in a `Break`-mode frame (the line
49//! ends there in any case, so nothing after it can make this line too long),
50//! or when the whole rest of the document has been walked. It answers *no* as
51//! soon as the total exceeds the room left, or when it reaches an
52//! unconditional break (`hardline`, `blocksep`, a `raw` block of several
53//! lines, a table that has columns and rows, a `ruled` node whose child
54//! prints something) inside the group being tested, since such a group cannot
55//! print on one line at all. A `flush_right` node counts as an atom as wide as
56//! its gap and its child's one line, or as nothing when its child prints
57//! nothing; the columns counted for the unbroken `line`s directly before it
58//! are given back, since the node replaces their spaces by its own (section
59//! 6).
60//!
61//! Walking on past the group makes prose wrap correctly. Each space between
62//! two words of [`fill_words`](super::DocBuf::fill_words) is its own group;
63//! when the scan for the last such group reaches a trailing text after the
64//! prose, a text with no break opportunity of its own, it finds that the word
65//! *plus* that text would be too long, and the group breaks. A scan that
66//! stopped at the group's end would instead keep the word on the line, and the
67//! trailing text would make the line too long.
68//!
69//! **A group reached *during* the scan keeps the mode of the frame it came
70//! from**: flat inside the group being tested, `Break` in the rest of the
71//! work stack. A group further along the work stack has not been decided yet,
72//! so its own break opportunities count as places where the line may end.
73//! Prose filled word by word therefore looks exactly one word ahead, instead of
74//! requiring that the rest of the paragraph fit.
75//!
76//! The scan does not count indentation: `nest`, `align` and `prefix` change
77//! where *later* lines start, and the scan stops at the first line break, so
78//! the scan's stack holds only `(mode, node)` pairs, and the indentation
79//! affects the scan only through the current column, where it starts. This is
80//! a known limitation: an indentation node inside a group at the start of a
81//! line does change that group's first line, and the scan does not count it,
82//! so `group(nest(4, ..))` printed right after a line break can be found to
83//! fit when its indented first line does not. Emitters keep indentation
84//! outside groups ([`fill_words`](super::DocBuf::fill_words) puts groups only
85//! around single break opportunities), which avoids the case.
86//!
87//! # 3. The indentation stack
88//!
89//! A frame's indentation is not a number of columns but an `IndentId`: a
90//! reference into a persistent stack of `IndentUnit`s whose stacks share
91//! their common outer part. Each unit is either `Spaces(n)` (from `nest`, and
92//! from `align`, which pads to the column where it starts) or a `Prefix` (from
93//! `prefix`). At each line start, the stack is written in nesting order, so a
94//! list inside a quotation gives `"> "` then the item's indentation, and a
95//! quotation inside a list gives the item's indentation then `"> "`. The
96//! printer stores the display width of each stack, and the width available
97//! for wrapping is measured from it, so content inside `prefix("> ", ..)`
98//! wraps two columns earlier.
99//!
100//! Because a line's indentation is written only when its first content
101//! character is (section 4), the rule "a prefix applies to the current line
102//! if it starts at a line start, and from the next line otherwise" needs no
103//! special case: a prefix that starts in the middle of a line cannot change
104//! the line's indentation, which has already been written. Adjacent `Spaces`
105//! units are merged into one, so `nest(2, nest(3, ..))` uses one unit and
106//! prints like `nest(5, ..)`; the merge keeps the outer unit, so it never
107//! hides a prefix from the blank-line rule below.
108//!
109//! # 4. Writing a line only when content arrives: the pending break and the spaces not yet written
110//!
111//! The printer never writes whitespace ahead of time:
112//!
113//! - A request for a line break (`line` or `softbreak` in `Break` mode,
114//! `hardline`, `blocksep`) writes no newline. It records a *pending break*
115//! with a number of blank lines (`blocksep(n)` asks for `n`, everything else
116//! for `0`). A request made while another is pending is merged with it, and
117//! the larger number of blank lines is kept; the numbers are never added. So
118//! `hardline` next to `blocksep(1)` gives one blank line, and `blocksep(2)`
119//! next to `blocksep(1)` gives two.
120//! - The indentation stack, and the space of a flat `line`, are written only
121//! when a content character follows on that line. A *content character* is
122//! a character of the layout document's own text that the printer writes,
123//! as opposed to the indentation, the prefixes, the spaces and the line
124//! breaks the printer adds.
125//!
126//! Therefore no line ends in whitespace the printer added; a pending break at
127//! the very start of the output is dropped; a pending break at the very end is
128//! replaced by exactly one final newline; and a blank line can only come from
129//! `blocksep` or from a newline inside `raw` content. Runs of newlines cannot
130//! arise, so no pass removes them afterwards.
131//!
132//! **What a blank line contains.** A blank line written for a pending break
133//! holds the *longest common outer part* of two indentation stacks (the stack
134//! that applied at the last content character and the stack that applies
135//! where the break is written), trimmed of trailing whitespace. The two stacks
136//! are compared by **identity of their units**, not by their text: each time
137//! a `prefix` node is printed it pushes a unit of its own, so the common part
138//! is exactly the units that the two stacks share. Consequences: a blank line
139//! between two paragraphs inside one `prefix("> ")` prints `>`, so the two
140//! paragraphs remain one quoted passage; a blank line between two *sibling*
141//! `prefix("> ")` nodes prints nothing, so they remain two separate
142//! quotations (the emitter decides whether two quotations are one, never the
143//! printer); and stacks made only of spaces trim to an empty line.
144//!
145//! # 5. Marks
146//!
147//! A `mark` changes nothing in the output; it only records a position. Its
148//! span **starts at the first content character of its child**, after any
149//! pending break, its blank lines and the line's indentation, and **ends
150//! immediately after the child's last content character**, before any space
151//! or line break that is written later. The start is found when that
152//! character is written: opening a mark only records it as waiting, and the
153//! next content character gives every waiting mark its start. A prefix written
154//! on a blank line (a `>` on a blank quoted line) is not content for this
155//! purpose.
156//!
157//! A child that prints nothing gives an empty span placed at the next content
158//! character or, if nothing follows, at the end of the text before the final
159//! newline. Marks may be nested to any depth, have no width for the fitting
160//! scan, and are reported in the order they are opened (the order in which
161//! the printer reaches their nodes). Lines and columns are counted from 0,
162//! columns are display columns, and the end position is excluded from the
163//! span. A marked document and the same document without marks print the
164//! same bytes.
165//!
166//! A table's spans follow the spans of the marks opened before it, the mark
167//! around the table included. A table given a border mark
168//! ([`DocBuf::table`]) first reports one span under that mark for each run of
169//! characters it draws on a line, in the order they are written. Then come
170//! the marks inside its cells, row by row and column by column, each cell's
171//! marks in their own order. Each cell is printed by a separate run of the
172//! printer, and each of its marks is placed where the cell's text lands in
173//! the table: on the table's line that holds the cell's line, at the column
174//! after the indentation, the frame or the gutter, and the padding before the
175//! cell.
176//!
177//! A span of a mark inside a cell never covers a character the cell did not
178//! print. The printer reports one span per occurrence of a mark, except that
179//! a mark inside a table's cell over several lines of the cell gives one
180//! span per line of the cell on which it covers at least one character,
181//! because the table interleaves the cell's lines with the rest of the row:
182//! the first span runs from the mark's start to the end of that line of the
183//! cell, the last from the start of its line of the cell to the mark's end,
184//! and each one in between covers its whole line of the cell. The cell's line
185//! breaks belong to no span, and a blank line of the cell gives none. The
186//! spans of one mark are consecutive, in line order, at the mark's place
187//! among the cell's marks. A table nested in a cell places its cells' marks into the cell, and the
188//! enclosing table places them once more. A mark inside a cell whose row
189//! prints nothing gets an empty span at the next content character after the
190//! table or, if nothing follows, at the end of the text before the final
191//! newline.
192//!
193//! The marks inside the child of a `flush_right` or a `ruled` node come at
194//! their place in the order the marks are opened, each placed where the
195//! child's text lands (section 6), one span per mark, as anywhere else. A
196//! `ruled` node given a mark reports one span under it for its rule line
197//! above, before the marks of its child, and one for its rule line under,
198//! after them. A mark inside a child that prints nothing gets an empty span
199//! at the next content character.
200//!
201//! # 6. Nodes printed apart: `flush_right` and `ruled`
202//!
203//! The printer prints the child of a `flush_right` or a `ruled` node in a
204//! separate run, as it prints a table's cells, then writes the lines of that
205//! printing into its own output:
206//!
207//! - The child of `flush_right` is printed with no width limit, on one line.
208//! The node replaces the spaces not yet written on the current line (the
209//! space of an unbroken `line` before it) by its own: as many as bring the
210//! child's end to the last column of the width, where the current column,
211//! the gap and the child fit in the width, and otherwise the gap, or none
212//! at the start of a line. The child's text is then written as content.
213//! - The child of `ruled` is printed at the width the node's indentation
214//! stack leaves, with an empty stack. The node is written as a block: the
215//! rule line above, if any, each line of the child under the node's stack
216//! (a blank line with the stack trimmed, as for a table), and the rule
217//! line under, if any. A rule line is the node's character repeated to the
218//! widest line of the child's printing.
219//!
220//! The record of the nodes printed apart serves the child's printing to the
221//! fitting scan, which needs the width of a `flush_right` child and whether a
222//! `ruled` child prints anything.
223
224use std::cell::RefCell;
225use std::collections::BTreeMap;
226use std::ops::Range;
227use std::rc::Rc;
228
229use super::doc::{
230 ColSpec, DocBuf, DocId, MarkId, Node, PoolRange, RawPolicy, RuledDef, TableCell, TableDef,
231};
232use super::table::{self, AssembledLine, RenderedCell, RowLine};
233use super::width::{UnicodeMeasure, WidthMeasure};
234
235/// The printer's option: the target line width.
236///
237/// Every other behavior of the printer is fixed: lines end in `\n` (an
238/// emitter that needs `\r\n` converts the text afterwards); a non-empty text
239/// ends in exactly one newline; an atom wider than the line is written whole,
240/// never split; and widths are measured by [`display_width`](super::display_width),
241/// which counts the East-Asian *Ambiguous* characters (such as `…`, `→` and
242/// `•`, which a terminal configured for Western languages draws one column
243/// wide and one configured for East-Asian languages two) as one column.
244///
245/// The default profile (`Profile::default()`) has the width 80.
246#[derive(Clone, Copy, PartialEq, Eq, Debug)]
247pub struct Profile {
248 /// The target line width in columns, or `None` to never wrap.
249 ///
250 /// With `None`, every group prints flat (every `line` a space, every
251 /// `softbreak` nothing) and the fitting scan never runs; this is a separate, faster path, not a very large width. The
252 /// widths of atoms are still measured, because `align` needs the current
253 /// column. `hardline` and `blocksep` still end lines, because they are
254 /// part of the document's structure, and every table column gets its
255 /// maximum width.
256 pub width: Option<u32>,
257}
258
259impl Profile {
260 /// Creates a profile with the target width `width` (`None` to never
261 /// wrap).
262 pub const fn new(width: Option<u32>) -> Self {
263 Profile { width }
264 }
265}
266
267impl Default for Profile {
268 /// A profile with the width 80.
269 fn default() -> Self {
270 Profile { width: Some(80) }
271 }
272}
273
274/// A position in the printed text: a line number and a display column on
275/// that line, both counted from 0.
276#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
277pub struct LineCol {
278 /// The line number, counted from 0.
279 pub line: u32,
280 /// The display column, counted from 0 and measured with
281 /// [`display_width`](super::display_width).
282 pub col: u32,
283}
284
285/// Where the child of one [`mark`](super::DocBuf::mark) was printed: the
286/// mark's identifier, the byte range of the child's content characters in the
287/// printed text, and their first and last line and column.
288///
289/// [`print_full`] returns one `MarkSpan` per occurrence of a mark. The end
290/// positions are excluded from the span, so `bytes` slices
291/// [`PrintOutput::text`] directly. The [module documentation](self), section
292/// 5, gives the exact rules for where a span starts and ends.
293#[derive(Clone, PartialEq, Eq, Debug)]
294pub struct MarkSpan {
295 /// The identifier the caller gave the mark.
296 pub id: MarkId,
297 /// The byte range of [`PrintOutput::text`] that holds the child's
298 /// content characters.
299 pub bytes: Range<usize>,
300 /// The line and column of the child's first content character.
301 pub start: LineCol,
302 /// The line and column just after the child's last content character.
303 pub end: LineCol,
304}
305
306/// The result of [`print_full`]: the printed text, and where each mark's
307/// child was printed in it.
308#[derive(Clone, PartialEq, Eq, Debug, Default)]
309pub struct PrintOutput {
310 /// The printed text: empty when the document prints nothing; otherwise it
311 /// ends with exactly one `'\n'`.
312 pub text: String,
313 /// One span per occurrence of a mark, in the order the marks are opened
314 /// (the order in which the printer reaches the `mark` nodes); a mark
315 /// inside a table cell over several lines of the cell gives one span per
316 /// line, because the table interleaves the cell's lines with the rest of
317 /// the row. A table's spans follow those of the marks opened before it:
318 /// one span under its border mark for each run of characters it draws on
319 /// a line, if it has a border mark, then the marks inside its cells, row
320 /// by row and column by column (see the [module documentation](self),
321 /// section 5).
322 pub marks: Vec<MarkSpan>,
323}
324
325/// Prints the layout document `buf` from its node `root`, at the width of
326/// `profile`, and returns the text.
327///
328/// The result is the [`text`](PrintOutput::text) of [`print_full`] with the
329/// same arguments; use [`print_full`] to know where marked parts were printed.
330///
331/// # Panics
332///
333/// `root` must have been created by `buf`, and not before a call to
334/// [`DocBuf::clear`]: an id beyond the arena's nodes panics with an index
335/// error. An id from another arena that is within range refers to the node at
336/// that index instead, a caller error the engine cannot detect.
337///
338/// In a debug build, also if the child of a
339/// [`flush_right`](super::DocBuf::flush_right) node prints a line break (see
340/// that constructor's requirements).
341pub fn print(buf: &DocBuf, root: DocId, profile: &Profile) -> String {
342 print_full(buf, root, profile).text
343}
344
345/// Prints the layout document `buf` from its node `root`, at the width of
346/// `profile`, and returns the text together with one [`MarkSpan`] per mark
347/// occurrence.
348///
349/// # Panics
350///
351/// As for [`print()`]: `root` must have been created by `buf`, and not before
352/// a call to [`DocBuf::clear`].
353///
354/// In a debug build, also if the child of a
355/// [`flush_right`](super::DocBuf::flush_right) node prints a line break.
356pub fn print_full(buf: &DocBuf, root: DocId, profile: &Profile) -> PrintOutput {
357 print_with_measure(buf, root, profile.width, &UnicodeMeasure)
358}
359
360/// Prints with the width measure `measure` instead of the engine's; for the
361/// crate's own use.
362///
363/// It lets the tests check the printer under other measures, and would let
364/// the crate select a measure that counts East-Asian *Ambiguous* characters as
365/// two columns with a change of one line. Callers outside the crate use
366/// [`print()`] and [`print_full`].
367pub(crate) fn print_with_measure(
368 buf: &DocBuf,
369 root: DocId,
370 width: Option<u32>,
371 measure: &dyn WidthMeasure,
372) -> PrintOutput {
373 let apart = SeparatePrints::default();
374 let mut printer = Printer::new(buf, measure, width, &apart);
375 printer.run(root);
376 printer.finish()
377}
378
379/// The text of `run`, a node printed apart, without its final newline: empty
380/// where the node prints nothing.
381fn printed_text(run: &PrintOutput) -> &str {
382 run.text.strip_suffix('\n').unwrap_or(&run.text)
383}
384
385/// The nodes one print has printed apart, by node and width: the table
386/// cells, and the children of `flush_right` and `ruled` nodes.
387///
388/// A cell is printed by a separate run of the printer, at width 1 and with no
389/// width limit to measure it, and at its column's width to show it; a table
390/// inside a cell does the same for its own cells within each of those runs.
391/// Without this record, the innermost cells of a table nested *n* deep would
392/// be printed three to the *n*-th power times. A cell's printed text depends
393/// only on the cell and the width (the separate run starts from an empty
394/// indentation stack), so one printing serves every later request for the
395/// same cell and width, and the output is the same. The record keeps the
396/// marks of the printing with its text, so a table nested in a cell, whose
397/// cells' marks were placed into the cell's printing, places them once more
398/// into the enclosing table. The children of `flush_right` and `ruled` nodes
399/// are printed apart in the same way and recorded with the cells: the
400/// fitting scan asks for them as well as the node's printing.
401#[derive(Default)]
402struct SeparatePrints(RefCell<BTreeMap<NodeAtWidth, Rc<PrintOutput>>>);
403
404/// A node printed apart and the width it is printed at (`None` for no
405/// limit).
406type NodeAtWidth = (DocId, Option<u32>);
407
408/// The printing of one cell of a table at its column's width, with its
409/// position in the table, for placing its marks.
410struct PrintedCell {
411 /// The cell's row, counted from 0.
412 row: usize,
413 /// The cell's column, counted from 0.
414 col: usize,
415 /// The cell's printing.
416 output: Rc<PrintOutput>,
417}
418
419/// What a break opportunity prints in the frame from which the printer
420/// reaches it.
421#[derive(Clone, Copy, PartialEq, Eq, Debug)]
422enum Mode {
423 /// `line` is a space, `softbreak` is nothing.
424 Flat,
425 /// Both are line breaks.
426 Break,
427}
428
429/// The work of one entry of the work stack.
430#[derive(Clone, Copy, Debug)]
431enum Work {
432 /// Print this node.
433 Doc(DocId),
434 /// Close the mark at this index of the mark list (once the mark's child
435 /// has been printed completely).
436 CloseMark(u32),
437}
438
439/// One entry of the work stack.
440#[derive(Clone, Copy, Debug)]
441struct Frame {
442 indent: IndentId,
443 mode: Mode,
444 work: Work,
445}
446
447/// One unit of the indentation stack.
448#[derive(Clone, Copy, Debug)]
449enum IndentUnit {
450 /// Plain columns, from `nest` and from `align`'s padding.
451 Spaces(u32),
452 /// A per-line prefix: a range into the arena's text pool.
453 Prefix(PoolRange),
454}
455
456/// A node of the persistent indentation stack. Stacks share their outer
457/// part, so a frame holds only an `IndentId`, and two stacks are the same when
458/// their ids are equal.
459#[derive(Clone, Copy, Debug)]
460struct IndentNode {
461 unit: IndentUnit,
462 parent: IndentId,
463 /// The display width of the whole stack ending at this node, stored so
464 /// that the width available for wrapping is not recomputed.
465 width: u32,
466}
467
468/// Index into the printer's indentation-stack pool; [`IndentId::EMPTY`] is
469/// the empty stack.
470#[derive(Clone, Copy, PartialEq, Eq, Debug)]
471struct IndentId(u32);
472
473impl IndentId {
474 const EMPTY: IndentId = IndentId(u32::MAX);
475}
476
477/// A position in the output text.
478#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
479struct Pos {
480 byte: usize,
481 line: u32,
482 col: u32,
483}
484
485/// A mark being resolved.
486struct MarkState {
487 id: MarkId,
488 start: Option<Pos>,
489 end: Option<Pos>,
490 /// The child printed no content character: the end must equal the
491 /// start, wherever the start is eventually found.
492 empty: bool,
493}
494
495struct Printer<'a> {
496 buf: &'a DocBuf,
497 measure: &'a dyn WidthMeasure,
498 width: Option<u32>,
499
500 out: String,
501 stack: Vec<Frame>,
502 indents: Vec<IndentNode>,
503
504 /// The column the next content character would occupy on the current
505 /// line, counting `pending_space`. Meaningful only while `line_open`.
506 col: u32,
507 /// Index of the line currently being written (0-based).
508 line: u32,
509 /// Whether the current line has been started (its indentation stack
510 /// written).
511 line_open: bool,
512 /// Deferred spaces on the current line, from flat `line`s.
513 pending_space: u32,
514 /// A requested line break with this many blank lines after it, not yet
515 /// written. `None` = no break pending.
516 pending_break: Option<u8>,
517 /// The indentation stack that applied at the last content character: one
518 /// of the two stacks the blank-line rule compares.
519 last_indent: IndentId,
520
521 /// Marks, in open order.
522 marks: Vec<MarkState>,
523 /// The indices into `marks` of the marks whose start waits for the next
524 /// content character.
525 pending_starts: Vec<u32>,
526 /// The position immediately after the last content character written.
527 last_end: Pos,
528 /// The nodes printed apart so far by this print and its separate runs
529 /// (table cells, and the children of `flush_right` and `ruled` nodes).
530 apart: &'a SeparatePrints,
531}
532
533impl<'a> Printer<'a> {
534 fn new(
535 buf: &'a DocBuf,
536 measure: &'a dyn WidthMeasure,
537 width: Option<u32>,
538 apart: &'a SeparatePrints,
539 ) -> Self {
540 Printer {
541 buf,
542 measure,
543 apart,
544 width,
545 out: String::new(),
546 stack: Vec::new(),
547 indents: Vec::new(),
548 col: 0,
549 line: 0,
550 line_open: false,
551 pending_space: 0,
552 pending_break: None,
553 last_indent: IndentId::EMPTY,
554 marks: Vec::new(),
555 pending_starts: Vec::new(),
556 last_end: Pos::default(),
557 }
558 }
559
560 // ========================================================================
561 // the main loop
562 // ========================================================================
563
564 #[inline]
565 fn push_doc(&mut self, indent: IndentId, mode: Mode, id: DocId) {
566 self.stack.push(Frame {
567 indent,
568 mode,
569 work: Work::Doc(id),
570 });
571 }
572
573 fn run(&mut self, root: DocId) {
574 // Root mode by width: an unbounded profile starts flat, so a bare
575 // `line` outside any group is a space, not a break.
576 let mode = if self.width.is_some() {
577 Mode::Break
578 } else {
579 Mode::Flat
580 };
581 self.push_doc(IndentId::EMPTY, mode, root);
582
583 let buf = self.buf;
584 while let Some(f) = self.stack.pop() {
585 let id = match f.work {
586 Work::Doc(id) => id,
587 Work::CloseMark(idx) => {
588 self.close_mark(idx);
589 continue;
590 }
591 };
592 match buf.node(id) {
593 Node::Text(range) => {
594 let s = buf.text_at(range);
595 if !s.is_empty() {
596 self.emit(f.indent, s);
597 }
598 }
599 Node::Line => match f.mode {
600 Mode::Flat => self.flat_space(),
601 Mode::Break => self.request_break(0),
602 },
603 Node::SoftBreak => match f.mode {
604 Mode::Flat => {}
605 Mode::Break => self.request_break(0),
606 },
607 Node::HardLine => self.request_break(0),
608 Node::BlockSep { blank_lines } => self.request_break(blank_lines),
609 Node::Nest { indent, child } => {
610 let id = self.push_spaces(f.indent, u32::from(indent));
611 self.push_doc(id, f.mode, child);
612 }
613 Node::Align { child } => {
614 // Pad the current stack out to the column reached at
615 // entry. Saturating: entering an `align` mid-line from
616 // inside a deeper stack (`text("a") ++ nest(50, align(..))`)
617 // can put the column behind the stack; the stack wins.
618 let pad = self
619 .column(f.indent)
620 .saturating_sub(self.stack_width(f.indent));
621 let id = self.push_spaces(f.indent, pad);
622 self.push_doc(id, f.mode, child);
623 }
624 Node::Prefix { prefix, child } => {
625 // Each *visit* pushes its own unit: scope identity, which
626 // is what the blank-line rule compares.
627 let id = self.push_unit(f.indent, IndentUnit::Prefix(prefix));
628 self.push_doc(id, f.mode, child);
629 }
630 Node::Group { child } => {
631 // Unbounded, or already inside a flattened group: flat
632 // with no scanning (the `||` short-circuits before the
633 // scan). Otherwise the fitting scan decides.
634 let flat = self.width.is_none()
635 || f.mode == Mode::Flat
636 || self.fits(f.indent, child);
637 let mode = if flat { Mode::Flat } else { Mode::Break };
638 self.push_doc(f.indent, mode, child);
639 }
640 Node::Concat(range) => {
641 // Push in reverse so that children pop in document order.
642 for &child in buf.children_at(range).iter().rev() {
643 self.push_doc(f.indent, f.mode, child);
644 }
645 }
646 Node::Raw { content, policy } => {
647 self.emit_raw(f.indent, buf.text_at(content), policy);
648 }
649 Node::Table { def } => {
650 self.emit_table(f.indent, buf.table_def(def));
651 }
652 Node::FlushRight { gap, child } => {
653 self.emit_flush_right(f.indent, child, u32::from(gap));
654 }
655 Node::Ruled { def } => {
656 self.emit_ruled(f.indent, buf.ruled_def(def));
657 }
658 Node::Mark { id: mark, child } => {
659 let idx = self.open_mark(mark);
660 // Close after the child: the stack is LIFO, so push the
661 // closer first.
662 self.stack.push(Frame {
663 indent: f.indent,
664 mode: f.mode,
665 work: Work::CloseMark(idx),
666 });
667 self.push_doc(f.indent, f.mode, child);
668 }
669 }
670 }
671 }
672
673 // ========================================================================
674 // marks
675 // ========================================================================
676
677 fn open_mark(&mut self, id: MarkId) -> u32 {
678 let idx = self.marks.len() as u32;
679 self.marks.push(MarkState {
680 id,
681 start: None,
682 end: None,
683 empty: false,
684 });
685 self.pending_starts.push(idx);
686 idx
687 }
688
689 fn close_mark(&mut self, idx: u32) {
690 let mark = &mut self.marks[idx as usize];
691 if mark.start.is_some() {
692 mark.end = Some(self.last_end);
693 } else {
694 // Nothing visible came out of the child: an empty span, anchored
695 // wherever the start eventually resolves.
696 mark.empty = true;
697 }
698 }
699
700 /// The next content character is about to be written at `pos`: every
701 /// mark still waiting for its start gets `pos`.
702 fn resolve_pending_starts(&mut self, pos: Pos) {
703 for &idx in &self.pending_starts {
704 let mark = &mut self.marks[idx as usize];
705 mark.start = Some(pos);
706 if mark.empty {
707 mark.end = Some(pos);
708 }
709 }
710 self.pending_starts.clear();
711 }
712
713 /// Called immediately before content characters are written.
714 fn note_visible_start(&mut self) {
715 let pos = Pos {
716 byte: self.out.len(),
717 line: self.line,
718 col: self.col,
719 };
720 self.resolve_pending_starts(pos);
721 }
722
723 /// Called immediately after content characters are written.
724 fn note_visible_end(&mut self) {
725 self.last_end = Pos {
726 byte: self.out.len(),
727 line: self.line,
728 col: self.col,
729 };
730 }
731
732 // ========================================================================
733 // the indentation stack
734 // ========================================================================
735
736 #[inline]
737 fn stack_width(&self, id: IndentId) -> u32 {
738 if id == IndentId::EMPTY {
739 0
740 } else {
741 self.indents[id.0 as usize].width
742 }
743 }
744
745 fn unit_width(&self, unit: IndentUnit) -> u32 {
746 match unit {
747 IndentUnit::Spaces(n) => n,
748 IndentUnit::Prefix(range) => self.measure.str_width(self.buf.text_at(range)),
749 }
750 }
751
752 fn push_unit(&mut self, parent: IndentId, unit: IndentUnit) -> IndentId {
753 let width = self.stack_width(parent).saturating_add(self.unit_width(unit));
754 self.indents.push(IndentNode {
755 unit,
756 parent,
757 width,
758 });
759 IndentId((self.indents.len() - 1) as u32)
760 }
761
762 /// Pushes `n` columns, merged with an adjacent `Spaces` unit, so that
763 /// `nest(2, nest(3, ..))` and `nest(5, ..)` print the same and use one
764 /// node. The merge keeps the outer unit's parent, so it never hides a
765 /// `Prefix` unit from the blank-line rule, which compares units by
766 /// identity; the merge changes only which `Spaces` unit is which, and
767 /// spaces are trimmed from a blank line anyway.
768 fn push_spaces(&mut self, parent: IndentId, n: u32) -> IndentId {
769 if n == 0 {
770 return parent;
771 }
772 if parent != IndentId::EMPTY {
773 let node = self.indents[parent.0 as usize];
774 if let IndentUnit::Spaces(m) = node.unit {
775 return self.push_unit(node.parent, IndentUnit::Spaces(m.saturating_add(n)));
776 }
777 }
778 self.push_unit(parent, IndentUnit::Spaces(n))
779 }
780
781 /// The ids along a stack, outermost first.
782 fn chain(&self, id: IndentId) -> Vec<IndentId> {
783 let mut v = Vec::new();
784 let mut cur = id;
785 while cur != IndentId::EMPTY {
786 v.push(cur);
787 cur = self.indents[cur.0 as usize].parent;
788 }
789 v.reverse();
790 v
791 }
792
793 fn write_unit(&self, out: &mut String, unit: IndentUnit) {
794 match unit {
795 IndentUnit::Spaces(n) => {
796 for _ in 0..n {
797 out.push(' ');
798 }
799 }
800 IndentUnit::Prefix(range) => out.push_str(self.buf.text_at(range)),
801 }
802 }
803
804 /// The full rendering of a stack, for a line start.
805 fn stack_string(&self, id: IndentId) -> String {
806 let mut s = String::new();
807 for unit_id in self.chain(id) {
808 self.write_unit(&mut s, self.indents[unit_id.0 as usize].unit);
809 }
810 s
811 }
812
813 /// The text of a blank line between two stacks: their longest common
814 /// outer part (units compared by identity, not by text), written out and
815 /// trimmed of trailing whitespace (see the module documentation, section
816 /// 4).
817 fn blank_line_text(&self, a: IndentId, b: IndentId) -> String {
818 let ca = self.chain(a);
819 let cb = self.chain(b);
820 let mut s = String::new();
821 for (x, y) in ca.iter().zip(cb.iter()) {
822 if x != y {
823 break;
824 }
825 self.write_unit(&mut s, self.indents[x.0 as usize].unit);
826 }
827 s.truncate(s.trim_end().len());
828 s
829 }
830
831 // ========================================================================
832 // line mechanics
833 // ========================================================================
834
835 /// The column at which the next content character will be written, when
836 /// it is printed under the stack `indent`.
837 ///
838 /// If a break is pending, or the line has not been started yet, the next
839 /// character is written right after the stack; otherwise at the current
840 /// column.
841 #[inline]
842 fn column(&self, indent: IndentId) -> u32 {
843 if self.pending_break.is_some() || !self.line_open {
844 self.stack_width(indent)
845 } else {
846 self.col
847 }
848 }
849
850 /// Requests a line break followed by `blanks` blank lines. A request made
851 /// while another is pending is merged with it, keeping the larger number.
852 #[inline]
853 fn request_break(&mut self, blanks: u8) {
854 self.pending_break = Some(match self.pending_break {
855 Some(pending) => pending.max(blanks),
856 None => blanks,
857 });
858 }
859
860 /// A `line` printed flat: one space, written only when content follows.
861 ///
862 /// Dropped at a line start (it would be whitespace before the
863 /// indentation, and trailing whitespace if the line then ended). The
864 /// fitting scan still counts one column for such a `line`; that extra
865 /// column can only make the scan break a line that would have fit.
866 #[inline]
867 fn flat_space(&mut self) {
868 if self.pending_break.is_none() && self.line_open {
869 self.pending_space += 1;
870 self.col += 1;
871 }
872 }
873
874 fn push_nl(&mut self) {
875 self.out.push('\n');
876 self.line += 1;
877 }
878
879 /// Writes the pending break, if any: the newline that ends the current
880 /// line, then its blank lines (each holding the longest common outer part
881 /// of the two stacks). The next line is left unstarted.
882 fn flush_break(&mut self, indent: IndentId) {
883 let Some(blanks) = self.pending_break.take() else {
884 return;
885 };
886 self.pending_space = 0;
887 if !self.out.is_empty() {
888 // A break at the very start of the output is dropped.
889 self.push_nl();
890 if blanks > 0 {
891 let blank = self.blank_line_text(self.last_indent, indent);
892 for _ in 0..blanks {
893 self.out.push_str(&blank);
894 self.push_nl();
895 }
896 }
897 }
898 self.line_open = false;
899 self.col = 0;
900 }
901
902 /// Starts the current line by writing its indentation stack.
903 fn open_line(&mut self, indent: IndentId) {
904 debug_assert!(self.pending_break.is_none());
905 if !self.line_open {
906 let s = self.stack_string(indent);
907 self.out.push_str(&s);
908 self.col = self.stack_width(indent);
909 self.line_open = true;
910 }
911 }
912
913 /// Writes a line that has no content: the stack, trimmed of trailing
914 /// whitespace (`"> "` keeps its `">"`; indentation made only of spaces
915 /// disappears).
916 ///
917 /// The stack written on such a line is not content for marks: a mark
918 /// waiting for its start gets the next content character instead.
919 fn open_blank_line(&mut self, indent: IndentId) {
920 debug_assert!(self.pending_break.is_none());
921 if !self.line_open {
922 let s = self.stack_string(indent);
923 let t = &s[..s.trim_end().len()];
924 self.out.push_str(t);
925 self.col = self.measure.str_width(t);
926 self.line_open = true;
927 }
928 }
929
930 /// Writes a newline that is part of the content, as *inside* `raw`
931 /// content and between the lines of a table. It is never merged with a
932 /// pending break.
933 fn hard_nl(&mut self) {
934 self.push_nl();
935 self.line_open = false;
936 self.col = 0;
937 self.pending_space = 0;
938 }
939
940 fn flush_spaces(&mut self) {
941 for _ in 0..self.pending_space {
942 self.out.push(' ');
943 }
944 self.pending_space = 0;
945 }
946
947 /// Writes content characters, starting the line first if needed.
948 ///
949 /// Atoms are never split: an atom wider than the room left is written
950 /// whole, and the line is longer than the width. Lines break only at
951 /// break opportunities.
952 fn emit(&mut self, indent: IndentId, s: &str) {
953 self.flush_break(indent);
954 self.open_line(indent);
955 self.flush_spaces();
956 self.note_visible_start();
957 self.out.push_str(s);
958 self.col += self.measure.str_width(s);
959 self.note_visible_end();
960 self.last_indent = indent;
961 }
962
963 /// Ends the print: a pending break at the end of the output is dropped, as
964 /// is any space not yet written; a non-empty output ends with exactly one
965 /// `'\n'`.
966 fn finish(mut self) -> PrintOutput {
967 // Marks never resolved: anchor them at the end of the content, before
968 // the final newline.
969 let end = self.last_end;
970 self.resolve_pending_starts(end);
971 for mark in &mut self.marks {
972 if mark.end.is_none() {
973 mark.end = Some(end);
974 }
975 }
976 if !self.out.is_empty() && !self.out.ends_with('\n') {
977 self.out.push('\n');
978 }
979 let marks = self
980 .marks
981 .iter()
982 .map(|mark| {
983 let s = mark.start.unwrap_or_default();
984 let e = mark.end.unwrap_or_default();
985 MarkSpan {
986 id: mark.id,
987 bytes: s.byte..e.byte,
988 start: LineCol {
989 line: s.line,
990 col: s.col,
991 },
992 end: LineCol {
993 line: e.line,
994 col: e.col,
995 },
996 }
997 })
998 .collect();
999 PrintOutput {
1000 text: self.out,
1001 marks,
1002 }
1003 }
1004
1005 // ========================================================================
1006 // raw
1007 // ========================================================================
1008
1009 /// Writes verbatim content.
1010 ///
1011 /// Newlines inside the content are written as they are, so runs of blank
1012 /// lines inside a code block are kept exactly. A newline at the *end* of
1013 /// the content becomes a pending break instead of being written, so that
1014 /// a following `blocksep` is merged with it (the larger number of blank
1015 /// lines kept) rather than adding a blank line.
1016 fn emit_raw(&mut self, indent: IndentId, content: &str, policy: RawPolicy) {
1017 if content.is_empty() {
1018 return;
1019 }
1020 // Verbatim-exempt content escapes the scope entirely, including for
1021 // the blank lines of the break being flushed.
1022 let scope = match policy {
1023 RawPolicy::Indented => indent,
1024 RawPolicy::Exempt => IndentId::EMPTY,
1025 };
1026 self.flush_break(scope);
1027 if policy == RawPolicy::Exempt && self.line_open {
1028 // Exempt raw must start at column 0, so it ends any open line.
1029 self.hard_nl();
1030 }
1031
1032 let mut segments = content.split('\n').peekable();
1033 let mut first = true;
1034 while let Some(seg) = segments.next() {
1035 let last = segments.peek().is_none();
1036 if !first {
1037 if last && seg.is_empty() {
1038 // Trailing newline: hand it to the pending-break
1039 // mechanism.
1040 self.request_break(0);
1041 break;
1042 }
1043 self.hard_nl();
1044 }
1045 first = false;
1046 if seg.is_empty() {
1047 match policy {
1048 RawPolicy::Indented => self.open_blank_line(indent),
1049 // Truly empty; mark the line materialized so that the next
1050 // `hard_nl` terminates it.
1051 RawPolicy::Exempt => self.line_open = true,
1052 }
1053 } else {
1054 match policy {
1055 RawPolicy::Indented => self.open_line(indent),
1056 RawPolicy::Exempt => {
1057 if !self.line_open {
1058 self.line_open = true;
1059 self.col = 0;
1060 }
1061 }
1062 }
1063 self.flush_spaces();
1064 self.note_visible_start();
1065 self.out.push_str(seg);
1066 // Best effort: the column after a raw that does not end in a
1067 // newline is measured from its last line with the engine
1068 // measure (tabs included, whatever the measure says they
1069 // are).
1070 self.col += self.measure.str_width(seg);
1071 self.note_visible_end();
1072 }
1073 }
1074 self.last_indent = scope;
1075 }
1076
1077 // ========================================================================
1078 // tables
1079 // ========================================================================
1080
1081 /// Prints `node` on its own, at `width`, with this printer's measure and
1082 /// an empty indentation stack (the table's own stack applies to the
1083 /// assembled lines), and returns the text and the marks of that printing;
1084 /// [`emit_table`](Self::emit_table) places the marks into the table, and
1085 /// [`emit_flush_right`](Self::emit_flush_right) and
1086 /// [`emit_ruled`](Self::emit_ruled) into the lines they write.
1087 ///
1088 /// Each printing of a table asks for each of its cells at three widths
1089 /// (width 1, no limit, and the column's computed width), and each cell is
1090 /// printed once per width for the whole print: the text is recorded in
1091 /// [`SeparatePrints`], and a later request at the same width reads the
1092 /// record, so a nested table does not multiply the printings of its
1093 /// innermost cells by three per level.
1094 fn print_apart(&self, node: DocId, width: Option<u32>) -> Rc<PrintOutput> {
1095 if let Some(done) = self.apart.0.borrow().get(&(node, width)) {
1096 return Rc::clone(done);
1097 }
1098 let mut printer = Printer::new(self.buf, self.measure, width, self.apart);
1099 printer.run(node);
1100 let output = Rc::new(printer.finish());
1101 self.apart.0.borrow_mut().insert((node, width), Rc::clone(&output));
1102 output
1103 }
1104
1105 fn max_line_width(&self, s: &str) -> u32 {
1106 s.lines()
1107 .map(|l| self.measure.str_width(l))
1108 .max()
1109 .unwrap_or(0)
1110 }
1111
1112 /// A cell's **minimum** width: the width below which breaking more lines
1113 /// makes the cell no narrower. It is computed as the widest line of the
1114 /// cell printed at width 1 (every break opportunity broken), which is the
1115 /// widest atom (or raw line) plus the indentation around it.
1116 fn cell_min(&self, cell: DocId) -> u32 {
1117 self.max_line_width(&self.print_apart(cell, Some(1)).text)
1118 }
1119
1120 /// A cell's **maximum** width: the widest line of the cell printed with no
1121 /// width limit, where only its unconditional breaks (`hardline`,
1122 /// `blocksep`, newlines of raw content) end lines.
1123 fn cell_max(&self, cell: DocId) -> u32 {
1124 self.max_line_width(&self.print_apart(cell, None).text)
1125 }
1126
1127 /// Lays out and writes a table: measure the cells, compute the column
1128 /// widths, print the cells, assemble the lines, write them.
1129 ///
1130 /// A table is a block on both sides: it requests a line break before and
1131 /// after itself, and every assembled line is written under the table's
1132 /// indentation stack, so a table inside a list or a quotation is indented
1133 /// and prefixed correctly. A table that prints nothing (no columns, no
1134 /// rows, or only empty cells) is not a block: it leaves the current line
1135 /// and any pending break as they are (see the [`layout`](super) module
1136 /// documentation).
1137 fn emit_table(&mut self, indent: IndentId, def: TableDef) {
1138 let buf = self.buf;
1139 let cols: Vec<ColSpec> = buf.cols_at(def.cols).to_vec();
1140 let ncols = cols.len();
1141 if ncols == 0 {
1142 return;
1143 }
1144 let rows: Vec<PoolRange> = buf.rows_at(def.rows).to_vec();
1145
1146 // -- measure ---------------------------------------------------------
1147 let mut mins = vec![0u32; ncols];
1148 let mut maxs = vec![0u32; ncols];
1149 let mut grid: Vec<Vec<Option<TableCell>>> = Vec::with_capacity(rows.len());
1150 for &row_range in &rows {
1151 let cells = buf.cells_at(row_range);
1152 let mut row = vec![None; ncols];
1153 for (i, &cell) in cells.iter().take(ncols).enumerate() {
1154 row[i] = Some(cell);
1155 mins[i] = mins[i].max(self.cell_min(cell.doc));
1156 maxs[i] = maxs[i].max(self.cell_max(cell.doc));
1157 }
1158 grid.push(row);
1159 }
1160 // A cell whose indentation grows when it breaks can measure "wider
1161 // when narrow"; keep max >= min so that the solver's spans stay sane.
1162 for (max, &min) in maxs.iter_mut().zip(&mins) {
1163 *max = (*max).max(min);
1164 }
1165
1166 // -- solve -----------------------------------------------------------
1167 let frame = table::frame_width(def.frame, ncols);
1168 let available = self.width.map(|w| {
1169 w.saturating_sub(self.stack_width(indent))
1170 .saturating_sub(frame)
1171 });
1172 let widths = table::solve_columns(&mins, &maxs, available);
1173
1174 // -- render cells ----------------------------------------------------
1175 let mut rendered: Vec<Vec<RenderedCell>> = Vec::with_capacity(grid.len());
1176 // Each cell's printing, in reading order, for its marks.
1177 let mut printed: Vec<PrintedCell> = Vec::new();
1178 for (r, row) in grid.iter().enumerate() {
1179 let mut out_row = Vec::with_capacity(ncols);
1180 for (i, cell) in row.iter().enumerate() {
1181 // With an unbounded profile every column already has its max
1182 // width; render the cell unbounded too, so that the assignment
1183 // is exactly the unbounded layout.
1184 let cell_width = self.width.map(|_| widths[i]);
1185 let lines: Vec<String> = match cell {
1186 None => Vec::new(),
1187 Some(cell) => {
1188 let output = self.print_apart(cell.doc, cell_width);
1189 let s = printed_text(&output);
1190 let lines = if s.is_empty() {
1191 Vec::new()
1192 } else {
1193 s.split('\n').map(|l| l.to_string()).collect()
1194 };
1195 if !output.marks.is_empty() {
1196 printed.push(PrintedCell {
1197 row: r,
1198 col: i,
1199 output: Rc::clone(&output),
1200 });
1201 }
1202 lines
1203 }
1204 };
1205 // A cell's own alignment replaces its column's.
1206 let align = cell.and_then(|cell| cell.align).unwrap_or(cols[i].align);
1207 out_row.push(RenderedCell { lines, align });
1208 }
1209 rendered.push(out_row);
1210 }
1211
1212 // -- assemble --------------------------------------------------------
1213 let lines = table::assemble_lines(
1214 &rendered,
1215 &widths,
1216 def.header_rows,
1217 def.frame,
1218 self.measure,
1219 );
1220
1221 // -- emit ------------------------------------------------------------
1222 // A table that prints nothing is not a block: it leaves the current
1223 // line and any pending break untouched, since output that does not
1224 // exist must not push the following text onto a new line.
1225 if lines.is_empty() {
1226 self.add_cell_marks(&printed, &[], &[], &BTreeMap::new());
1227 return;
1228 }
1229 // Otherwise a table is a block: it starts on its own line and ends
1230 // one.
1231 if self.line_open {
1232 self.request_break(0);
1233 }
1234 self.flush_break(indent);
1235 // Where each line's text starts in the output, by line of the table.
1236 let mut line_starts: Vec<Pos> = Vec::with_capacity(lines.len());
1237 // The index of each line of a row in `lines`, by row and line.
1238 let mut row_lines: BTreeMap<(usize, usize), usize> = BTreeMap::new();
1239 for (k, line) in lines.iter().enumerate() {
1240 if k > 0 {
1241 self.hard_nl();
1242 }
1243 if line.text.is_empty() {
1244 self.open_blank_line(indent);
1245 } else {
1246 self.open_line(indent);
1247 self.note_visible_start();
1248 if let Some(id) = def.border_mark {
1249 self.add_table_runs(id, line);
1250 }
1251 }
1252 line_starts.push(Pos {
1253 byte: self.out.len(),
1254 line: self.line,
1255 col: self.col,
1256 });
1257 if let Some(RowLine { row, line: n, .. }) = line.row_line {
1258 row_lines.insert((row, n), k);
1259 }
1260 if !line.text.is_empty() {
1261 self.out.push_str(&line.text);
1262 self.col += self.measure.str_width(&line.text);
1263 self.note_visible_end();
1264 }
1265 }
1266 self.last_indent = indent;
1267 self.request_break(0);
1268 self.add_cell_marks(&printed, &lines, &line_starts, &row_lines);
1269 }
1270
1271 /// Records one span under `id` for each run of characters the table draws
1272 /// on `line` ([`AssembledLine::borders`]), the line about to be written
1273 /// at the current position.
1274 fn add_table_runs(&mut self, id: MarkId, line: &AssembledLine) {
1275 let byte = self.out.len();
1276 for run in &line.borders {
1277 let col = self.col + self.measure.str_width(&line.text[..run.start]);
1278 let width = self.measure.str_width(&line.text[run.clone()]);
1279 self.marks.push(MarkState {
1280 id,
1281 start: Some(Pos {
1282 byte: byte + run.start,
1283 line: self.line,
1284 col,
1285 }),
1286 end: Some(Pos {
1287 byte: byte + run.end,
1288 line: self.line,
1289 col: col + width,
1290 }),
1291 empty: false,
1292 });
1293 }
1294 }
1295
1296 /// Records the marks printed inside the table's cells, `cells` in reading
1297 /// order, each mark placed where its cell's line was written: `lines` are
1298 /// the table's assembled lines, `starts[k]` the position in the output at
1299 /// which the text of `lines[k]` starts, and `row_lines` the index in
1300 /// `lines` of each line of a row, by row and line within the row.
1301 ///
1302 /// A mark keeps its byte range, line and column relative to the line of
1303 /// the cell it is on, shifted to where that line stands in the output; a
1304 /// position past the end of a line whose trailing whitespace was removed
1305 /// moves to the line's end. A mark over several lines of the cell is
1306 /// cut at the cell's line breaks into one span per line on which it
1307 /// covers a character (see the [module documentation](self), section 5).
1308 /// A mark of a cell whose row prints no line gets an empty span at the
1309 /// next content character after the table or, if nothing follows, at the
1310 /// end of the text before the final newline.
1311 fn add_cell_marks(
1312 &mut self,
1313 cells: &[PrintedCell],
1314 lines: &[AssembledLine],
1315 starts: &[Pos],
1316 row_lines: &BTreeMap<(usize, usize), usize>,
1317 ) {
1318 let measure = self.measure;
1319 for cell in cells {
1320 let text = &cell.output.text;
1321 // The byte offset of each line of the cell's text.
1322 let offsets: Vec<usize> = std::iter::once(0)
1323 .chain(text.match_indices('\n').map(|(i, _)| i + 1))
1324 .collect();
1325 let place = |byte: usize, at: usize| -> Option<Pos> {
1326 let k = *row_lines.get(&(cell.row, at))?;
1327 let line = &lines[k];
1328 let row_line = line.row_line.as_ref()?;
1329 let within = byte - offsets[at];
1330 let byte = (row_line.starts[cell.col] + within).min(line.text.len());
1331 let start = starts[k];
1332 Some(Pos {
1333 byte: start.byte + byte,
1334 line: start.line,
1335 col: start.col + measure.str_width(&line.text[..byte]),
1336 })
1337 };
1338 // The end of each line of the cell's text, before its newline.
1339 let line_end = |l: usize| offsets.get(l + 1).map_or(text.len(), |&o| o - 1);
1340 for span in &cell.output.marks {
1341 // The pieces of the span, one per line of the cell on which it
1342 // covers a character: the cell's newlines belong to no piece.
1343 let (first, last) = (span.start.line as usize, span.end.line as usize);
1344 let mut pieces: Vec<(usize, usize, usize)> = if first == last {
1345 vec![(first, span.bytes.start, span.bytes.end)]
1346 } else {
1347 (first..=last)
1348 .map(|l| {
1349 let from = span.bytes.start.max(offsets[l]);
1350 let to = span.bytes.end.min(line_end(l));
1351 (l, from, to)
1352 })
1353 .filter(|&(_, from, to)| from < to)
1354 .collect()
1355 };
1356 if pieces.is_empty() {
1357 // Only line breaks: an empty span where the mark starts.
1358 pieces.push((first, span.bytes.start, span.bytes.start));
1359 }
1360 let placed: Option<Vec<(Pos, Pos)>> = pieces
1361 .iter()
1362 .map(|&(l, from, to)| Some((place(from, l)?, place(to, l)?)))
1363 .collect();
1364 match placed {
1365 Some(placed) => {
1366 for (start, end) in placed {
1367 self.marks.push(MarkState {
1368 id: span.id,
1369 start: Some(start),
1370 end: Some(end),
1371 empty: false,
1372 });
1373 }
1374 }
1375 None => {
1376 let idx = self.open_mark(span.id);
1377 self.marks[idx as usize].empty = true;
1378 }
1379 }
1380 }
1381 }
1382 }
1383
1384 // ========================================================================
1385 // flush_right and ruled
1386 // ========================================================================
1387
1388 /// Records the marks of `run`, the separate printing of a node whose
1389 /// text is written into this printing, each position placed by `place`
1390 /// (from a byte offset and a line and column of `run`). Where `run`
1391 /// printed nothing, its marks get empty spans at the next content
1392 /// character, as a mark whose child prints nothing does.
1393 fn add_run_marks(&mut self, run: &PrintOutput, place: impl Fn(usize, LineCol) -> Pos) {
1394 let prints_nothing = printed_text(run).is_empty();
1395 for span in &run.marks {
1396 if prints_nothing {
1397 let idx = self.open_mark(span.id);
1398 self.marks[idx as usize].empty = true;
1399 } else {
1400 self.marks.push(MarkState {
1401 id: span.id,
1402 start: Some(place(span.bytes.start, span.start)),
1403 end: Some(place(span.bytes.end, span.end)),
1404 empty: false,
1405 });
1406 }
1407 }
1408 }
1409
1410 /// Writes the node `flush_right(child, gap)`: `child` printed apart, with
1411 /// no width limit, and its one line placed at the right edge of the width
1412 /// where it fits, otherwise `gap` columns after what precedes it (see
1413 /// [`DocBuf::flush_right`]).
1414 fn emit_flush_right(&mut self, indent: IndentId, child: DocId, gap: u32) {
1415 let run = self.print_apart(child, None);
1416 let text = printed_text(&run);
1417 debug_assert!(
1418 !text.contains('\n'),
1419 "the child of flush_right must print on one line: {text:?}"
1420 );
1421 if text.is_empty() {
1422 self.add_run_marks(&run, |_, _| Pos::default());
1423 return;
1424 }
1425 let width = self.measure.str_width(text);
1426 self.flush_break(indent);
1427 let at_line_start = !self.line_open;
1428 self.open_line(indent);
1429 // The space of an unbroken `line` just before the node is replaced
1430 // by the placement's own spaces.
1431 self.col -= self.pending_space;
1432 self.pending_space = 0;
1433 let before = self.col;
1434 let fits = self
1435 .width
1436 .is_some_and(|w| u64::from(before) + u64::from(gap) + u64::from(width) <= u64::from(w));
1437 let pad = match self.width {
1438 Some(w) if fits => w - before - width,
1439 _ if at_line_start => 0,
1440 _ => gap,
1441 };
1442 self.pending_space = pad;
1443 self.col += pad;
1444 self.emit(indent, text);
1445 let start = Pos {
1446 byte: self.out.len() - text.len(),
1447 line: self.line,
1448 col: self.col - width,
1449 };
1450 self.add_run_marks(&run, |byte, at| Pos {
1451 byte: start.byte + byte,
1452 line: start.line + at.line,
1453 col: if at.line == 0 { start.col + at.col } else { at.col },
1454 });
1455 }
1456
1457 /// Writes one rule line of a `ruled` node under `indent`, and records its
1458 /// span under `mark`, if given.
1459 fn write_rule_line(&mut self, indent: IndentId, rule: &str, mark: Option<MarkId>) {
1460 self.open_line(indent);
1461 self.note_visible_start();
1462 let start = Pos {
1463 byte: self.out.len(),
1464 line: self.line,
1465 col: self.col,
1466 };
1467 self.out.push_str(rule);
1468 self.col += self.measure.str_width(rule);
1469 self.note_visible_end();
1470 if let Some(id) = mark {
1471 self.marks.push(MarkState {
1472 id,
1473 start: Some(start),
1474 end: Some(self.last_end),
1475 empty: false,
1476 });
1477 }
1478 }
1479
1480 /// Writes a `ruled` node: its child printed apart, at the width the
1481 /// indentation leaves, its lines written under `indent` between the rule
1482 /// lines the node asks for (see [`DocBuf::ruled`]).
1483 ///
1484 /// Like a table, the node is a block, except where its child prints
1485 /// nothing: it then leaves the current line and any pending break as
1486 /// they are.
1487 fn emit_ruled(&mut self, indent: IndentId, def: RuledDef) {
1488 let width = self
1489 .width
1490 .map(|w| w.saturating_sub(self.stack_width(indent)));
1491 let run = self.print_apart(def.child, width);
1492 let text = printed_text(&run);
1493 if text.is_empty() {
1494 self.add_run_marks(&run, |_, _| Pos::default());
1495 return;
1496 }
1497 let lines: Vec<&str> = text.split('\n').collect();
1498 let rule_width = lines
1499 .iter()
1500 .map(|line| self.measure.str_width(line))
1501 .max()
1502 .unwrap_or(0);
1503 // A child whose characters are all of width 0 gets no rule line: a
1504 // rule of no character would be a blank line.
1505 let rule: String = std::iter::repeat_n(def.rule, rule_width as usize).collect();
1506 let mark = def.mark;
1507
1508 if self.line_open {
1509 self.request_break(0);
1510 }
1511 self.flush_break(indent);
1512 let mut first = true;
1513 if def.above && !rule.is_empty() {
1514 self.write_rule_line(indent, &rule, mark);
1515 first = false;
1516 }
1517 // Where each line's text starts in the output, and in the child's
1518 // text.
1519 let mut starts: Vec<Pos> = Vec::with_capacity(lines.len());
1520 let mut offsets: Vec<usize> = Vec::with_capacity(lines.len());
1521 let mut offset = 0;
1522 for line in &lines {
1523 if !first {
1524 self.hard_nl();
1525 }
1526 first = false;
1527 if line.is_empty() {
1528 self.open_blank_line(indent);
1529 } else {
1530 self.open_line(indent);
1531 self.note_visible_start();
1532 }
1533 starts.push(Pos {
1534 byte: self.out.len(),
1535 line: self.line,
1536 col: self.col,
1537 });
1538 offsets.push(offset);
1539 offset += line.len() + 1;
1540 if !line.is_empty() {
1541 self.out.push_str(line);
1542 self.col += self.measure.str_width(line);
1543 self.note_visible_end();
1544 }
1545 }
1546 self.last_indent = indent;
1547 self.add_run_marks(&run, |byte, at| {
1548 let k = at.line as usize;
1549 Pos {
1550 byte: starts[k].byte + (byte - offsets[k]),
1551 line: starts[k].line,
1552 col: starts[k].col + at.col,
1553 }
1554 });
1555 if def.below && !rule.is_empty() {
1556 self.hard_nl();
1557 self.write_rule_line(indent, &rule, mark);
1558 }
1559 self.request_break(0);
1560 }
1561
1562 // ========================================================================
1563 // the fitting scan
1564 // ========================================================================
1565
1566 /// Returns whether `child`, printed flat under `indent`, keeps the rest of
1567 /// the current line within the width. The scan continues through the rest
1568 /// of the work stack; see the [module documentation](self), section 2.
1569 fn fits(&self, indent: IndentId, child: DocId) -> bool {
1570 let Some(max) = self.width else {
1571 return true;
1572 };
1573 // Room left on the current line. Saturating: if the line is already
1574 // past the width (an overflowing atom), nothing further fits.
1575 let mut rem = i64::from(max.saturating_sub(self.column(indent)));
1576
1577 let buf = self.buf;
1578 // Indentation is inert here, so the scan stack is (mode, node) only.
1579 let mut scan: Vec<(Mode, DocId)> = vec![(Mode::Flat, child)];
1580 // Index into the work stack, walked from the top downwards once the
1581 // group's own content is exhausted.
1582 let mut cont = self.stack.len();
1583 // The columns of the unbroken `line`s counted since the last content
1584 // character, starting with the spaces already pending on the line: a
1585 // `flush_right` node replaces them by its own spaces.
1586 let mut spaces = if self.pending_break.is_none() && self.line_open {
1587 i64::from(self.pending_space)
1588 } else {
1589 0
1590 };
1591
1592 loop {
1593 let (mode, id) = match scan.pop() {
1594 Some(item) => item,
1595 None => {
1596 if cont == 0 {
1597 // Nothing left in the document: the line ends here.
1598 return true;
1599 }
1600 cont -= 1;
1601 let f = self.stack[cont];
1602 match f.work {
1603 Work::Doc(id) => (f.mode, id),
1604 // Mark closers have no width and must be stepped
1605 // over, or the continuation walk stops short.
1606 Work::CloseMark(_) => continue,
1607 }
1608 }
1609 };
1610 match buf.node(id) {
1611 Node::Text(range) => {
1612 let s = buf.text_at(range);
1613 if !s.is_empty() {
1614 spaces = 0;
1615 }
1616 rem -= i64::from(self.measure.str_width(s));
1617 if rem < 0 {
1618 return false;
1619 }
1620 }
1621 Node::Line => match mode {
1622 Mode::Flat => {
1623 rem -= 1;
1624 spaces += 1;
1625 if rem < 0 {
1626 return false;
1627 }
1628 }
1629 // The line ends here regardless of this group's decision.
1630 Mode::Break => return true,
1631 },
1632 Node::SoftBreak => match mode {
1633 Mode::Flat => {}
1634 Mode::Break => return true,
1635 },
1636 Node::HardLine | Node::BlockSep { .. } => match mode {
1637 // A hard break inside the candidate group: it cannot be
1638 // flattened.
1639 Mode::Flat => return false,
1640 // A hard break after it: the line ends there.
1641 Mode::Break => return true,
1642 },
1643 Node::Nest { child, .. }
1644 | Node::Align { child }
1645 | Node::Prefix { child, .. }
1646 | Node::Mark { child, .. } => scan.push((mode, child)),
1647 // The load-bearing line: a group keeps the mode of the frame
1648 // it came from. Content of the candidate
1649 // group is flat, whereas a group further along the work stack
1650 // is still undecided and its own break opportunities count as
1651 // real ones. This is what makes per-word fill look exactly one
1652 // word ahead instead of demanding that the whole rest of the
1653 // paragraph fit.
1654 Node::Group { child } => scan.push((mode, child)),
1655 Node::Concat(range) => {
1656 for &c in buf.children_at(range).iter().rev() {
1657 scan.push((mode, c));
1658 }
1659 }
1660 Node::Raw { content, .. } => {
1661 let s = buf.text_at(content);
1662 match s.find('\n') {
1663 // Single-line raw measures like an atom.
1664 None => {
1665 if !s.is_empty() {
1666 spaces = 0;
1667 }
1668 rem -= i64::from(self.measure.str_width(s));
1669 if rem < 0 {
1670 return false;
1671 }
1672 }
1673 Some(nl) => match mode {
1674 // Multi-line raw is hard structure, like a
1675 // hardline.
1676 Mode::Flat => return false,
1677 Mode::Break => {
1678 rem -= i64::from(self.measure.str_width(&s[..nl]));
1679 return rem >= 0;
1680 }
1681 },
1682 }
1683 }
1684 Node::FlushRight { gap, child } => {
1685 // An atom of the gap and the child's one line, or nothing.
1686 // The spaces of unbroken `line`s just before it are
1687 // replaced by the placement's own spaces, as the printer
1688 // does.
1689 let run = self.print_apart(child, None);
1690 let text = printed_text(&run);
1691 if !text.is_empty() {
1692 let width = self.max_line_width(text);
1693 rem += spaces;
1694 rem -= i64::from(gap) + i64::from(width);
1695 spaces = 0;
1696 if rem < 0 {
1697 return false;
1698 }
1699 }
1700 }
1701 Node::Ruled { def } => {
1702 // A block, unless its child prints nothing; whether it
1703 // does is the same at every width.
1704 let run = self.print_apart(buf.ruled_def(def).child, None);
1705 if !printed_text(&run).is_empty() {
1706 match mode {
1707 Mode::Flat => return false,
1708 Mode::Break => return true,
1709 }
1710 }
1711 }
1712 Node::Table { def } => {
1713 // A table is a block — unless it prints nothing. The two
1714 // shapes decidable without rendering, no columns and no
1715 // rows, count as zero width and force no break; a table
1716 // whose rows all render empty is still a block to the scan.
1717 let def = buf.table_def(def);
1718 let prints_nothing = buf.cols_at(def.cols).is_empty()
1719 || buf.rows_at(def.rows).is_empty();
1720 if !prints_nothing {
1721 match mode {
1722 Mode::Flat => return false,
1723 Mode::Break => return true,
1724 }
1725 }
1726 }
1727 }
1728 }
1729 }
1730}
1731
1732#[cfg(test)]
1733mod tests {
1734 //! Tests that need to choose the width measure, which only crate-internal
1735 //! code can do. The rest of the printer's tests are integration tests of
1736 //! the crate.
1737
1738 use super::super::doc::DocBuf;
1739 use super::super::width::UnicodeCjkMeasure;
1740 use super::{print, print_with_measure, Profile};
1741
1742 /// The width measure is not a cosmetic setting: it moves break points *and*
1743 /// hanging-indent columns. U+2022 BULLET is East-Asian Ambiguous, so the
1744 /// same document hangs at column 4 under the shipped (ambiguous-narrow)
1745 /// measure and column 5 under an ambiguous-wide one.
1746 ///
1747 /// `Profile` exposes only the width; the measure is reached through the
1748 /// crate-internal print function, which is what an ambiguous-wide profile
1749 /// would change.
1750 #[test]
1751 fn the_measure_changes_the_layout() {
1752 let mut b = DocBuf::new();
1753 let bullet = b.text(" • ");
1754 let body = b.fill_words("alpha beta gamma");
1755 let hung = b.align(body);
1756 let d = b.concat(&[bullet, hung]);
1757
1758 let narrow = print(&b, d, &Profile::new(Some(14)));
1759 let wide = print_with_measure(&b, d, Some(14), &UnicodeCjkMeasure).text;
1760 for out in [&narrow, &wide] {
1761 for line in out.split('\n') {
1762 assert_eq!(line.trim_end(), line, "trailing whitespace in {out:?}");
1763 }
1764 }
1765
1766 assert_eq!(narrow, " • alpha beta\n gamma\n");
1767 // One extra column of label pushes both the hanging indent and every
1768 // break.
1769 assert_eq!(wide, " • alpha\n beta\n gamma\n");
1770 }
1771}