pub struct DocBuf { /* private fields */ }Expand description
A layout document: an arena of layout nodes, with its pools of text, children, rows, cells, columns and tables.
An emitter builds a layout document by calling the constructors
(text, line, group, …),
innermost parts first. Each returns the DocId of the node it creates,
which the emitter passes to the constructors of the enclosing nodes; the
id of the outermost node is the root that print and
print_full take. The module documentation
lists the constructors and describes the representation.
§Requirements
An id is meaningful only for the arena that created it, and
clear makes every id given out before it meaningless;
giving such an id to the printer is a caller error (see
print).
§Panics
Every constructor panics if the arena or one of its pools would grow past
u32::MAX entries (about four billion nodes, children, rows, cells,
columns or tables, or four gigabytes of text), a size no document reaches;
the panic message gives the pool.
Implementations§
Source§impl DocBuf
impl DocBuf
Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Removes every node and pool entry and keeps the allocated capacity, so
that the arena can be reused for the next render. Every DocId given
out before the call becomes meaningless.
Sourcepub fn text(&mut self, s: &str) -> DocId
pub fn text(&mut self, s: &str) -> DocId
Creates an atom: a text, already in its final form (escaped if the output format needs it), that the printer writes as one unit.
The printer never splits an atom at the width limit (an atom wider than
the room left on the line is written whole, and the line is longer than
the width) and never changes it. An atom’s width is measured in display
columns (display_width).
§Requirements
An atom must not contain '\n': a line break is expressed with
hardline or blocksep. It must
not contain '\t' either, which has no fixed display width: an emitter
expands tabs into spaces when it builds atoms, or writes text holding
tabs through raw.
§Panics
In a debug build, if s contains '\n' or '\t': the requirements
above are checked by a debug assertion. A release build writes such an
atom as it is, and the column count of that line is then wrong. In any
build, if the arena’s node or text pool would overflow (see
DocBuf).
Sourcepub fn line(&mut self) -> DocId
pub fn line(&mut self) -> DocId
Creates a break opportunity that prints as one space if the enclosing group stays on one line (prints flat), and as a line break if the group breaks.
The space is written only when a content character follows it on the
same line: an unbroken line at the end of a line leaves no trailing
whitespace, and an unbroken line at the start of a line is dropped.
§Panics
If the arena’s node pool would overflow (see DocBuf).
Sourcepub fn align(&mut self, child: DocId) -> DocId
pub fn align(&mut self, child: DocId) -> DocId
Indents child to the column at which it starts: a hanging indent.
The second and later lines of child start under its first character.
text(" • ") followed by align(body) lays out a list item whose
wrapped lines start under the item’s first word. If that column is to
the left of the enclosing indentation (which can happen when a deeper
nest starts in the middle of a line), the enclosing indentation
applies instead.
§Panics
If the arena’s node pool would overflow (see DocBuf).
Sourcepub fn group(&mut self, child: DocId) -> DocId
pub fn group(&mut self, child: DocId) -> DocId
Creates a group: a unit whose break opportunities all stay unbroken or all break.
The printer prints child flat (every line a space, every
softbreak nothing) if child, together with everything that follows
it on the same line, fits within the width; otherwise every break
opportunity directly inside child becomes a line break (the break
opportunities inside a nested group follow that group’s own decision).
The printer’s module documentation describes the
exact test.
§Panics
If the arena’s node pool would overflow (see DocBuf).
Sourcepub fn blocksep(&mut self, blank_lines: u8) -> DocId
pub fn blocksep(&mut self, blank_lines: u8) -> DocId
Creates a separation between two blocks: a line break followed by
blank_lines blank lines.
Adjacent requests for a line break are merged into one, which keeps the larger number of blank lines (the numbers are never added), so nested containers can each ask for the separation they need without producing runs of blank lines. A line break at the very start or end of the output is dropped.
§Panics
If the arena’s node pool would overflow (see DocBuf).
Sourcepub fn prefix(&mut self, prefix: &str, child: DocId) -> DocId
pub fn prefix(&mut self, prefix: &str, child: DocId) -> DocId
Writes prefix before every line of child (> for a quotation,
// for a comment block).
The prefix is a unit of the indentation stack, like an indentation
written as text rather than spaces: it combines with nest and align
in nesting order, and its width is subtracted from the width available
for wrapping (text inside prefix("> ", ..) wraps two columns earlier).
A blank line inside child is written with the prefix trimmed of
trailing whitespace (>), so a quoted passage remains one quotation
across its paragraphs.
§Examples
Two paragraphs inside one prefix: the blank line between them is written with the prefix trimmed of its trailing space.
use flm_core::layout::{DocBuf, Profile, print};
let mut b = DocBuf::new();
let first = b.text("one");
let gap = b.blocksep(1);
let second = b.text("two");
let body = b.concat(&[first, gap, second]);
let quoted = b.prefix("> ", body);
assert_eq!(print(&b, quoted, &Profile::new(Some(40))), "> one\n>\n> two\n");§Requirements
Like an atom, a prefix must not contain '\n' or '\t'.
§Panics
In a debug build, if prefix contains '\n' or '\t': the
requirement above is checked by a debug assertion. In any build, if the
arena’s node or text pool would overflow (see DocBuf).
Sourcepub fn raw(&mut self, content: &str, policy: RawPolicy) -> DocId
pub fn raw(&mut self, content: &str, policy: RawPolicy) -> DocId
Creates a verbatim block: text written as it is, never reflowed, never split and never escaped.
Unlike an atom, content may contain '\n' and '\t'. A newline
inside content is part of the content, not a request for a line
break, so runs of blank lines inside the block are kept exactly. A
newline at the end of content is treated as a request for a line
break and merged with the requests around it, so raw("code\n")
followed by blocksep(1) gives one blank line, not two. An empty
content prints nothing. policy says whether the enclosing
indentation applies to the lines of the block.
A block of several lines makes its enclosing groups break; a block of one line is measured like an atom. Tabs are written unchanged and counted as one column each. The printer never breaks a raw line, regardless of its width: a raw line longer than the line width is written as it is.
§Panics
If the arena’s node or text pool would overflow (see DocBuf).
Sourcepub fn mark(&mut self, id: MarkId, child: DocId) -> DocId
pub fn mark(&mut self, id: MarkId, child: DocId) -> DocId
Marks child, so that print_full reports where
it is printed, under the identifier id.
A mark has no width and does not change the layout: the printer prints
child as if the mark were not there, and records one
MarkSpan in the result of
print_full. Marks may be nested; a marked node
that appears several times in the document (a shared node) is reported
once per occurrence.
§Panics
If the arena’s node pool would overflow (see DocBuf).
Sourcepub fn table<C>(
&mut self,
cols: &[ColSpec],
rows: &[&[C]],
header_rows: u8,
frame: TableFrame,
border_mark: Option<MarkId>,
) -> DocId
pub fn table<C>( &mut self, cols: &[ColSpec], rows: &[&[C]], header_rows: u8, frame: TableFrame, border_mark: Option<MarkId>, ) -> DocId
Creates a table: one ColSpec per column in cols, and the rows of
cells in rows.
Each cell is a TableCell: any node of the same arena and,
optionally, an alignment of its own that replaces its column’s for that
cell alone. A row may be given as DocIds, which are cells that
follow their columns. Rows may have fewer cells than there are columns
(the missing cells at the end of a row are empty); cells beyond
cols.len() are ignored. header_rows is the number of leading rows
that form the header; a rule is drawn after them (0 means no
header). frame is how the table is drawn around and between its
cells (TableFrame): a gutter of two spaces between the columns and
a rule of -, or a frame of box-drawing characters.
border_mark, when given, is the mark under which
print_full reports the characters the table
draws itself: one MarkSpan per maximal run of
such characters on a line (a whole rule or frame line; each bar of a
line of the rows on its own; the padding spaces are not part of any
run), in the order they are written, after the spans of the marks
opened before the table.
§How the columns are laid out
The printer lays a table out in four steps:
- Measure. Every cell is printed twice on its own: at width 1, where every break opportunity breaks, and with no width limit, where only unconditional line breaks break. A column’s minimum is the widest line of its cells printed at width 1 (its widest part that cannot be broken, indentation included); its maximum is the widest line printed with no limit. A cell can be wider at width 1 than with no limit (when its indentation grows as it breaks), so the maximum is raised to the minimum where it is smaller.
- Compute the widths. The available width is the profile’s width
minus the enclosing indentation and the table’s own drawing: the
gutters (two spaces between adjacent columns) under
TableFrame::Gutter, three columns per column and one more underTableFrame::Box(a bar and two spaces of padding per column, and the closing bar). If the maxima of all columns fit, or the profile has no width, each column gets its maximum. Otherwise each column starts at its minimum, and the remaining width is shared out in proportion to each column’s room to grow (maximum minus minimum), in whole columns: each column first gets the whole part of its share, then the columns with the largest fractional parts get one more column each until the width is used up (on equal fractional parts, the column further left first), and no column grows past its maximum. If even the minima do not fit, every column gets its minimum and the lines are longer than the width, because atoms are never split. - Print the cells. Every cell is printed at its column’s width with an empty indentation stack; the table’s own indentation applies to the assembled lines, so a table inside a list or a quotation is indented and prefixed correctly.
- Assemble. The rows are assembled line by line, with every cell
at the top of its row: a row is as tall as its tallest cell. Each
cell is padded to its column’s width in its own alignment, or in its
column’s where it has none. Under
TableFrame::Gutter, columns are separated by the gutter, trailing whitespace is removed from every line (the padding, and any trailing whitespace of the last cell’s own text), and the rule of-follows the header rows. UnderTableFrame::Box, every line of the rows ends with its closing bar, the frame’s lines come above the first row and below the last, and its rule follows the header rows when rows follow them.
A table is a block: it starts on a line of its own and ends its last line. A table that prints nothing (no columns, no rows, or only empty cells) is not a block and leaves the surrounding line as it is.
The marks inside the cells are reported where the cells’ text lands in
the table, after the spans of the marks opened before the table and
after the runs of the border mark, row by row and column by column. A
mark over several lines of a cell gives one span per line of the
cell, because the table interleaves the cell’s lines with the rest of
the row (see the printer module, section 5).
§Examples
use flm_core::layout::{ColSpec, DocBuf, Profile, TableFrame, print};
let mut b = DocBuf::new();
let name = b.text("name");
let count = b.text("count");
let alpha = b.text("alpha");
let three = b.text("3");
let t = b.table(
&[ColSpec::left(), ColSpec::right()],
&[&[name, count], &[alpha, three]],
1,
TableFrame::Gutter,
None,
);
assert_eq!(
print(&b, t, &Profile::new(Some(40))),
"name count\n----- -----\nalpha 3\n"
);A cell with an alignment of its own, in a left-aligned column:
use flm_core::layout::{ColAlign, ColSpec, DocBuf, Profile, TableCell, TableFrame, print};
let mut b = DocBuf::new();
let wide = b.text("a wide cell");
let right = b.text("right");
let t = b.table(
&[ColSpec::left()],
&[&[TableCell::new(wide)], &[TableCell::aligned(right, ColAlign::Right)]],
0,
TableFrame::Gutter,
None,
);
assert_eq!(print(&b, t, &Profile::new(Some(40))), "a wide cell\n right\n");A framed table, with the characters it draws reported under a mark:
use flm_core::layout::{ColSpec, DocBuf, MarkId, Profile, TableFrame, print_full};
let mut b = DocBuf::new();
let name = b.text("name");
let alpha = b.text("alpha");
let t = b.table(
&[ColSpec::left()],
&[&[name], &[alpha]],
1,
TableFrame::Box,
Some(MarkId(0)),
);
let out = print_full(&b, t, &Profile::new(Some(40)));
assert_eq!(out.text, "┌───────┐\n│ name │\n├───────┤\n│ alpha │\n└───────┘\n");
let runs: Vec<&str> = out.marks.iter().map(|m| &out.text[m.bytes.clone()]).collect();
assert_eq!(runs, ["┌───────┐", "│", "│", "├───────┤", "│", "│", "└───────┘"]);§Panics
If the arena’s node, column, row, cell or table pool would overflow
(see DocBuf).
Sourcepub fn fill_words(&mut self, s: &str) -> DocId
pub fn fill_words(&mut self, s: &str) -> DocId
Creates prose: the words of s, separated by spaces that each break
independently of the others.
This is a combination of the other constructors, and its exact shape
matters: each space between two words is its own group(line()), so
each space decides on its own whether to stay a space or become a line
break. Because the printer’s test for a group looks past the group to
what follows on the line, this gives correct greedy wrapping, including
before a trailing text that has no break opportunity of its own. One
group around a whole paragraph would instead give one line longer than
the width, or a line break at every space.
s is split at breakable whitespace (is_breakable_space), which is
dropped; the words become atoms. A non-breaking space (U+00A0 no-break
space, U+2007 figure space, U+202F narrow no-break space) stays inside
the word it joins, so an author’s request not to break there is kept.
An s holding only breakable whitespace gives an empty sequence.
§Panics
If the arena’s node, text or children pool would overflow (see
DocBuf).
Trait Implementations§
Auto Trait Implementations§
impl Forget for DocBuf
impl Freeze for DocBuf
impl Move for DocBuf
impl RefUnwindSafe for DocBuf
impl Send for DocBuf
impl Sync for DocBuf
impl Unpin for DocBuf
impl UnsafeUnpin for DocBuf
impl UnwindSafe for DocBuf
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CheckedAs for T
impl<T> CheckedAs for T
Source§fn checked_as<Dst>(self) -> Option<Dst>where
T: CheckedCast<Dst>,
fn checked_as<Dst>(self) -> Option<Dst>where
T: CheckedCast<Dst>,
Source§impl<Src, Dst> CheckedCastFrom<Src> for Dstwhere
Src: CheckedCast<Dst>,
impl<Src, Dst> CheckedCastFrom<Src> for Dstwhere
Src: CheckedCast<Dst>,
Source§fn checked_cast_from(src: Src) -> Option<Dst>
fn checked_cast_from(src: Src) -> Option<Dst>
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more