flm_core/stdlib/features/verbatim/mod.rs
1//! The `verbatim` feature: content shown exactly as the author wrote it, through
2//! three macros and two environments.
3//!
4//! The guide to the language describes verbatim content for authors
5//! ([verbatim content](crate::guide::language_syntax#verbatim-content)).
6//!
7//! # What an author writes
8//!
9//! Verbatim content is a [verbatim
10//! region](crate::guide::concepts_overview#verbatim-regions): a run of raw text in
11//! which no markup character means anything. A backslash, a brace and a percent
12//! sign are ordinary characters, and the region ends only at its own
13//! terminator. The feature declares five commands:
14//!
15//! | written | element | verbatim kind | display |
16//! |---|---|---|---|
17//! | `\verbtext{…}` | `flm.verbatim.macro` | `text` | inline |
18//! | `\verbcode[lang]{…}` | `flm.verbatim.macro` | `code` | inline |
19//! | `\verba[lang]{…}` | `flm.verbatim.macro` | `a` | inline |
20//! | `\begin{verbatimtext}…\end{verbatimtext}` | `flm.verbatim.environment` | `text` | inline |
21//! | `\begin{verbatimcode}[lang]…\end{verbatimcode}` | `flm.verbatim.environment` | `code` | block |
22//!
23//! A **verbatim kind** ([`VerbatimKind`]) says what sort of content a verbatim
24//! region holds: characters with no formatting of their own (`text`), computer
25//! code (`code`), or an identifier such as a keyword or a name (`a`, after the
26//! macro `\verba`). `{verbatimcode}` is the only one of the five commands that
27//! is a block of its own; the others are inline content of the paragraph they
28//! are written in.
29//!
30//! A macro's content is delimited by the first character after the command (and
31//! after its optional language argument): the region closes at the partner of
32//! that character for `{`, `[`, `<` and `(`, counting nested pairs, so that it
33//! ends at the partner that balances the opening one; for any other character it
34//! closes at the same character again, and the content may then hold unbalanced
35//! braces. `\verbcode+a{b+` and `\verbcode{a{b}c}` both read the characters
36//! between the delimiters. The optional argument `[lang]` gives the
37//! programming language the content is written in; no standard feature
38//! interprets it, and a backend that highlights syntax may use it.
39//!
40//! # What the feature registers
41//!
42//! The `verbatim` feature ([`Verbatim`], a
43//! [`FlmFeature`]) registers:
44//!
45//! - the element types [`MACRO`] (`flm.verbatim.macro`) for the three macros and
46//! [`ENVIRONMENT`] (`flm.verbatim.environment`) for the two environments, with
47//! one element value per command, each carrying a [`VerbatimCallable`] (the
48//! command's name, its verbatim kind, whether it takes a language argument,
49//! whether it is a block). The commands are declared as a family, one element
50//! type with one element value per command ([elements and
51//! aspects](crate::guide::concepts_overview#elements-and-aspects)); the two
52//! forms get two element types because a macro holds its content in an
53//! argument and an environment in its body, so each rule reads one shape;
54//! - the default lowering rules [`MACRO_RULE`] and [`ENVIRONMENT_RULE`], and the
55//! recomposition rules of [`latex`] for the `latex-recomposed` backend.
56//!
57//! The commands are declared with the language layer's declarations for raw text
58//! ([`ArgStdKind::Verbatim`] for a macro's content, [`BodyDef::verbatim`] for an
59//! environment's body), so the parse wraps every verbatim run in a group node of
60//! the verbatim class, as [`crate::lang::verbatim`] describes; the feature writes
61//! no parser of its own.
62//!
63//! # What a verbatim command becomes on each backend
64//!
65//! - **Default rules** ([`MACRO_RULE`], [`ENVIRONMENT_RULE`], used by the `text`
66//! and `html` backends): each stages (builds into the lowered tree; see
67//! [`Lowerer`]) a
68//! [`flm.pres.verbatim`](crate::stdlib::backends::pres::VERBATIM) node whose
69//! payload carries the verbatim kind, the display (inline or block) and the
70//! language, over the region's characters copied unchanged. Nothing inside a
71//! verbatim region is lowered through the rules.
72//! - **`text` backend**: it prints the characters byte for byte: inline content
73//! as one unit that is never broken across lines (or as a block when it
74//! holds a newline or a tab), a block on lines of its own; it prints neither
75//! the verbatim kind nor the language.
76//! - **`html` backend**: it writes the node as the [HTML
77//! contract](crate::guide::rendering#the-html-contract) states for
78//! `flm.pres.verbatim` ([`CONVENTIONS`](crate::stdlib::backends::html::CONVENTIONS)):
79//! a `<code>` element inline and a `<pre><code>` pair for a block, with the
80//! verbatim kind, the display and the language as attributes.
81//! - **`latex-recomposed` backend**: the rules of [`latex`] write inline content
82//! through the `fvextra` package's `\EscVerb` command and a block through the
83//! environment `flmVerbatimCode`. Each verbatim kind is set through its
84//! **formatting hook**: a [LaTeX hook](crate::stdlib::backends::latex::preamble)
85//! (a macro that the style file defines with a plain default and a user
86//! redefines) named `\flmFmtVRBverbtext`, `\flmFmtVRBverbcode` or
87//! `\flmFmtVRBverba` after the macro of that kind. Inline verbatim content
88//! keeps the font family of the surrounding text, and the hook alone sets
89//! the font of its kind: by default, `\verbtext` content looks like the
90//! surrounding text, `\verba` content is in italics and `\verbcode` content
91//! is in the typewriter family.
92//!
93//! # Content that is not characters
94//!
95//! What an author writes between a verbatim command's delimiters is characters.
96//! A user definition's template may place one of its arguments inside verbatim
97//! content, though, and its expansion then puts that argument's content there as
98//! it is: with a user definition `\code` whose template is `\verbcode{#1}`,
99//! the verbatim content of `\code{…}` is the content of its argument, which
100//! may hold any node a document can write. Every rule of this feature
101//! therefore reads the content as characters through
102//! [`read_verbatim_content`]: a text node gives its characters, a comment gives
103//! nothing, and a brace group gives its content without the braces, so
104//! `\code{a{b}c}` shows `abc`. A command, an environment, a special character
105//! sequence or mathematics has no characters to give: the Error
106//! [`ContentNotCharacters`] is reported at the verbatim command or environment,
107//! and the region shows its whole content written as its source, so
108//! `\code{\emph{x}}` shows `\emph{x}`. Every backend does the same, the
109//! recomposed LaTeX included.
110//!
111//! [`read_verbatim_content`]: crate::stdlib::backends::lowering::read_verbatim_content
112//! [`ContentNotCharacters`]: crate::stdlib::backends::lowering::ContentNotCharacters
113//!
114//! # Map of the module
115//!
116//! - [`Verbatim`] — the feature; [`feature`] returns it for a package entry.
117//! - [`MACRO`], [`ENVIRONMENT`], [`VerbatimCallable`] — the element types and the
118//! data of each element value; [`MACROS`] and [`ENVIRONMENTS`] list the five
119//! commands.
120//! - [`MACRO_RULE`], [`MacroRule`], [`ENVIRONMENT_RULE`], [`EnvironmentRule`] —
121//! the default lowering rules and their bodies.
122//! - [`CONTENT_ARG`], [`LANG_ARG`] — the names of the arguments.
123//! - [`latex`] — the recomposition rules for the `latex-recomposed` backend.
124
125// Each form is one element type for all its commands because rules and aspects
126// are chosen per element: one rule serves every command of a form, and the
127// command's value says what differs.
128// The language argument is an ordinary optional argument rather than the
129// characters-only group Python's parser requires immediately after the
130// command: the declarative argument vocabulary has no optional
131// characters-only shape, and adding one to the language layer for one
132// argument is not warranted.
133
134pub mod latex;
135
136use std::sync::Arc;
137
138use techy::core::node::NodeRef;
139
140use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
141use crate::model::element::{ElementSpec, element_value};
142use crate::core::lowering::{
143 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
144};
145use crate::model::names::{ElementName, FeatureName, Name};
146use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
147use crate::lang::mint::{ArgDef, ArgStdKind, BodyDef, ElementDef, SyntaxDef};
148use crate::lang::text::is_space;
149use crate::lang::{Flm, FlmGroupType};
150use crate::stdlib::backends::lowering::{copy_subtree_verbatim, stage_verbatim_content};
151use crate::stdlib::backends::pres::{
152 self, VerbatimDisplay, VerbatimKind, VerbatimPayload, plain_text,
153};
154
155/// The feature's registered name, `verbatim`.
156pub const FEATURE: &str = "verbatim";
157
158/// The name of the element type of the three verbatim macros,
159/// `flm.verbatim.macro`. The data of each element value is a
160/// [`VerbatimCallable`].
161pub const MACRO: &str = "flm.verbatim.macro";
162
163/// The name of the element type of the two verbatim environments,
164/// `flm.verbatim.environment`. The data of each element value is a
165/// [`VerbatimCallable`].
166pub const ENVIRONMENT: &str = "flm.verbatim.environment";
167
168/// The name of the default lowering rule of [`MACRO`] on every backend,
169/// `flm.verbatim.macro.lower.default`, whose body is [`MacroRule`].
170pub const MACRO_RULE: &str = "flm.verbatim.macro.lower.default";
171
172/// The name of the default lowering rule of [`ENVIRONMENT`] on every backend,
173/// `flm.verbatim.environment.lower.default`, whose body is
174/// [`EnvironmentRule`].
175pub const ENVIRONMENT_RULE: &str = "flm.verbatim.environment.lower.default";
176
177/// The name of the argument that holds a verbatim macro's content,
178/// `content`.
179pub const CONTENT_ARG: &str = "content";
180
181/// The name of the optional argument that gives the programming language of
182/// the content, `lang`.
183pub const LANG_ARG: &str = "lang";
184
185/// The verbatim macros the feature declares, as `(name, verbatim kind, takes
186/// a language argument)`.
187pub const MACROS: [(&str, VerbatimKind, bool); 3] = [
188 ("verbtext", VerbatimKind::Text, false),
189 ("verbcode", VerbatimKind::Code, true),
190 ("verba", VerbatimKind::Identifier, true),
191];
192
193/// The verbatim environments the feature declares, as `(name, verbatim kind,
194/// takes a language argument, is a block of its own)`.
195pub const ENVIRONMENTS: [(&str, VerbatimKind, bool, bool); 2] = [
196 ("verbatimtext", VerbatimKind::Text, false, false),
197 ("verbatimcode", VerbatimKind::Code, true, true),
198];
199
200/// The data of one element value of `flm.verbatim.macro` or
201/// `flm.verbatim.environment`: which verbatim command was written and what it
202/// means.
203///
204/// A lowering rule or a stage reads it from a node with [`element_value`].
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct VerbatimCallable {
207 /// The callable's name as written (`verbcode`, `verbatimcode`).
208 pub name: Name,
209 /// The verbatim kind of the content it introduces.
210 pub kind: VerbatimKind,
211 /// Whether it takes the optional `[lang]` argument.
212 pub lang_arg: bool,
213 /// Whether its content is a block of its own (`true` for
214 /// `{verbatimcode}` only).
215 pub block: bool,
216}
217
218/// The element value of one verbatim macro: inline content of the verbatim
219/// kind `kind`.
220fn macro_element(name: &str, kind: VerbatimKind, lang_arg: bool) -> Arc<ElementSpec> {
221 Arc::new(
222 ElementSpec::new(MACRO)
223 .docs(format!("`\\{name}`: inline verbatim content of kind `{kind}`."))
224 .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
225 .with_value(Arc::new(VerbatimCallable {
226 name: Name::from(name),
227 kind,
228 lang_arg,
229 block: false,
230 })),
231 )
232}
233
234/// The element value of one verbatim environment: content of the verbatim
235/// kind `kind`, a block of its own when `block`.
236fn environment_element(
237 name: &str,
238 kind: VerbatimKind,
239 lang_arg: bool,
240 block: bool,
241) -> Arc<ElementSpec> {
242 let role = if block { BlockRole::Block } else { BlockRole::DEFAULT };
243 Arc::new(
244 ElementSpec::new(ENVIRONMENT)
245 .docs(format!(
246 "`\\begin{{{name}}}…\\end{{{name}}}`: verbatim content of kind `{kind}`."
247 ))
248 .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(role)))
249 .with_value(Arc::new(VerbatimCallable {
250 name: Name::from(name),
251 kind,
252 lang_arg,
253 block,
254 })),
255 )
256}
257
258/// The arguments of a verbatim macro: the optional language argument when the
259/// callable takes one, then the delimited verbatim content.
260fn macro_args(lang_arg: bool) -> Vec<ArgDef> {
261 let mut args = Vec::new();
262 if lang_arg {
263 args.push(language_argument());
264 }
265 args.push(
266 ArgDef::named(CONTENT_ARG, ArgStdKind::Verbatim { delimiters: None }).docs(
267 "The content, shown exactly as written. The first character after the command \
268 opens the region, and its partner closes it (`}` for `{`, `]` for `[`, `>` for \
269 `<`, `)` for `(`, nested pairs counted; the same character for any other).",
270 ),
271 );
272 args
273}
274
275/// The declaration of the optional `[lang]` argument, shared by the commands
276/// that take one.
277fn language_argument() -> ArgDef {
278 ArgDef::optional(LANG_ARG).docs(
279 "The programming language the content is written in. A backend that highlights \
280 syntax may use it; the text backend does not print it.",
281 )
282}
283
284/// The language written on a verbatim node, trimmed of the whitespace around
285/// it: `None` when the node's element declares no language argument, when the
286/// argument is absent, or when its text is blank.
287pub(super) fn language_of(node: &NodeRef<'_, Flm>) -> Option<String> {
288 let content = node.argument_content_nodes_named(LANG_ARG).ok()??;
289 let text = plain_text(content.iter()).trim_matches(is_space).to_string();
290 (!text.is_empty()).then_some(text)
291}
292
293/// The verbatim kind and the display of a verbatim node, read from its
294/// element value; a [`LowerError`] for a node that carries no
295/// [`VerbatimCallable`].
296fn kind_and_display(
297 node: &NodeRef<'_, Flm>,
298) -> Result<(VerbatimKind, VerbatimDisplay), LowerError> {
299 let value = element_value::<VerbatimCallable>(node)
300 .ok_or_else(|| LowerError::structure("a verbatim node without its value"))?;
301 let display =
302 if value.block { VerbatimDisplay::Block } else { VerbatimDisplay::Inline };
303 Ok((value.kind, display))
304}
305
306/// The body of [`MACRO_RULE`]: it stages an inline
307/// [`flm.pres.verbatim`](crate::stdlib::backends::pres::VERBATIM) node,
308/// carrying the verbatim kind and the language, over the characters of the
309/// macro's content argument copied unchanged (for content that is not
310/// characters, see the module documentation, *Content that is not
311/// characters*).
312///
313/// When the content argument is missing (a parse recovery left it absent, for
314/// instance for a region that the end of the input cut short, and the parse
315/// reported it), the node is empty and nothing more is reported.
316///
317/// The rule returns a [`LowerError`] when the node carries no
318/// [`VerbatimCallable`] or when the content could not be staged.
319#[derive(Debug, Default)]
320pub struct MacroRule;
321
322impl Lower for MacroRule {
323 fn lower(
324 &self,
325 node: NodeRef<'_, Flm>,
326 cx: &mut LowerCx<'_>,
327 lw: &mut dyn Lowerer,
328 ) -> Result<Lowering, LowerError> {
329 let (kind, display) = kind_and_display(&node)?;
330 let lang = language_of(&node);
331 let body = match node.argument_content_nodes_named(CONTENT_ARG) {
332 Ok(Some(content)) => stage_verbatim_content(&node, content, cx, lw)?,
333 _ => Vec::new(),
334 };
335 let payload = VerbatimPayload { kind, display, lang };
336 let verbatim = lw.pres_with(cx, &ElementName::from(pres::VERBATIM), payload, body)?;
337 Ok(Lowering::Emit(vec![verbatim]))
338 }
339}
340
341/// The body of [`ENVIRONMENT_RULE`]: it stages a
342/// [`flm.pres.verbatim`](crate::stdlib::backends::pres::VERBATIM) node,
343/// carrying the verbatim kind, the display and the language, over the
344/// characters of the environment's body copied unchanged: a block for
345/// `{verbatimcode}`, inline for `{verbatimtext}` (for content that is not
346/// characters, see the module documentation, *Content that is not
347/// characters*).
348///
349/// The body of a verbatim environment holds the group node of the verbatim
350/// class that the parse puts around every verbatim run. The rule copies that
351/// group's children, not the group itself: the node the rule stages already
352/// represents the region, and lowering the group would stage a second
353/// `flm.pres.verbatim` node inside it.
354///
355/// The rule returns a [`LowerError`] when the node carries no
356/// [`VerbatimCallable`] or when the content could not be staged.
357#[derive(Debug, Default)]
358pub struct EnvironmentRule;
359
360impl Lower for EnvironmentRule {
361 fn lower(
362 &self,
363 node: NodeRef<'_, Flm>,
364 cx: &mut LowerCx<'_>,
365 lw: &mut dyn Lowerer,
366 ) -> Result<Lowering, LowerError> {
367 let (kind, display) = kind_and_display(&node)?;
368 let lang = language_of(&node);
369 let mut body = Vec::new();
370 if let Some(content) = node.body() {
371 for child in content.iter() {
372 if child.group_type() == Some(FlmGroupType::Verbatim) {
373 body.extend(stage_verbatim_content(&node, child.children(), cx, lw)?);
374 } else {
375 body.push(copy_subtree_verbatim(cx, child)?);
376 }
377 }
378 }
379 let payload = VerbatimPayload { kind, display, lang };
380 let verbatim = lw.pres_with(cx, &ElementName::from(pres::VERBATIM), payload, body)?;
381 Ok(Lowering::Emit(vec![verbatim]))
382 }
383}
384
385/// The `verbatim` feature: it registers the three verbatim macros, the two
386/// verbatim environments, their two default lowering rules and the
387/// recomposition rules of [`latex`]. See the module documentation.
388#[derive(Debug, Default, Clone, Copy)]
389pub struct Verbatim;
390
391impl FlmFeature for Verbatim {
392 fn info(&self) -> FeatureInfo {
393 FeatureInfo::new(FEATURE, "Verbatim content").docs(
394 "Content shown exactly as written: the macros `\\verbtext`, `\\verbcode` and \
395 `\\verba` and the environments `verbatimtext` and `verbatimcode`, each lowered to \
396 a `flm.pres.verbatim` node that carries its verbatim kind and its language.",
397 )
398 }
399
400 fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
401 let owner: FeatureName = b.feature().clone();
402 for (name, kind, lang_arg) in MACROS {
403 b.element(
404 ElementDef::new(
405 owner.clone(),
406 [name],
407 SyntaxDef::Macro { args: macro_args(lang_arg) },
408 macro_element(name, kind, lang_arg),
409 )
410 .docs(format!(
411 "Shows inline content of the verbatim kind `{kind}` exactly as written, \
412 between a delimiter character and its partner."
413 )),
414 )?;
415 }
416 for (name, kind, lang_arg, block) in ENVIRONMENTS {
417 let args = if lang_arg { vec![language_argument()] } else { Vec::new() };
418 b.element(
419 ElementDef::new(
420 owner.clone(),
421 [name],
422 SyntaxDef::Environment { args, body: BodyDef::new().verbatim() },
423 environment_element(name, kind, lang_arg, block),
424 )
425 .docs(format!(
426 "Shows its body, content of the verbatim kind `{kind}`, exactly as written, \
427 {}.",
428 if block { "as a block of its own" } else { "inline" }
429 )),
430 )?;
431 }
432 b.element_type_text(
433 MACRO,
434 "Inline content shown exactly as written, written with a macro between a delimiter \
435 character and its partner; its verbatim kind (text, code or identifier) says what \
436 the content is.",
437 )?;
438 b.element_type_text(
439 ENVIRONMENT,
440 "Content shown exactly as written, written as the body of an environment; its \
441 verbatim kind (text or code) says what the content is.",
442 )?;
443 b.lowering_rule(
444 LoweringRule::new(
445 MACRO_RULE,
446 MACRO,
447 LoweringDecl::new().produces(pres::VERBATIM),
448 Arc::new(MacroRule),
449 DefaultMark::Everywhere,
450 )
451 .docs(
452 "a verbatim macro lowers to an inline `flm.pres.verbatim` node carrying its \
453 verbatim kind and language, over the characters of its content argument",
454 ),
455 )?;
456 b.lowering_rule(
457 LoweringRule::new(
458 ENVIRONMENT_RULE,
459 ENVIRONMENT,
460 LoweringDecl::new().produces(pres::VERBATIM),
461 Arc::new(EnvironmentRule),
462 DefaultMark::Everywhere,
463 )
464 .docs(
465 "a verbatim environment lowers to a `flm.pres.verbatim` node carrying its \
466 verbatim kind, display and language, over the characters of its body",
467 ),
468 )?;
469 latex::register(b)?;
470 Ok(())
471 }
472}
473
474/// The [`Verbatim`] feature as a shared value, ready to be listed in a package
475/// entry.
476pub fn feature() -> Arc<dyn FlmFeature> {
477 Arc::new(Verbatim)
478}
479
480#[cfg(test)]
481mod tests {
482 use super::*;
483
484 #[test]
485 fn the_declared_callables_are_pythons_five() {
486 let macros: Vec<&str> = MACROS.iter().map(|(name, _, _)| *name).collect();
487 assert_eq!(macros, ["verbtext", "verbcode", "verba"]);
488 let environments: Vec<&str> = ENVIRONMENTS.iter().map(|(name, _, _, _)| *name).collect();
489 assert_eq!(environments, ["verbatimtext", "verbatimcode"]);
490 }
491
492 #[test]
493 fn only_the_code_environment_is_a_block() {
494 let element = environment_element("verbatimcode", VerbatimKind::Code, true, true);
495 assert_eq!(element.name, ENVIRONMENT);
496 let value = element.value_as::<VerbatimCallable>().expect("valued");
497 assert!(value.block);
498 let text = environment_element("verbatimtext", VerbatimKind::Text, false, false);
499 assert!(!text.value_as::<VerbatimCallable>().expect("valued").block);
500 }
501
502 #[test]
503 fn a_macro_takes_its_language_argument_before_its_content() {
504 let named: Vec<Option<String>> =
505 macro_args(true).iter().map(|arg| arg.name.clone()).collect();
506 assert_eq!(named, [Some(String::from(LANG_ARG)), Some(String::from(CONTENT_ARG))]);
507 let plain: Vec<Option<String>> =
508 macro_args(false).iter().map(|arg| arg.name.clone()).collect();
509 assert_eq!(plain, [Some(String::from(CONTENT_ARG))]);
510 }
511}