Skip to main content

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