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