Skip to main content

flm_core/stdlib/backends/text/
feature.rs

1//! The `text` feature: it registers the text backend, its native element
2//! set, its stages and tables, its render options, the `text` output and the
3//! `text` workflow.
4//!
5//! A feature ([`FlmFeature`]) contributes a related bundle of things to a
6//! registry. The `text` feature ([`TextBackend`], obtained as a shared value
7//! from [`feature()`]) registers next to the `lowering` feature
8//! ([`LoweringFeature`](crate::stdlib::backends::lowering::LoweringFeature)),
9//! which registers the presentation vocabulary and the shared lowering rules,
10//! and next to the `pieces` and `check` features; [`feature()`] lists what each
11//! of them provides to this one.
12//!
13//! # The elements the backend writes natively
14//!
15//! The backend's native set ([`native_elements`]) is the whole [presentation
16//! vocabulary](crate::stdlib::backends::pres) plus the six [structural
17//! elements](crate::lang::structural::StructuralElements) of [`FLOW_THROUGH`],
18//! whose meaning plain text does not need to translate: `flm.text`,
19//! `flm.group`, `flm.opaque-wrapper`, `flm.comment`, `flm.container` and
20//! `flm.parbreak`. The
21//! paragraph-break element `flm.parbreak` is in that list because the
22//! block-structure pass carries an [opaque
23//! region](crate::guide::concepts_overview#opaque-regions), such as
24//! mathematics, over unchanged and leaves the paragraph breaks inside it in
25//! place. The emitter treats it as a
26//! separation between blocks in a run of blocks (including the top level of a
27//! tree that no block-structure pass has gone over), and as a space inside
28//! inline content.
29//!
30//! The native set holds no element of another feature. Each feature registers
31//! lowering rules for its own elements, and the backend writes only the
32//! presentation elements those rules produce, so the backend never decides
33//! from outside a feature how that feature's content is printed. The
34//! `math-passthrough` feature, for instance, lowers its own fallback element
35//! into a `flm.pres.math-passthrough` node holding the original source.
36//!
37//! # What the `text` workflow demands
38//!
39//! The `text` [workflow](crate::core::registry::WorkflowDef) lists the `text`
40//! output and demands one capability beside it:
41//! [`flm.validated`](crate::stdlib::VALIDATED), a capability whose demand
42//! schedules every check the registry holds. A render of the `text` workflow
43//! therefore validates the document: a refused label type, a duplicate label
44//! or an error in mathematics content is reported exactly as by the [`check`
45//! workflow](crate::stdlib::CHECK_WORKFLOW), so a document gets the same
46//! diagnostics regardless of the workflow run over it. The capability
47//! `flm.validated` is declared by the `check` feature
48//! ([`check_feature`](crate::stdlib::check_feature)), so a registry offering
49//! this backend must hold that feature too; a registry without it fails to
50//! build, with an error that gives this workflow and the undeclared
51//! capability.
52//!
53//! Everything else the run needs follows from what the selected stages and
54//! lowering rules require, not from a list of demands: for instance, the
55//! lowering rule for paragraphs requires the capability
56//! `flm.blocks.structured`, which puts the block-structure rewrite into the
57//! plan.
58
59use std::sync::Arc;
60
61use crate::core::region::RegionsOutput;
62use crate::core::settings::SettingsDecl;
63use crate::stdlib::backends::lowering::REGIONS_SLOT;
64use crate::model::names::ElementName;
65use crate::model::options::Bind;
66use crate::core::registry::{
67    BackendDef, BuildError, FeatureBuilder, FeatureInfo, FlmFeature, OutputDef, WorkflowDef,
68};
69use crate::lang::structural;
70use crate::stdlib::VALIDATED;
71use crate::stdlib::backends::lowering::{LoweredTrees, lowered_table_name};
72use crate::stdlib::backends::pieces::{LoweredPieces, PiecesStage, lowered_pieces_table_name};
73use crate::stdlib::backends::pres;
74
75use super::emit::TEXT_OUTPUT;
76use super::stages::{
77    BACKEND, EXTENSION, MEDIA_TYPE, TEXT_DOCUMENT, TEXT_REGIONS, TextRegionsStage,
78    TextRenderOptions, WORKFLOW, stages,
79};
80
81/// The feature's registered name, `text`. It is also the middle part of the
82/// identifiers of the conditions this backend reports (`flm.text.*`).
83pub const FEATURE_NAME: &str = "text";
84
85/// The declaration of the feature's settings: the fields of
86/// [`TextRenderOptions`] are its settings keys, bound to the render request
87/// ([`Bind::Render`]). See [`crate::core::settings`].
88fn settings() -> SettingsDecl {
89    SettingsDecl::new(FEATURE_NAME)
90        .options::<TextRenderOptions>(
91            Bind::Render,
92            "the line width in columns (null: never wrap), default 80; the width of a tab in \
93            columns, default 4; the stop written after a run-in heading's title, default `.`, \
94            the empty text for none; whether a link to an address outside the document prints \
95            the address after its content, default on; whether a link whose content already \
96            shows its address prints the address too, default off; the heading level printed \
97            as a first-level heading, default 1; how a table is drawn, `none` (its columns two \
98            spaces apart, the default) or `box` (inside a frame of box-drawing characters); and \
99            the characters of the rules under the top two heading levels, `ascii` (`=` and \
100            `-`, the default) or `unicode` (`═` and `─`). Set per render request.",
101        )
102        .markup("run_in_stop")
103}
104
105/// The six [structural elements](crate::lang::structural::StructuralElements)
106/// the text backend writes natively, beside the presentation vocabulary:
107/// `flm.text`, `flm.group`, `flm.opaque-wrapper`, `flm.comment`,
108/// `flm.container` and `flm.parbreak` (see the module documentation).
109pub const FLOW_THROUGH: [&str; 6] = [
110    structural::TEXT,
111    structural::GROUP,
112    structural::OPAQUE_WRAPPER,
113    structural::COMMENT,
114    structural::CONTAINER,
115    structural::PARBREAK,
116];
117
118/// Returns the backend's native element set, the elements its emitter writes
119/// without a lowering rule: every element of the presentation vocabulary
120/// ([`pres::ALL`]), then the elements of [`FLOW_THROUGH`].
121///
122/// # Examples
123///
124/// ```
125/// use flm_core::stdlib::backends::pres;
126/// use flm_core::stdlib::backends::text::{FLOW_THROUGH, native_elements};
127///
128/// let native = native_elements();
129/// assert_eq!(native.len(), pres::ALL.len() + FLOW_THROUGH.len());
130/// assert!(native.iter().any(|element| element.as_str() == pres::PAR));
131/// ```
132pub fn native_elements() -> Vec<ElementName> {
133    pres::ALL.iter().chain(FLOW_THROUGH.iter()).map(|name| ElementName::from(*name)).collect()
134}
135
136/// The `text` feature, which registers the text backend (see the module
137/// documentation).
138///
139/// [`feature()`] returns it as a shared value that a package entry can list.
140/// It registers: the lowered-trees table `flm.lowered.text` that the lowering
141/// stage writes; the pieces stage ([`PiecesStage`] for `text`) and the
142/// lowered-pieces table `flm.lowered.text.pieces` it writes; the regions stage
143/// ([`TextRegionsStage`]) and its table `flm.output.text.regions`, together
144/// with the [`RegionsOutput`] that describes the `text` output's regions to a
145/// host (contributed to the service slot `flm.output.regions`); the output
146/// tables `flm.output.text` and `flm.output.text.document`; the settings of
147/// [`TextRenderOptions`]; the backend with its lowering, emit and final
148/// stages; the `text` output; and the `text` workflow.
149#[derive(Debug, Default)]
150pub struct TextBackend;
151
152impl FlmFeature for TextBackend {
153    fn info(&self) -> FeatureInfo {
154        FeatureInfo::new(FEATURE_NAME, "Text backend")
155            .docs("plain-text output over the layout engine: the `text` output and workflow")
156    }
157
158    fn settings(&self) -> Option<SettingsDecl> {
159        Some(settings())
160    }
161
162    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
163        b.table_named::<LoweredTrees>(
164            lowered_table_name(&BACKEND.into()),
165            "the text backend's lowered trees, one per document tree",
166        )?;
167        b.table_named::<LoweredPieces>(
168            lowered_pieces_table_name(&BACKEND.into()),
169            "the pieces that the render request places, lowered for the text backend",
170        )?;
171        b.stage(Arc::new(PiecesStage::new(BACKEND)))?;
172        b.table(TEXT_REGIONS, "the output's one region: the printed text")?;
173        b.stage(Arc::new(TextRegionsStage))?;
174        b.contribute_to::<RegionsOutput>(
175            REGIONS_SLOT,
176            Arc::new(RegionsOutput {
177                output: BACKEND.into(),
178                backend: BACKEND.into(),
179                document: TEXT_DOCUMENT.name().into(),
180                capability: TEXT_DOCUMENT.name().into(),
181                regions: TEXT_REGIONS.handle(),
182                artifacts: Vec::new(),
183            }),
184        )?;
185        b.table(
186            TEXT_OUTPUT,
187            "the printed text, its position marks, which record where each presentation node \
188             was printed, and its style marks, which record the printed ranges whose content \
189             carries a property plain text cannot show",
190        )?;
191        b.table(TEXT_DOCUMENT, "the printed text as a one-artifact set")?;
192        let (lowering, emit, final_stage) = stages();
193        b.backend(
194            BackendDef::new(BACKEND, native_elements(), lowering, emit, final_stage)
195                .docs("plain text over the layout engine"),
196        )?;
197        b.output(
198            OutputDef::new(
199                BACKEND,
200                TEXT_DOCUMENT.name(),
201                TEXT_DOCUMENT.name(),
202                MEDIA_TYPE,
203                EXTENSION,
204            )
205            .docs("the document as plain text"),
206        )?;
207        b.workflow(
208            WorkflowDef::new(WORKFLOW)
209                .output(BACKEND)
210                .demand(VALIDATED)
211                .docs("render the document as plain text, running every check"),
212        )?;
213        Ok(())
214    }
215}
216
217/// Returns the `text` feature ([`TextBackend`]) as a shared value, ready to be
218/// listed in a package entry.
219///
220/// A registry holding it must also hold three other features:
221///
222/// - the `lowering` feature
223///   ([`LoweringFeature`](crate::stdlib::backends::lowering::LoweringFeature)),
224///   which registers the presentation vocabulary this backend writes
225///   natively; without it, the registry fails to build, because the
226///   backend's native elements are not declared;
227/// - the `pieces` feature
228///   ([`pieces::feature`](crate::stdlib::backends::pieces::feature())), which
229///   declares the render options the pieces stage reads; without it, every
230///   plan of this backend fails;
231/// - the `check` feature ([`check_feature`](crate::stdlib::check_feature)),
232///   which declares the capability
233///   [`flm.validated`](crate::stdlib::VALIDATED) that the `text` workflow
234///   demands; without it, the registry fails
235///   to build.
236///
237/// The standard features ([`stdlib::add_features`](crate::stdlib::add_features))
238/// include all four.
239///
240/// # Examples
241///
242/// ```
243/// use flm_core::stdlib::backends::text;
244///
245/// assert_eq!(text::feature().info().name.as_str(), text::FEATURE_NAME);
246/// ```
247pub fn feature() -> Arc<dyn FlmFeature> {
248    Arc::new(TextBackend)
249}