Skip to main content

flm_core/layout/
doc.rs

1//! The layout document: the description of intended text that an emitter
2//! builds and hands to the printer.
3//!
4//! A *layout document* describes output text without deciding where the lines
5//! end. It holds the words as text atoms, the places where a line *may* end
6//! ([`line`](DocBuf::line), [`softbreak`](DocBuf::softbreak)), the places
7//! where a line *must* end ([`hardline`](DocBuf::hardline),
8//! [`blocksep`](DocBuf::blocksep)), and the structure that sets indentation,
9//! per-line prefixes, verbatim blocks and tables. The printer
10//! ([`super::print`]) decides the line breaks for a given width.
11//!
12//! An emitter creates a [`DocBuf`], calls its constructors from the innermost
13//! parts outwards (each returns the [`DocId`] of the node it creates), and
14//! hands the id of the outermost node, the root, to the printer.
15//!
16//! # The constructors
17//!
18//! The constructors of [`DocBuf`] are the only way to build a layout
19//! document; every one but [`fill_words`](DocBuf::fill_words) creates one kind
20//! of node:
21//!
22//! | constructor | meaning |
23//! |---|---|
24//! | [`text`](DocBuf::text) | an atom: printed whole, never split, never changed |
25//! | [`line`](DocBuf::line) | a break opportunity: one space when it does not break |
26//! | [`softbreak`](DocBuf::softbreak) | a break opportunity: nothing when it does not break |
27//! | [`hardline`](DocBuf::hardline) | an unconditional line break |
28//! | [`blocksep`](DocBuf::blocksep) | a line break followed by *n* blank lines |
29//! | [`nest`](DocBuf::nest) | indent the child by a fixed number of columns |
30//! | [`align`](DocBuf::align) | indent the child to the column where it starts (a hanging indent) |
31//! | [`group`](DocBuf::group) | a unit whose break opportunities all stay unbroken (flat), or all break |
32//! | [`concat`](DocBuf::concat) | a sequence |
33//! | [`prefix`](DocBuf::prefix) | write a string before every line of the child (`> `) |
34//! | [`raw`](DocBuf::raw) | verbatim lines, never reflowed |
35//! | [`table`](DocBuf::table) | rows of cells laid out in computed columns |
36//! | [`mark`](DocBuf::mark) | ask the printer to report where the child is printed |
37//! | [`fill_words`](DocBuf::fill_words) | prose: the words of a text, with one group around each space between two words |
38//!
39//! Each constructor's documentation states how the printer treats its node;
40//! the [printer](super::printer)'s module documentation explains the
41//! mechanisms the constructors share.
42//!
43//! # Representation: a flat arena
44//!
45//! A [`DocBuf`] is a set of growable pools and nothing else:
46//!
47//! - `nodes`: every node, as one fixed-size `Node` value;
48//! - `text`: every text atom, every line prefix and every raw block, copied
49//!   into one shared `String`; a node holds only a byte range into it;
50//! - `children`: the children of every sequence, appended into one shared
51//!   pool; a `Concat` node holds only a range into it;
52//! - `rows`, `cells`, `cols`, `tables`: the data of table nodes, held outside
53//!   the nodes.
54//!
55//! Building a document therefore makes no heap allocation per node, and a
56//! [`DocId`] is a plain `u32`, cheap to copy onto the printer's work stack.
57//! [`DocBuf::clear`] keeps the allocated capacity, so one arena can be reused
58//! for one render after another.
59//!
60//! Ids are given out bottom-up: a node's children exist before the node
61//! itself, so the arena cannot contain a cycle. A node may be shared: the same
62//! [`DocId`] may appear in several sequences, and the printer prints it at
63//! each occurrence (the arena is a directed acyclic graph, not a tree).
64
65use std::ops::Range;
66
67/// The identifier of a node of one [`DocBuf`]: its index in the arena.
68///
69/// Every constructor of [`DocBuf`] returns the `DocId` of the node it creates.
70/// A `DocId` is meaningful only for the arena that created it. Used with
71/// another arena, it refers to the node at the same index there, or makes
72/// the printer panic if the index is out of range (see [`print`](super::print)).
73#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
74pub struct DocId(u32);
75
76impl DocId {
77    /// The index of this node in its arena, for debugging output only.
78    #[inline]
79    pub fn index(self) -> usize {
80        self.0 as usize
81    }
82}
83
84/// The identifier of a [`mark`](DocBuf::mark), chosen by the caller.
85///
86/// The engine does not interpret the number and does **not** require it to
87/// be unique: an emitter may mark several nodes with the same id, and
88/// [`print_full`](super::print_full) reports one [`MarkSpan`](super::MarkSpan)
89/// per marked node, each carrying the id. The emitter keeps its own table from
90/// ids to the parts of its input that the marks refer to (the text backend's
91/// emitter maps them to lowered nodes), so this module does not depend on the
92/// document model.
93#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
94pub struct MarkId(pub u32);
95
96/// Whether the enclosing indentation and prefixes apply to the lines of a
97/// [`raw`](DocBuf::raw) block.
98#[derive(Clone, Copy, PartialEq, Eq, Debug)]
99pub enum RawPolicy {
100    /// Every raw line is written after the current indentation stack, so a
101    /// code block inside a list item or a quotation gets the item's indentation
102    /// or the `> ` on every line, and its own bytes are unchanged. The text
103    /// backend uses this policy.
104    Indented,
105    /// Every raw line starts at column 0 and the indentation stack is not
106    /// written at all, the way a LaTeX `verbatim` environment behaves. No
107    /// backend of this library uses this policy.
108    Exempt,
109}
110
111/// Horizontal alignment of the cells in one table column.
112#[derive(Clone, Copy, PartialEq, Eq, Debug)]
113pub enum ColAlign {
114    /// Cells start at the column's left edge; padding goes on the right.
115    Left,
116    /// Cells end at the column's right edge; padding goes on the left.
117    Right,
118    /// Padding is split between both sides; when it is an odd number of
119    /// columns, the extra column goes on the right.
120    Center,
121}
122
123/// The specification of one column of a [table](DocBuf::table): the
124/// alignment of its cells.
125#[derive(Clone, Copy, PartialEq, Eq, Debug)]
126pub struct ColSpec {
127    /// How the column's cells are aligned within the column's computed width.
128    pub align: ColAlign,
129}
130
131impl ColSpec {
132    /// A left-aligned column.
133    pub fn left() -> Self {
134        ColSpec {
135            align: ColAlign::Left,
136        }
137    }
138
139    /// A right-aligned column.
140    pub fn right() -> Self {
141        ColSpec {
142            align: ColAlign::Right,
143        }
144    }
145
146    /// A centered column.
147    pub fn center() -> Self {
148        ColSpec {
149            align: ColAlign::Center,
150        }
151    }
152}
153
154/// How a [table](DocBuf::table) is drawn around and between its cells.
155#[derive(Clone, Copy, PartialEq, Eq, Debug)]
156pub enum TableFrame {
157    /// The columns separated by a gutter of two spaces, a rule of `-` across
158    /// every column under the header rows, and nothing else.
159    Gutter,
160    /// A frame of box-drawing characters around every cell: a line above the
161    /// first row and one below the last, a rule under the header rows,
162    /// nothing between body rows, and on every line of the rows a bar before,
163    /// between and after the cells, with one space on each side of each cell.
164    ///
165    /// ```text
166    /// ┌──────────┬────────┐
167    /// │ Header   │ Right  │
168    /// ├──────────┼────────┤
169    /// │ a cell   │     42 │
170    /// │ wrapped  │        │
171    /// └──────────┴────────┘
172    /// ```
173    ///
174    /// The frame's characters are one column wide for the engine, as for a
175    /// terminal configured for Western languages.
176    Box,
177}
178
179/// One cell of a [table](DocBuf::table): its content, a node of the same
180/// arena, and optionally an alignment of its own.
181///
182/// A cell with no alignment of its own is aligned as its column's [`ColSpec`]
183/// says. A cell with one is padded to the column's computed width in that
184/// alignment instead, regardless of the other cells of the column. The
185/// alignment changes only where the cell's lines are placed inside the
186/// column: the column's width is computed from its cells' content alone.
187///
188/// A [`DocId`] converts into a cell with no alignment of its own, so the rows
189/// of a table whose cells all follow their columns can be given as ids.
190#[derive(Clone, Copy, PartialEq, Eq, Debug)]
191pub struct TableCell {
192    /// The cell's content: any node of the same arena.
193    pub doc: DocId,
194    /// The cell's own alignment; `None` uses the column's.
195    pub align: Option<ColAlign>,
196}
197
198impl TableCell {
199    /// A cell whose content is `doc`, aligned as its column is.
200    pub fn new(doc: DocId) -> Self {
201        TableCell { doc, align: None }
202    }
203
204    /// A cell whose content is `doc`, aligned as `align` says, regardless of
205    /// its column.
206    pub fn aligned(doc: DocId, align: ColAlign) -> Self {
207        TableCell {
208            doc,
209            align: Some(align),
210        }
211    }
212}
213
214impl From<DocId> for TableCell {
215    fn from(doc: DocId) -> Self {
216        TableCell::new(doc)
217    }
218}
219
220/// A range of bytes or of entries in one of the pools of a [`DocBuf`].
221///
222/// The node that holds the range determines which pool it refers to; the
223/// reading methods of [`DocBuf`] return what the range covers.
224#[derive(Clone, Copy, PartialEq, Eq, Debug)]
225pub(crate) struct PoolRange {
226    start: u32,
227    end: u32,
228}
229
230impl PoolRange {
231    #[inline]
232    fn as_range(self) -> Range<usize> {
233        self.start as usize..self.end as usize
234    }
235}
236
237/// The `u32` form of a pool length, checked against the arena's documented
238/// limit (see the `# Panics` section of [`DocBuf`]).
239#[inline]
240fn pool_len(len: usize, pool: &str) -> u32 {
241    assert!(
242        len <= u32::MAX as usize,
243        "the {pool} pool of the layout document must hold at most u32::MAX entries (bytes, \
244         for the text pool)"
245    );
246    len as u32
247}
248
249/// One node of the arena, as the printer reads it.
250///
251/// Every variant is `Copy` and holds no pointer; its data are ranges into the
252/// pools of the [`DocBuf`] that holds it, read through that arena's reading
253/// methods. Callers build nodes through the constructors of [`DocBuf`]; this
254/// enum is the printer's input and is crate-internal, so that the arena's
255/// representation can change.
256#[derive(Clone, Copy, PartialEq, Eq, Debug)]
257pub(crate) enum Node {
258    /// An atom (see [`DocBuf::text`]): a range into the text pool.
259    Text(PoolRange),
260    /// A break opportunity that is one space when it does not break.
261    Line,
262    /// A break opportunity that is nothing when it does not break.
263    SoftBreak,
264    /// An unconditional line break.
265    HardLine,
266    /// Indent `child` by `indent` extra columns.
267    Nest { indent: u16, child: DocId },
268    /// Indent `child` to the column reached when it is entered.
269    Align { child: DocId },
270    /// A unit whose break opportunities all break or all stay flat.
271    Group { child: DocId },
272    /// A sequence: a range into the children pool.
273    Concat(PoolRange),
274    /// A line break followed by `blank_lines` blank lines.
275    BlockSep { blank_lines: u8 },
276    /// A prefix written before every line of `child`; `prefix` is a range
277    /// into the text pool.
278    Prefix { prefix: PoolRange, child: DocId },
279    /// Verbatim content. `content` is a range into the text pool and is the
280    /// only text that may contain `'\n'` and `'\t'`.
281    Raw { content: PoolRange, policy: RawPolicy },
282    /// A table; `def` is its index in the arena's table pool.
283    Table { def: u32 },
284    /// A mark around `child`.
285    Mark { id: MarkId, child: DocId },
286}
287
288/// The data of a [`Node::Table`], held in the arena's table pool.
289#[derive(Clone, Copy, PartialEq, Eq, Debug)]
290pub(crate) struct TableDef {
291    /// A range into the rows pool; each row is itself a range into the cells
292    /// pool, holding that row's cells. Rows may have different numbers of
293    /// cells.
294    pub(crate) rows: PoolRange,
295    /// A range into the column pool.
296    pub(crate) cols: PoolRange,
297    /// The number of leading rows that form the header; a rule is drawn
298    /// after them. `0` means no header.
299    pub(crate) header_rows: u8,
300    /// How the table is drawn around and between its cells.
301    pub(crate) frame: TableFrame,
302    /// The mark under which the printer reports the characters the table
303    /// draws itself, if any.
304    pub(crate) border_mark: Option<MarkId>,
305}
306
307/// A layout document: an arena of layout nodes, with its pools of text,
308/// children, rows, cells, columns and tables.
309///
310/// An emitter builds a layout document by calling the constructors
311/// ([`text`](Self::text), [`line`](Self::line), [`group`](Self::group), ...),
312/// innermost parts first. Each returns the [`DocId`] of the node it creates,
313/// which the emitter passes to the constructors of the enclosing nodes; the
314/// id of the outermost node is the root that [`print`](super::print) and
315/// [`print_full`](super::print_full) take. The [module documentation](self)
316/// lists the constructors and describes the representation.
317///
318/// # Requirements
319///
320/// An id is meaningful only for the arena that created it, and
321/// [`clear`](Self::clear) makes every id given out before it meaningless;
322/// giving such an id to the printer is a caller error (see
323/// [`print`](super::print)).
324///
325/// # Panics
326///
327/// Every constructor panics if the arena or one of its pools would grow past
328/// `u32::MAX` entries (about four billion nodes, children, rows, cells,
329/// columns or tables, or four gigabytes of text), a size no document reaches;
330/// the panic message gives the pool.
331#[derive(Clone, Default, Debug)]
332pub struct DocBuf {
333    nodes: Vec<Node>,
334    text: String,
335    children: Vec<DocId>,
336    rows: Vec<PoolRange>,
337    cells: Vec<TableCell>,
338    cols: Vec<ColSpec>,
339    tables: Vec<TableDef>,
340}
341
342impl DocBuf {
343    /// Creates an empty layout document.
344    pub fn new() -> Self {
345        Self::default()
346    }
347
348    /// Removes every node and pool entry and keeps the allocated capacity, so
349    /// that the arena can be reused for the next render. Every [`DocId`] given
350    /// out before the call becomes meaningless.
351    pub fn clear(&mut self) {
352        self.nodes.clear();
353        self.text.clear();
354        self.children.clear();
355        self.rows.clear();
356        self.cells.clear();
357        self.cols.clear();
358        self.tables.clear();
359    }
360
361    /// The number of nodes in the arena.
362    pub fn len(&self) -> usize {
363        self.nodes.len()
364    }
365
366    /// Whether the arena holds no nodes.
367    pub fn is_empty(&self) -> bool {
368        self.nodes.is_empty()
369    }
370
371    // -- reader side (the printer) -------------------------------------------
372
373    /// The node an id refers to.
374    #[inline]
375    pub(crate) fn node(&self, id: DocId) -> Node {
376        self.nodes[id.0 as usize]
377    }
378
379    /// The text a range of the text pool covers (an atom, a prefix, a raw
380    /// block).
381    #[inline]
382    pub(crate) fn text_at(&self, range: PoolRange) -> &str {
383        &self.text[range.as_range()]
384    }
385
386    /// The children a range of the children pool covers (a sequence's
387    /// children).
388    #[inline]
389    pub(crate) fn children_at(&self, range: PoolRange) -> &[DocId] {
390        &self.children[range.as_range()]
391    }
392
393    /// The data of the table at index `def` of the table pool.
394    #[inline]
395    pub(crate) fn table_def(&self, def: u32) -> TableDef {
396        self.tables[def as usize]
397    }
398
399    /// The rows of a table, each a range into the cells pool.
400    #[inline]
401    pub(crate) fn rows_at(&self, range: PoolRange) -> &[PoolRange] {
402        &self.rows[range.as_range()]
403    }
404
405    /// The cells of one table row.
406    #[inline]
407    pub(crate) fn cells_at(&self, range: PoolRange) -> &[TableCell] {
408        &self.cells[range.as_range()]
409    }
410
411    /// The column specifications of a table.
412    #[inline]
413    pub(crate) fn cols_at(&self, range: PoolRange) -> &[ColSpec] {
414        &self.cols[range.as_range()]
415    }
416
417    // -- builder side --------------------------------------------------------
418
419    #[inline]
420    fn push(&mut self, node: Node) -> DocId {
421        let id = pool_len(self.nodes.len(), "node");
422        self.nodes.push(node);
423        DocId(id)
424    }
425
426    /// Copies `s` into the shared text pool and returns its byte range.
427    fn intern(&mut self, s: &str) -> PoolRange {
428        let start = pool_len(self.text.len(), "text");
429        self.text.push_str(s);
430        let end = pool_len(self.text.len(), "text");
431        PoolRange { start, end }
432    }
433
434    /// Creates an atom: a text, already in its final form (escaped if the
435    /// output format needs it), that the printer writes as one unit.
436    ///
437    /// The printer never splits an atom at the width limit (an atom wider than
438    /// the room left on the line is written whole, and the line is longer than
439    /// the width) and never changes it. An atom's width is measured in display
440    /// columns ([`display_width`](super::display_width)).
441    ///
442    /// # Requirements
443    ///
444    /// An atom must not contain `'\n'`: a line break is expressed with
445    /// [`hardline`](Self::hardline) or [`blocksep`](Self::blocksep). It must
446    /// not contain `'\t'` either, which has no fixed display width: an emitter
447    /// expands tabs into spaces when it builds atoms, or writes text holding
448    /// tabs through [`raw`](Self::raw).
449    ///
450    /// # Panics
451    ///
452    /// In a debug build, if `s` contains `'\n'` or `'\t'`: the requirements
453    /// above are checked by a debug assertion. A release build writes such an
454    /// atom as it is, and the column count of that line is then wrong. In any
455    /// build, if the arena's node or text pool would overflow (see
456    /// [`DocBuf`]).
457    pub fn text(&mut self, s: &str) -> DocId {
458        debug_assert!(
459            !s.contains('\n'),
460            "text atoms must not contain newlines; use hardline()/blocksep()"
461        );
462        debug_assert!(
463            !s.contains('\t'),
464            "text atoms must not contain tabs; expand them or use raw()"
465        );
466        let range = self.intern(s);
467        self.push(Node::Text(range))
468    }
469
470    /// Creates a break opportunity that prints as one space if the enclosing
471    /// group stays on one line (prints *flat*), and as a line break if the
472    /// group breaks.
473    ///
474    /// The space is written only when a content character follows it on the
475    /// same line: an unbroken `line` at the end of a line leaves no trailing
476    /// whitespace, and an unbroken `line` at the start of a line is dropped.
477    ///
478    /// # Panics
479    ///
480    /// If the arena's node pool would overflow (see [`DocBuf`]).
481    pub fn line(&mut self) -> DocId {
482        self.push(Node::Line)
483    }
484
485    /// Creates a break opportunity that prints as nothing if the enclosing
486    /// group stays on one line, and as a line break if the group breaks.
487    ///
488    /// # Panics
489    ///
490    /// If the arena's node pool would overflow (see [`DocBuf`]).
491    pub fn softbreak(&mut self) -> DocId {
492        self.push(Node::SoftBreak)
493    }
494
495    /// Creates an unconditional line break. It also makes every enclosing
496    /// group break, because a group that contains a line break cannot print
497    /// on one line.
498    ///
499    /// Two adjacent `hardline`s produce a single newline: blank lines come only
500    /// from [`blocksep`](Self::blocksep).
501    ///
502    /// # Panics
503    ///
504    /// If the arena's node pool would overflow (see [`DocBuf`]).
505    pub fn hardline(&mut self) -> DocId {
506        self.push(Node::HardLine)
507    }
508
509    /// Indents `child` by `columns` columns more than the enclosing
510    /// indentation.
511    ///
512    /// The indentation applies from the next line start on: it is a unit of
513    /// the printer's indentation stack, written at the start of every line
514    /// that begins inside `child`.
515    ///
516    /// # Panics
517    ///
518    /// If the arena's node pool would overflow (see [`DocBuf`]).
519    pub fn nest(&mut self, columns: u16, child: DocId) -> DocId {
520        self.push(Node::Nest {
521            indent: columns,
522            child,
523        })
524    }
525
526    /// Indents `child` to the column at which it starts: a hanging indent.
527    ///
528    /// The second and later lines of `child` start under its first character.
529    /// `text("  • ")` followed by `align(body)` lays out a list item whose
530    /// wrapped lines start under the item's first word. If that column is to
531    /// the left of the enclosing indentation (which can happen when a deeper
532    /// `nest` starts in the middle of a line), the enclosing indentation
533    /// applies instead.
534    ///
535    /// # Panics
536    ///
537    /// If the arena's node pool would overflow (see [`DocBuf`]).
538    pub fn align(&mut self, child: DocId) -> DocId {
539        self.push(Node::Align { child })
540    }
541
542    /// Creates a group: a unit whose break opportunities all stay unbroken or
543    /// all break.
544    ///
545    /// The printer prints `child` flat (every `line` a space, every
546    /// `softbreak` nothing) if `child`, *together with everything that follows
547    /// it on the same line*, fits within the width; otherwise every break
548    /// opportunity directly inside `child` becomes a line break (the break
549    /// opportunities inside a nested group follow that group's own decision).
550    /// The [printer](super::printer)'s module documentation describes the
551    /// exact test.
552    ///
553    /// # Panics
554    ///
555    /// If the arena's node pool would overflow (see [`DocBuf`]).
556    pub fn group(&mut self, child: DocId) -> DocId {
557        self.push(Node::Group { child })
558    }
559
560    /// Creates a sequence of the nodes `ids`, printed in that order.
561    ///
562    /// # Panics
563    ///
564    /// If the arena's node or children pool would overflow (see [`DocBuf`]).
565    pub fn concat(&mut self, ids: &[DocId]) -> DocId {
566        let start = pool_len(self.children.len(), "children");
567        self.children.extend_from_slice(ids);
568        let end = pool_len(self.children.len(), "children");
569        self.push(Node::Concat(PoolRange { start, end }))
570    }
571
572    /// Creates a separation between two blocks: a line break followed by
573    /// `blank_lines` blank lines.
574    ///
575    /// Adjacent requests for a line break are merged into one, which keeps the
576    /// larger number of blank lines (the numbers are never added), so nested
577    /// containers can each ask for the separation they need without producing
578    /// runs of blank lines. A line break at the very start or end of the
579    /// output is dropped.
580    ///
581    /// # Panics
582    ///
583    /// If the arena's node pool would overflow (see [`DocBuf`]).
584    pub fn blocksep(&mut self, blank_lines: u8) -> DocId {
585        self.push(Node::BlockSep { blank_lines })
586    }
587
588    /// Writes `prefix` before every line of `child` (`> ` for a quotation,
589    /// `// ` for a comment block).
590    ///
591    /// The prefix is a unit of the indentation stack, like an indentation
592    /// written as text rather than spaces: it combines with `nest` and `align`
593    /// in nesting order, and its width is subtracted from the width available
594    /// for wrapping (text inside `prefix("> ", ..)` wraps two columns earlier).
595    /// A blank line inside `child` is written with the prefix trimmed of
596    /// trailing whitespace (`>`), so a quoted passage remains one quotation
597    /// across its paragraphs.
598    ///
599    /// # Examples
600    ///
601    /// Two paragraphs inside one prefix: the blank line between them is
602    /// written with the prefix trimmed of its trailing space.
603    ///
604    /// ```
605    /// use flm_core::layout::{DocBuf, Profile, print};
606    ///
607    /// let mut b = DocBuf::new();
608    /// let first = b.text("one");
609    /// let gap = b.blocksep(1);
610    /// let second = b.text("two");
611    /// let body = b.concat(&[first, gap, second]);
612    /// let quoted = b.prefix("> ", body);
613    ///
614    /// assert_eq!(print(&b, quoted, &Profile::new(Some(40))), "> one\n>\n> two\n");
615    /// ```
616    ///
617    /// # Requirements
618    ///
619    /// Like an atom, a prefix must not contain `'\n'` or `'\t'`.
620    ///
621    /// # Panics
622    ///
623    /// In a debug build, if `prefix` contains `'\n'` or `'\t'`: the
624    /// requirement above is checked by a debug assertion. In any build, if the
625    /// arena's node or text pool would overflow (see [`DocBuf`]).
626    pub fn prefix(&mut self, prefix: &str, child: DocId) -> DocId {
627        debug_assert!(
628            !prefix.contains('\n'),
629            "a line prefix must not contain newlines"
630        );
631        debug_assert!(!prefix.contains('\t'), "a line prefix must not contain tabs");
632        let range = self.intern(prefix);
633        self.push(Node::Prefix {
634            prefix: range,
635            child,
636        })
637    }
638
639    /// Creates a verbatim block: text written as it is, never reflowed, never
640    /// split and never escaped.
641    ///
642    /// Unlike an atom, `content` **may** contain `'\n'` and `'\t'`. A newline
643    /// inside `content` is part of the content, not a request for a line
644    /// break, so runs of blank lines inside the block are kept exactly. A
645    /// newline at the end of `content` is treated as a request for a line
646    /// break and merged with the requests around it, so `raw("code\n")`
647    /// followed by `blocksep(1)` gives one blank line, not two. An empty
648    /// `content` prints nothing. `policy` says whether the enclosing
649    /// indentation applies to the lines of the block.
650    ///
651    /// A block of several lines makes its enclosing groups break; a block of
652    /// one line is measured like an atom. Tabs are written unchanged and
653    /// counted as one column each. The printer never breaks a raw line,
654    /// regardless of its width: a raw line longer than the line width is written
655    /// as it is.
656    ///
657    /// # Panics
658    ///
659    /// If the arena's node or text pool would overflow (see [`DocBuf`]).
660    pub fn raw(&mut self, content: &str, policy: RawPolicy) -> DocId {
661        let range = self.intern(content);
662        self.push(Node::Raw {
663            content: range,
664            policy,
665        })
666    }
667
668    /// Marks `child`, so that [`print_full`](super::print_full) reports where
669    /// it is printed, under the identifier `id`.
670    ///
671    /// A mark has no width and does not change the layout: the printer prints
672    /// `child` as if the mark were not there, and records one
673    /// [`MarkSpan`](super::MarkSpan) in the result of
674    /// [`print_full`](super::print_full). Marks may be nested; a marked node
675    /// that appears several times in the document (a shared node) is reported
676    /// once per occurrence.
677    ///
678    /// # Panics
679    ///
680    /// If the arena's node pool would overflow (see [`DocBuf`]).
681    pub fn mark(&mut self, id: MarkId, child: DocId) -> DocId {
682        self.push(Node::Mark { id, child })
683    }
684
685    /// Creates a table: one [`ColSpec`] per column in `cols`, and the rows of
686    /// cells in `rows`.
687    ///
688    /// Each cell is a [`TableCell`]: any node of the same arena and,
689    /// optionally, an alignment of its own that replaces its column's for that
690    /// cell alone. A row may be given as [`DocId`]s, which are cells that
691    /// follow their columns. Rows may have fewer cells than there are columns
692    /// (the missing cells at the end of a row are empty); cells beyond
693    /// `cols.len()` are ignored. `header_rows` is the number of leading rows
694    /// that form the header; a rule is drawn after them (`0` means no
695    /// header). `frame` is how the table is drawn around and between its
696    /// cells ([`TableFrame`]): a gutter of two spaces between the columns and
697    /// a rule of `-`, or a frame of box-drawing characters.
698    ///
699    /// `border_mark`, when given, is the mark under which
700    /// [`print_full`](super::print_full) reports the characters the table
701    /// draws itself: one [`MarkSpan`](super::MarkSpan) per maximal run of
702    /// such characters on a line (a whole rule or frame line; each bar of a
703    /// line of the rows on its own; the padding spaces are not part of any
704    /// run), in the order they are written, after the spans of the marks
705    /// opened before the table.
706    ///
707    /// # How the columns are laid out
708    ///
709    /// The printer lays a table out in four steps:
710    ///
711    /// 1. **Measure.** Every cell is printed twice on its own: at width 1,
712    ///    where every break opportunity breaks, and with no width limit, where
713    ///    only unconditional line breaks break. A column's *minimum* is the
714    ///    widest line of its cells printed at width 1 (its widest part that
715    ///    cannot be broken, indentation included); its *maximum* is the widest
716    ///    line printed with no limit. A cell can be wider at width 1 than with
717    ///    no limit (when its indentation grows as it breaks), so the maximum is
718    ///    raised to the minimum where it is smaller.
719    /// 2. **Compute the widths.** The available width is the profile's width
720    ///    minus the enclosing indentation and the table's own drawing: the
721    ///    gutters (two spaces between adjacent columns) under
722    ///    [`TableFrame::Gutter`], three columns per column and one more under
723    ///    [`TableFrame::Box`] (a bar and two spaces of padding per column, and
724    ///    the closing bar). If the maxima of all columns fit, or the profile
725    ///    has no width, each column gets its maximum. Otherwise each column
726    ///    starts at its minimum, and the remaining width is shared out in
727    ///    proportion to each column's room to grow (maximum minus minimum), in
728    ///    whole columns: each column first gets the whole part of its share,
729    ///    then the columns with the largest fractional parts get one more
730    ///    column each until the width is used up (on equal fractional parts,
731    ///    the column further left first), and no column grows past its
732    ///    maximum. If even the minima do not fit, every column gets its minimum
733    ///    and the lines are longer than the width, because atoms are never
734    ///    split.
735    /// 3. **Print the cells.** Every cell is printed at its column's width with
736    ///    an empty indentation stack; the table's own indentation applies to
737    ///    the assembled lines, so a table inside a list or a quotation is
738    ///    indented and prefixed correctly.
739    /// 4. **Assemble.** The rows are assembled line by line, with every cell
740    ///    at the top of its row: a row is as tall as its tallest cell. Each
741    ///    cell is padded to its column's width in its own alignment, or in its
742    ///    column's where it has none. Under [`TableFrame::Gutter`], columns are
743    ///    separated by the gutter, trailing whitespace is removed from every
744    ///    line (the padding, and any trailing whitespace of the last cell's
745    ///    own text), and the rule of `-` follows the header rows. Under
746    ///    [`TableFrame::Box`], every line of the rows ends with its closing
747    ///    bar, the frame's lines come above the first row and below the last,
748    ///    and its rule follows the header rows when rows follow them.
749    ///
750    /// A table is a block: it starts on a line of its own and ends its last
751    /// line. A table that prints nothing (no columns, no rows, or only empty
752    /// cells) is not a block and leaves the surrounding line as it is.
753    ///
754    /// The marks inside the cells are reported where the cells' text lands in
755    /// the table, after the spans of the marks opened before the table and
756    /// after the runs of the border mark, row by row and column by column. A
757    /// mark over several lines of a cell gives one span per line of the
758    /// cell, because the table interleaves the cell's lines with the rest of
759    /// the row (see the [`printer`](super::printer) module, section 5).
760    ///
761    /// # Examples
762    ///
763    /// ```
764    /// use flm_core::layout::{ColSpec, DocBuf, Profile, TableFrame, print};
765    ///
766    /// let mut b = DocBuf::new();
767    /// let name = b.text("name");
768    /// let count = b.text("count");
769    /// let alpha = b.text("alpha");
770    /// let three = b.text("3");
771    /// let t = b.table(
772    ///     &[ColSpec::left(), ColSpec::right()],
773    ///     &[&[name, count], &[alpha, three]],
774    ///     1,
775    ///     TableFrame::Gutter,
776    ///     None,
777    /// );
778    ///
779    /// assert_eq!(
780    ///     print(&b, t, &Profile::new(Some(40))),
781    ///     "name   count\n-----  -----\nalpha      3\n"
782    /// );
783    /// ```
784    ///
785    /// A cell with an alignment of its own, in a left-aligned column:
786    ///
787    /// ```
788    /// use flm_core::layout::{ColAlign, ColSpec, DocBuf, Profile, TableCell, TableFrame, print};
789    ///
790    /// let mut b = DocBuf::new();
791    /// let wide = b.text("a wide cell");
792    /// let right = b.text("right");
793    /// let t = b.table(
794    ///     &[ColSpec::left()],
795    ///     &[&[TableCell::new(wide)], &[TableCell::aligned(right, ColAlign::Right)]],
796    ///     0,
797    ///     TableFrame::Gutter,
798    ///     None,
799    /// );
800    ///
801    /// assert_eq!(print(&b, t, &Profile::new(Some(40))), "a wide cell\n      right\n");
802    /// ```
803    ///
804    /// A framed table, with the characters it draws reported under a mark:
805    ///
806    /// ```
807    /// use flm_core::layout::{ColSpec, DocBuf, MarkId, Profile, TableFrame, print_full};
808    ///
809    /// let mut b = DocBuf::new();
810    /// let name = b.text("name");
811    /// let alpha = b.text("alpha");
812    /// let t = b.table(
813    ///     &[ColSpec::left()],
814    ///     &[&[name], &[alpha]],
815    ///     1,
816    ///     TableFrame::Box,
817    ///     Some(MarkId(0)),
818    /// );
819    ///
820    /// let out = print_full(&b, t, &Profile::new(Some(40)));
821    /// assert_eq!(out.text, "┌───────┐\n│ name  │\n├───────┤\n│ alpha │\n└───────┘\n");
822    /// let runs: Vec<&str> = out.marks.iter().map(|m| &out.text[m.bytes.clone()]).collect();
823    /// assert_eq!(runs, ["┌───────┐", "│", "│", "├───────┤", "│", "│", "└───────┘"]);
824    /// ```
825    ///
826    /// # Panics
827    ///
828    /// If the arena's node, column, row, cell or table pool would overflow
829    /// (see [`DocBuf`]).
830    pub fn table<C>(
831        &mut self,
832        cols: &[ColSpec],
833        rows: &[&[C]],
834        header_rows: u8,
835        frame: TableFrame,
836        border_mark: Option<MarkId>,
837    ) -> DocId
838    where
839        C: Copy + Into<TableCell>,
840    {
841        let cols_start = pool_len(self.cols.len(), "column");
842        self.cols.extend_from_slice(cols);
843        let cols_end = pool_len(self.cols.len(), "column");
844
845        let rows_start = pool_len(self.rows.len(), "row");
846        // Two passes so that the rows pool stays contiguous for this table.
847        let mut ranges = Vec::with_capacity(rows.len());
848        for row in rows {
849            let start = pool_len(self.cells.len(), "cell");
850            self.cells.extend(row.iter().map(|&cell| cell.into()));
851            let end = pool_len(self.cells.len(), "cell");
852            ranges.push(PoolRange { start, end });
853        }
854        self.rows.extend_from_slice(&ranges);
855        let rows_end = pool_len(self.rows.len(), "row");
856
857        let def = pool_len(self.tables.len(), "table");
858        self.tables.push(TableDef {
859            rows: PoolRange {
860                start: rows_start,
861                end: rows_end,
862            },
863            cols: PoolRange {
864                start: cols_start,
865                end: cols_end,
866            },
867            header_rows,
868            frame,
869            border_mark,
870        });
871        self.push(Node::Table { def })
872    }
873
874    /// Creates prose: the words of `s`, separated by spaces that each break
875    /// independently of the others.
876    ///
877    /// This is a combination of the other constructors, and its exact shape
878    /// matters: each space between two words is its own `group(line())`, so
879    /// each space decides on its own whether to stay a space or become a line
880    /// break. Because the printer's test for a group looks past the group to
881    /// what follows on the line, this gives correct greedy wrapping, including
882    /// before a trailing text that has no break opportunity of its own. One
883    /// group around a whole paragraph would instead give one line longer than
884    /// the width, or a line break at every space.
885    ///
886    /// `s` is split at breakable whitespace ([`is_breakable_space`]), which is
887    /// dropped; the words become atoms. A non-breaking space (U+00A0 no-break
888    /// space, U+2007 figure space, U+202F narrow no-break space) stays inside
889    /// the word it joins, so an author's request not to break there is kept.
890    /// An `s` holding only breakable whitespace gives an empty sequence.
891    ///
892    /// # Panics
893    ///
894    /// If the arena's node, text or children pool would overflow (see
895    /// [`DocBuf`]).
896    pub fn fill_words(&mut self, s: &str) -> DocId {
897        let mut parts: Vec<DocId> = Vec::new();
898        for word in s.split(is_breakable_space).filter(|word| !word.is_empty()) {
899            if !parts.is_empty() {
900                let l = self.line();
901                parts.push(self.group(l));
902            }
903            parts.push(self.text(word));
904        }
905        self.concat(&parts)
906    }
907}
908
909/// Returns whether `c` is whitespace at which a line may break: every Unicode
910/// whitespace character except the non-breaking spaces (U+00A0 no-break
911/// space, U+2007 figure space, U+202F narrow no-break space), which join the
912/// words on either side of them into one word.
913///
914/// [`DocBuf::fill_words`] splits its text into words with this function. An
915/// emitter that splits text into words itself, before building atoms, uses
916/// the same function, so that both split at the same characters.
917pub fn is_breakable_space(c: char) -> bool {
918    c.is_whitespace() && !matches!(c, '\u{00A0}' | '\u{2007}' | '\u{202F}')
919}