pub struct DocBuf { /* private fields */ }Expand description
A layout document: an arena of layout nodes, with its pools of text, children, rows, cells, columns, tables and rules.
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, tables or rules, 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 flush_right(&mut self, child: DocId, gap: u16) -> DocId
pub fn flush_right(&mut self, child: DocId, gap: u16) -> DocId
Sets child on one line, at the right edge of the width where it fits
there, and otherwise gap columns after what precedes it on its line:
an equation’s number at the end of its formula’s last line.
child is printed on its own, with no width limit and no indentation,
and the line it prints is placed on the current line: its break
opportunities print as spaces (a softbreak as nothing), and its
width is the display width of that line. The node is placed as
follows:
- Where the profile has a width, and the columns before
childon its line (the indentation, the prefixes and the content already written there),gapand the width ofchildfit in it,childends at the last column of the width; spaces fill the columns before it. - Otherwise
childfollows what precedes it on its line aftergapspaces; at the start of a line, where nothing precedes it, it starts after the indentation, with no gap.
The space of an unbroken line directly before the node
is not counted among the columns before it: the spaces of the
placement replace it. The right edge is the profile’s width whatever
the indentation, and inside a table cell it is the
cell’s width, at which the cell is printed. A child that prints
nothing prints nothing and adds no space. The fitting scan (the
printer’s test of whether a group fits, see the
printer module) counts the node as an atom as wide
as gap plus the width of child, and as nothing when child prints
nothing; like the placement, it does not count the space of an
unbroken line directly before the node.
A mark around the node covers the text of child, not the spaces
before it; the marks inside child are reported where its text lands,
in the order they are opened, as anywhere else in the document.
§Examples
use flm_core::layout::{DocBuf, Profile, print};
let mut b = DocBuf::new();
let formula = b.text("E = mc^2");
let number = b.text("(1)");
let tag = b.flush_right(number, 4);
let line = b.concat(&[formula, tag]);
// At a width, the number ends at the last column of the width.
assert_eq!(print(&b, line, &Profile::new(Some(20))), "E = mc^2 (1)\n");
// With no width, or where it does not fit, it follows after the gap.
assert_eq!(print(&b, line, &Profile::new(None)), "E = mc^2 (1)\n");
assert_eq!(print(&b, line, &Profile::new(Some(12))), "E = mc^2 (1)\n");§Requirements
child must print on one line: it must hold no unconditional line
break (hardline, blocksep, a
raw block of several lines, a table or a
ruled node that prints something). This is a
requirement on the emitter’s code, like the requirements on an atom.
§Panics
The printer panics in a debug build if the printing of child holds a
line break: the requirement above is checked by a debug assertion. A
release build writes that printing as it is, and the line and column
counts of the output are then wrong. In any build, this constructor
panics if the arena’s node pool would overflow (see DocBuf).
Sourcepub fn ruled(
&mut self,
child: DocId,
rule: char,
above: bool,
below: bool,
mark: Option<MarkId>,
) -> DocId
pub fn ruled( &mut self, child: DocId, rule: char, above: bool, below: bool, mark: Option<MarkId>, ) -> DocId
Sets child on lines of its own, with a rule line above it if
above and under it if below: rule repeated to the display width
of the widest line that child prints, written under the same
indentation and prefixes as the lines of child. A heading underlined
with =, a title between two rules.
child is printed on its own, at the width that the enclosing
indentation leaves (with no width limit where the profile has none)
and with an empty indentation stack; its lines are then written under
the node’s indentation stack, as a table’s lines are, a blank line of
child with that stack trimmed of trailing whitespace. The width of a
line of child does not count the enclosing indentation, so the rule
is as wide as the widest line of the child’s own text, a line it
wraps included.
The node is a block: it starts on a line of its own and ends its last
line. A child that prints nothing makes the node print nothing: no
rule line, and no line break, as for a table that prints nothing. The
fitting scan treats the node as a block, except where child prints
nothing.
mark, when given, is the mark under which
print_full reports the rule lines, one
MarkSpan per line, as a table reports its border.
The marks inside child are reported where its text lands; a mark over
several lines of child gives one span, as anywhere else in the
document. The spans come in the order of the output: the rule line
above, the marks inside child, the rule line under it.
§Examples
use flm_core::layout::{DocBuf, MarkId, Profile, print, print_full};
let mut b = DocBuf::new();
let title = b.fill_words("Bounds on approximate codes");
let ruled = b.ruled(title, '=', true, true, Some(MarkId(0)));
// The title wraps; the rules are as wide as its widest line.
let out = print_full(&b, ruled, &Profile::new(Some(20)));
assert_eq!(
out.text,
"=================\nBounds on\napproximate codes\n=================\n"
);
let rules: Vec<&str> = out.marks.iter().map(|m| &out.text[m.bytes.clone()]).collect();
assert_eq!(rules, ["=================", "================="]);
// Under an indentation, the rule is written after it.
let heading = b.text("Introduction");
let underlined = b.ruled(heading, '-', false, true, None);
let indented = b.nest(2, underlined);
assert_eq!(
print(&b, indented, &Profile::new(Some(40))),
" Introduction\n ------------\n"
);§Requirements
rule must be one column wide (display_width
of 1); in particular it is not '\n' or '\t'.
§Panics
In a debug build, if rule is not one column wide: the requirement
above is checked by a debug assertion. In any build, if the arena’s
node or rule 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 DocBufwhere
*const u8 is !null: Freeze,
PhantomData<Node>: Freeze,
PhantomData<u8>: Freeze,
PhantomData<DocId>: Freeze,
PhantomData<PoolRange>: Freeze,
PhantomData<TableCell>: Freeze,
PhantomData<ColSpec>: Freeze,
PhantomData<TableDef>: Freeze,
PhantomData<RuledDef>: Freeze,
impl Move for DocBuf
impl RefUnwindSafe for DocBuf
impl Send for DocBufwhere
RawVecInner: Send,
impl Sync for DocBufwhere
RawVecInner: Sync,
impl Unpin for DocBuf
impl UnsafeUnpin for DocBufwhere
*const u8 is !null: UnsafeUnpin,
PhantomData<Node>: UnsafeUnpin,
PhantomData<u8>: UnsafeUnpin,
PhantomData<DocId>: UnsafeUnpin,
PhantomData<PoolRange>: UnsafeUnpin,
PhantomData<TableCell>: UnsafeUnpin,
PhantomData<ColSpec>: UnsafeUnpin,
PhantomData<TableDef>: UnsafeUnpin,
PhantomData<RuledDef>: UnsafeUnpin,
impl UnwindSafe for DocBufwhere
RawVecInner: UnwindSafe,
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