Skip to main content

flm_core/stdlib/backends/text/
feature.rs

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