flm_core/stdlib/features/quote/mod.rs
1//! The `quote` feature: quotations, blocks set apart from the running text
2//! whose content is organized in quotation sections (a quoted passage, lines
3//! set as written, an attribution, ordinary paragraphs). The feature declares
4//! the quote environments `quote`, `blockquote` and `address` by default, and
5//! any other quote environment a host configures.
6//!
7//! # What an author writes
8//!
9//! A **quote environment** is an environment whose content is a quotation.
10//! The content is made of **quotation sections**, each written with a
11//! quotation-section command:
12//!
13//! - `\text{…}` — a quoted passage, one paragraph;
14//! - `\lines{…}` — lines set as written, such as a poem or an address: each
15//! `\\` ends a line, and each `\indent` at the start of a line indents that
16//! line by one tab, a unit of indentation whose width each backend decides
17//! ([`Length`](crate::stdlib::backends::pres::Length));
18//! - `\attributed{…}` — the attribution: an author or a source;
19//! - `\block{…}` — ordinary paragraphs and blocks, lists included.
20//!
21//! ```text
22//! \begin{quote} To be or not to be.
23//! \text{To be or not to be.}
24//! \attributed{Shakespeare} Shakespeare
25//! \end{quote}
26//!
27//! \begin{address} 123 Main St
28//! 123 Main St\\ City, ST 12345
29//! City, ST 12345
30//! \end{address}
31//! ```
32//!
33//! The right column is what the text backend prints. Content written in the
34//! body of a quote environment outside any quotation-section command is the
35//! environment's **bare content**. The configuration of each environment
36//! ([`QuoteEnvironment`]) states which quotation-section commands its body
37//! accepts, and which kind of quotation section its bare content is read as,
38//! if any; where it states none, bare content is an error. The default
39//! configuration ([`QuoteConfig`]) declares three environments:
40//!
41//! - `quote` accepts the four quotation-section commands and reads no bare
42//! content;
43//! - `blockquote` accepts no quotation-section command and reads its content
44//! as one block section;
45//! - `address` accepts no quotation-section command and reads its content as
46//! one lines section.
47//!
48//! A host declares other environments with any combination.
49//!
50//! A quotation-section command can be written only in text mode, and only
51//! inside the body of a quote environment that accepts it: the commands of an
52//! environment are declared in a scoped package
53//! ([`ScopedPackageDef`](crate::lang::mint::ScopedPackageDef)) of that
54//! environment, a set of element declarations that can be written only inside
55//! the environment bodies and arguments whose declarations refer to the
56//! package ([scoped packages](crate::guide::concepts_overview#scoped-packages)).
57//! Inside a formula, `\text{…}` is therefore mathematics' own text command,
58//! never a quotation section. The guide for authors describes quotations
59//! under [Quotations](crate::guide::language_syntax#quotations).
60//!
61//! # What the feature provides to the pipeline
62//!
63//! **Elements.** Every quote environment is one element value of the element
64//! type [`QUOTE`] (`flm.quote`), carrying a [`QuoteElement`]. It is a block,
65//! takes no argument, and is declared in text mode. Its body is laid out as
66//! paragraphs and blocks, or as inline content where its bare content is read
67//! as a passage, lines or an attribution
68//! ([`QuoteEnvironment::holds_blocks`]). The four quotation-section commands
69//! are four element values of the element type [`SECTION`]
70//! (`flm.quote.section`), each carrying a [`SectionElement`]; each is a macro
71//! with one mandatory argument, [`CONTENT_ARG`]. A quotation-section command
72//! is in **section position** when it is written directly in the body of a
73//! quote environment that accepts it. There it opens a quotation section, and
74//! where the body is laid out as paragraphs and blocks, it is a block of its
75//! own between the others. Anywhere else it is inline content.
76//!
77//! **Scoped packages.** The feature declares one scoped package per quote
78//! environment that accepts at least one quotation-section command, whose
79//! name [`sections_package`] returns (`flm.quote.sections.quote` for
80//! `quote`), holding exactly the commands that environment accepts. It also declares
81//! the scoped package [`LINES_PACKAGE`] (`flm.quote.lines`), which holds
82//! `\\` and `\indent`, the two commands of a lines section. Both are field
83//! macros, macros that carry data rather than content
84//! ([fields](crate::guide::concepts_overview#fields-data-a-construct-reads)):
85//! they write nothing of their own, and the lowering rules read them in place
86//! among the line's content. The argument of `\lines` and the body of an
87//! environment whose bare content is lines refer to the package.
88//!
89//! **Reading a quotation's body.** The rules below read the body's direct
90//! children in order. A quotation-section command in section position opens
91//! a quotation section. Each maximal run of other content between two
92//! quotation sections, without the whitespace and source comments at its
93//! edges, is one **bare run**: it is lowered exactly as a quotation section
94//! of the environment's bare-content kind would be lowered over the same
95//! content. The rules read the body each time they lower a quotation, and
96//! store nothing.
97//!
98//! **Lowering rules.** A lowering rule ([`LoweringRule`]) says how an element
99//! becomes output on a backend. The feature registers these rules. A rule
100//! marked as the default for one backend ranks above a rule marked as the
101//! default everywhere ([`DefaultMark`]):
102//!
103//! - [`QUOTE_RULE`] ([`QuoteRule`]), the default on every backend that has no
104//! rule of its own for a quotation: it stages
105//! (builds into the lowered tree; [`Lowerer`](crate::core::lowering::Lowerer))
106//! one `flm.pres.block` of role [`QUOTE_ROLE`] (`flm.quote`), whose one kind
107//! token is the environment's name, holding one `flm.pres.block` per
108//! quotation section in the order written, of the role of the section's
109//! kind ([`TEXT_ROLE`], [`LINES_ROLE`], [`ATTRIBUTED_ROLE`] or
110//! [`BLOCK_ROLE`]). A role is a feature-owned dotted name on a presentation
111//! payload that says what a container is, and kind tokens classify it
112//! further ([`payload`](crate::stdlib::backends::pres::payload)). A passage
113//! and an attribution hold one paragraph, a block section holds its
114//! paragraphs and blocks, and a lines section holds one `flm.pres.lines`
115//! with one `flm.pres.line` per line, the line's left indentation a
116//! [`Length`](crate::stdlib::backends::pres::Length) of as many tabs as
117//! the line has leading `\indent`s. Every quote environment has the same
118//! role, so that a stylesheet or a lowering rule treats them alike; the
119//! kind token selects one environment. The text backend uses this rule: it
120//! prints a quotation as its quotation sections, one blank line apart, with
121//! no prefix and no indentation of the whole.
122//! - [`SECTION_RULE`] ([`SectionRule`]), the default on every backend that
123//! has no rule of its own for a quotation-section command: a
124//! quotation-section command outside section position is lowered as its
125//! argument's content.
126//! - On the `html` backend, the feature's stylesheet `flm.quote.style`
127//! ([`html`]), which [`QuoteRule`] requires at every quotation. The HTML
128//! backend writes the quotation as a `<blockquote>` and each quotation
129//! section as a `<div>`.
130//! - On the `latex-rendered` backend, the definition piece
131//! `flm.latex.def.flmx.quote` ([`latex_rendered`]), which the same
132//! requirement brings into the style file.
133//! - [`latex::LATEX_RULE`] ([`latex::QuoteLatexRule`]), the default on the
134//! `latex-recomposed` backend: it writes the environment as the author
135//! wrote it, each quotation section through a LaTeX hook (`\flmQuoteText`,
136//! `\flmQuoteLines`, `\flmQuoteAttributed`, `\flmQuoteBlock`) and a line's
137//! indentation through `\flmIndent`; the feature's definition piece
138//! `flm.latex.def.quote` defines them in the style file ([`latex`]).
139//!
140//! **Settings.** The feature's configuration, [`QuoteConfig`], is the value
141//! the feature is constructed from; it is fixed when the registry is built
142//! ([configuration](crate::guide::concepts_overview#settings-options-and-configuration)),
143//! because the environments and their commands are part of the language. The
144//! same value written as data is the feature's settings: the settings key
145//! `environments` maps each environment's name to its [`QuoteEnvironment`],
146//! and a host that combines several sources of settings combines that map
147//! one environment at a time
148//! ([`SettingsDecl::merge_entries`](crate::core::settings::SettingsDecl::merge_entries)).
149//! The feature feeds the configuration into the [registry
150//! digest](crate::model::digest), the number that changes whenever something
151//! about the registry that can change what processing produces changes
152//! ([`FeatureBuilder::digest_input`]); [`QuoteConfig::digest_bytes`] gives the
153//! bytes. It declares no option type.
154//!
155//! # Errors
156//!
157//! The feature reports three conditions
158//! ([diagnostics](crate::guide::concepts_overview#diagnostics)), each an Error, while a quotation is
159//! lowered, on every backend; [`diagnostics`] gives each one's recovery, the
160//! way the lowering goes on after it
161//! ([recovery](crate::stdlib::backends::lowering::error)):
162//!
163//! - [`BareContent`] (`flm.quote.bare-content`) — bare content in an
164//! environment that reads none, such as text written directly in `quote`;
165//! reported once per bare run;
166//! - [`NestedSection`] (`flm.quote.nested-section`) — a quotation-section
167//! command written anywhere other than directly in the body of a quote
168//! environment, such as inside another quotation section's argument
169//! (`\lines{\text{x}}`);
170//! - [`IndentMidLine`] (`flm.quote.indent-mid-line`) — an `\indent` after the
171//! first content of its line.
172//!
173//! A quotation-section command that an environment does not accept is not
174//! declared in that environment's body, so writing one there is an unknown
175//! command, part of the bare content. One case differs. Inside a quotation
176//! nested in a quotation section of another quotation, the enclosing
177//! quotation's commands can still be written, because the scoped packages of
178//! the enclosing bodies remain available. Such a command, written directly in
179//! the nested body that does not accept it, is part of the nested body's bare
180//! content: where the nested environment reads no bare content, it is
181//! reported with its bare run, and it is shown as its argument's content.
182//!
183//! # Interactions with other features
184//!
185//! - **Block structure.** The block role of a quotation-section command is
186//! decided per occurrence ([`SectionElement`]), and the block-structure
187//! pass ([`blocks`](crate::lang::rewrites::blocks)) lays the body out from
188//! it.
189//! - **Lists.** The environment's name becomes a kind token of the
190//! quotation's block, so it may not be one of the kind tokens a
191//! presentation list reserves
192//! ([`LIST_RESERVED_KINDS`](crate::stdlib::backends::pres::LIST_RESERVED_KINDS));
193//! [`QuoteConfig::validate`] refuses such a name.
194//! - **Other features' environments.** An environment name that another
195//! feature also declares, such as `itemize`, makes the registry build fail,
196//! as any two declarations of one name do.
197//! - **Margin notes on the page.** The feature's stylesheet sets
198//! `--flm-margin-note-inset` on a quotation, so that a note shown in the
199//! margin and written inside the quotation still reaches the page's column
200//! of notes ([`html`]).
201//! - **The LaTeX family.** The rule of the `latex-recomposed` backend
202//! ([`latex::QuoteLatexRule`]) uses the LaTeX hooks and definition pieces
203//! of the [LaTeX family](crate::stdlib::backends::latex), the code shared
204//! by the LaTeX backends, and writes a line's indentation with the family's
205//! length `\flmTabWidth` ([`latex`]).
206//! - **The standard features.** The [standard features](crate::stdlib)
207//! include the feature under the configuration
208//! [`StdlibConfig::quote`](crate::stdlib::StdlibConfig::quote).
209//!
210//! # Items
211//!
212//! - [`Quote`] and [`feature`] — the feature, under a configuration or the
213//! default one.
214//! - [`QuoteConfig`], [`QuoteEnvironment`], [`QuoteSection`] — the
215//! configuration: the environments, what each accepts, the four kinds of
216//! quotation section.
217//! - [`QuoteElement`], [`SectionElement`] — the per-value data of the two
218//! element types [`QUOTE`] and [`SECTION`].
219//! - [`QuoteRule`], [`SectionRule`] — the general lowering rules; [`html`]
220//! and [`latex`] — the rules of the `html` and `latex-recomposed` backends.
221//! - [`diagnostics`] — the three conditions.
222//! - The names: [`FEATURE`], [`QUOTE`], [`SECTION`], [`CONTENT_ARG`],
223//! [`LINES_PACKAGE`], [`SECTIONS_PACKAGE_PREFIX`] and [`sections_package`],
224//! [`LINEBREAK_COMMAND`], [`INDENT_COMMAND`], [`QUOTE_RULE`],
225//! [`SECTION_RULE`], and the roles [`QUOTE_ROLE`], [`TEXT_ROLE`],
226//! [`LINES_ROLE`], [`ATTRIBUTED_ROLE`], [`BLOCK_ROLE`].
227
228mod config;
229pub mod diagnostics;
230mod elements;
231pub mod html;
232pub mod latex;
233pub mod latex_rendered;
234mod lower;
235
236use std::sync::Arc;
237
238use crate::core::settings::SettingsDecl;
239use crate::core::lowering::{DefaultMark, LoweringDecl, LoweringRule};
240use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
241
242pub use config::{QuoteConfig, QuoteEnvironment, QuoteSection};
243pub use diagnostics::{BareContent, IndentMidLine, NestedSection};
244pub use elements::{QuoteElement, SectionElement};
245pub use lower::{QuoteRule, SectionRule};
246
247/// The feature's registered name, `quote`.
248pub const FEATURE: &str = "quote";
249
250/// The declaration of the feature's settings ([`crate::core::settings`]): the
251/// fields of [`QuoteConfig`] are its settings keys, and the key
252/// `environments` is combined one environment at a time.
253fn settings() -> SettingsDecl {
254 SettingsDecl::new(FEATURE)
255 .config::<QuoteConfig>(
256 "The quote environments, by name: for each, the quotation-section commands its body \
257 accepts (`text`, `lines`, `attributed`, `block`) and the kind of quotation section \
258 that content written outside those commands is read as (the key `bare`; when it is \
259 absent, such content is an error). Fixed when the registry is built: it cannot vary \
260 per document or per render.",
261 )
262 .merge_entries("environments", || serde_json::to_value(&QuoteConfig::default().environments).map_err(|error| error.to_string()))
263 .remove_false("environments")
264}
265
266/// The element type shared by every quote environment, `flm.quote`. Each
267/// configured environment is one element value of this type, carrying a
268/// [`QuoteElement`].
269pub const QUOTE: &str = "flm.quote";
270
271/// The element type shared by the four quotation-section commands,
272/// `flm.quote.section`. Each command is one element value of this type,
273/// carrying a [`SectionElement`].
274pub const SECTION: &str = "flm.quote.section";
275
276/// The name of the one argument of a quotation-section command, `content`:
277/// the content of the quotation section.
278pub const CONTENT_ARG: &str = "content";
279
280/// The name of the scoped package holding the two commands of a lines
281/// section, `\\` and `\indent`: `flm.quote.lines`. Both are field macros:
282/// they write nothing, and the lowering rules read them in place
283/// ([fields](crate::guide::concepts_overview#fields-data-a-construct-reads)). The declaration of the
284/// argument of `\lines` refers to it, and so does the declaration of the body
285/// of an environment whose bare content is read as lines.
286pub const LINES_PACKAGE: &str = "flm.quote.lines";
287
288/// The prefix of the name of the scoped package holding the
289/// quotation-section commands of one quote environment, `flm.quote.sections.`:
290/// the package of `quote` is `flm.quote.sections.quote` ([`sections_package`]).
291pub const SECTIONS_PACKAGE_PREFIX: &str = "flm.quote.sections.";
292
293/// The name of the field macro that ends a line of a lines section: a single
294/// backslash, the name written after the escape character, so that an author
295/// writes `\\`.
296pub const LINEBREAK_COMMAND: &str = "\\";
297
298/// The name of the field macro that indents a line of a lines section by one
299/// tab, `indent`.
300pub const INDENT_COMMAND: &str = "indent";
301
302/// The name of the general lowering rule of a quotation,
303/// `flm.quote.lower.default` ([`QuoteRule`]), the default on every backend.
304pub const QUOTE_RULE: &str = "flm.quote.lower.default";
305
306/// The name of the lowering rule of a quotation-section command outside
307/// section position, `flm.quote.section.lower.default` ([`SectionRule`]), the
308/// default on every backend.
309pub const SECTION_RULE: &str = "flm.quote.section.lower.default";
310
311/// Returns the name of the scoped package holding the quotation-section
312/// commands that the quote environment `environment` accepts:
313/// [`SECTIONS_PACKAGE_PREFIX`] followed by the environment's name.
314///
315/// Because of the prefix, no environment name, `lines` included, can produce
316/// the name of [`LINES_PACKAGE`].
317pub fn sections_package(environment: &str) -> String {
318 format!("{SECTIONS_PACKAGE_PREFIX}{environment}")
319}
320
321/// The role of the block a quotation is staged as, `flm.quote`, for every
322/// quote environment; the environment's name is the block's kind token.
323pub const QUOTE_ROLE: &str = "flm.quote";
324
325/// The role of the block a text section (a quoted passage) is staged as,
326/// `flm.quote.text`.
327pub const TEXT_ROLE: &str = "flm.quote.text";
328
329/// The role of the block a lines section is staged as, `flm.quote.lines`.
330pub const LINES_ROLE: &str = "flm.quote.lines";
331
332/// The role of the block an attribution is staged as,
333/// `flm.quote.attributed`.
334pub const ATTRIBUTED_ROLE: &str = "flm.quote.attributed";
335
336/// The role of the block a block section is staged as, `flm.quote.block`.
337pub const BLOCK_ROLE: &str = "flm.quote.block";
338
339/// The `quote` feature ([`FlmFeature`]), constructed from a [`QuoteConfig`]:
340/// it registers the quote environments, their quotation-section commands and
341/// the lowering rules of a quotation. See the [module documentation](self).
342#[derive(Debug, Clone, Default)]
343pub struct Quote {
344 config: QuoteConfig,
345}
346
347impl Quote {
348 /// Returns the feature constructed from `config`, which stays fixed for
349 /// the life of the registry the feature is registered into.
350 ///
351 /// The configuration is checked when the feature registers: an invalid
352 /// one ([`QuoteConfig::validate`]) makes the registry build fail with a
353 /// [`BuildError::Feature`].
354 pub fn new(config: QuoteConfig) -> Quote {
355 Quote { config }
356 }
357
358 /// Returns the configuration this feature was constructed from.
359 pub fn config(&self) -> &QuoteConfig {
360 &self.config
361 }
362}
363
364impl FlmFeature for Quote {
365 fn info(&self) -> FeatureInfo {
366 FeatureInfo::new(FEATURE, "Quotations").docs(
367 "Quotations: the quote environments (`quote`, `blockquote`, `address` and any a host \
368 configures), their quotation-section commands `\\text`, `\\lines`, `\\attributed` \
369 and `\\block`, and the commands `\\\\` and `\\indent` of a lines section.",
370 )
371 }
372
373 fn settings(&self) -> Option<SettingsDecl> {
374 Some(settings())
375 }
376
377 fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
378 let owner = b.feature().clone();
379 self.config
380 .validate()
381 .map_err(|detail| BuildError::Feature { feature: owner.clone(), detail })?;
382 for (name, environment) in &self.config.environments {
383 b.element(elements::environment_def(&owner, name, environment))?;
384 }
385 let sections = elements::sections_packages(&owner, &self.config.environments);
386 let any_section = !sections.is_empty();
387 for package in sections {
388 b.scoped_package(package)?;
389 }
390 if !self.config.environments.is_empty() {
391 b.element_type_text(
392 QUOTE,
393 "A quotation set apart from the running text, made of quotation sections: a \
394 quoted passage, lines, an attribution or paragraphs and blocks.",
395 )?;
396 }
397 if any_section {
398 b.element_type_text(
399 SECTION,
400 "A section of a quotation: a quoted passage, lines, an attribution or paragraphs \
401 and blocks, as its command says.",
402 )?;
403 }
404 b.scoped_package(elements::lines_package(&owner))?;
405 if !self.config.environments.is_empty() {
406 b.lowering_rule(
407 LoweringRule::new(
408 QUOTE_RULE,
409 QUOTE,
410 lower::quote_decl(),
411 Arc::new(QuoteRule),
412 DefaultMark::Everywhere,
413 )
414 .docs(
415 "a quotation lowers to a `flm.pres.block` of role `flm.quote` whose kind token \
416 is the environment's name, holding one `flm.pres.block` per quotation section, \
417 of the role of the section's kind",
418 ),
419 )?;
420 html::register(b)?;
421 latex_rendered::register(b)?;
422 latex::register(b)?;
423 }
424 if any_section {
425 b.lowering_rule(
426 LoweringRule::new(
427 SECTION_RULE,
428 SECTION,
429 LoweringDecl::new(),
430 Arc::new(SectionRule),
431 DefaultMark::Everywhere,
432 )
433 .docs("a quotation-section command outside section position lowers to its argument's content, and is reported unless it is part of a quotation body's bare content"),
434 )?;
435 }
436 b.digest_input(&self.config.digest_bytes())?;
437 Ok(())
438 }
439}
440
441/// Returns the [`Quote`] feature under the default configuration (the
442/// environments `quote`, `blockquote` and `address`), ready to be listed in a
443/// package entry.
444///
445/// To list the feature under a [`QuoteConfig`] of your own, use
446/// `Arc::new(Quote::new(config))`, or pass the configuration to the standard
447/// package with [`StdlibConfig::quote`](crate::stdlib::StdlibConfig::quote).
448pub fn feature() -> Arc<dyn FlmFeature> {
449 Arc::new(Quote::default())
450}