flm_core/stdlib/features/quote/
elements.rs1use std::sync::Arc;
12
13use techy::core::node::NodeRef;
14
15use crate::lang::{Flm, FlmGroupType};
16use crate::lang::mint::{
17 ArgDef, ArgLayout, BodyDef, BodyLayout, ElementDef, ScopedPackageDef, SyntaxDef, field_element,
18};
19use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
20use crate::model::element::{ElementSpec, element_value};
21use crate::model::names::{FeatureName, Name};
22use crate::stdlib::backends::lowering::rules::owning_callable;
23
24use super::config::{QuoteEnvironment, QuoteSection};
25use super::{
26 CONTENT_ARG, INDENT_COMMAND, LINEBREAK_COMMAND, LINES_PACKAGE, QUOTE, SECTION,
27 sections_package,
28};
29
30#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct QuoteElement {
34 pub name: String,
37 pub environment: QuoteEnvironment,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct SectionElement {
53 pub section: QuoteSection,
55}
56
57impl BlockRoleAspect for SectionElement {
58 fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole {
59 match section_position(node) {
60 Some(position) if position.quote.environment.holds_blocks() => BlockRole::Block,
61 _ => BlockRole::DEFAULT,
62 }
63 }
64}
65
66#[derive(Debug, Clone, Copy)]
70pub(super) struct SectionPosition<'t> {
71 pub(super) section: QuoteSection,
73 pub(super) quote: &'t QuoteElement,
75}
76
77pub(super) fn section_position<'t>(node: &NodeRef<'t, Flm>) -> Option<SectionPosition<'t>> {
86 let section = element_value::<SectionElement>(node)?.section;
87 let quote = quote_of_body(node)?;
88 quote.environment.enables(section).then_some(SectionPosition { section, quote })
89}
90
91fn quote_of_body<'t>(node: &NodeRef<'t, Flm>) -> Option<&'t QuoteElement> {
94 owning_callable(node).and_then(|owner| element_value::<QuoteElement>(&owner))
96}
97
98pub(super) fn is_in_quote_body(node: &NodeRef<'_, Flm>) -> bool {
102 let place = match node.parent() {
103 Some(parent) if parent.group_type() == Some(FlmGroupType::Paragraph) => parent,
104 _ => *node,
105 };
106 quote_of_body(&place).is_some()
107}
108
109fn quote_element(name: &str, environment: &QuoteEnvironment) -> Arc<ElementSpec> {
112 Arc::new(
113 ElementSpec::new(QUOTE)
114 .docs(format!("`{name}`: a quote environment, a quotation set apart from the running text."))
115 .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block)))
116 .with_value(Arc::new(QuoteElement {
117 name: name.to_string(),
118 environment: environment.clone(),
119 })),
120 )
121}
122
123pub(super) fn environment_def(
131 owner: &FeatureName,
132 name: &str,
133 environment: &QuoteEnvironment,
134) -> ElementDef {
135 let layout = if environment.holds_blocks() { BodyLayout::Blocks } else { BodyLayout::Inline };
136 let mut body = BodyDef::new().layout(layout);
137 if !environment.sections.is_empty() {
138 body = body.scoped(sections_package(name));
139 }
140 if environment.bare == Some(QuoteSection::Lines) {
141 body = body.scoped(LINES_PACKAGE);
142 }
143 let commands: Vec<String> =
144 environment.sections.iter().map(|section| format!("`\\{}`", section.as_str())).collect();
145 let docs = match (commands.is_empty(), environment.bare) {
146 (false, _) => format!(
147 "Writes a quotation set apart from the running text, whose quotation sections are \
148 written with {}.",
149 commands.join(", ")
150 ),
151 (true, Some(kind)) => format!(
152 "Writes a quotation set apart from the running text, whose content is one {} section.",
153 kind.as_str()
154 ),
155 (true, None) => String::from("Writes a quotation set apart from the running text."),
156 };
157 ElementDef::new(
158 owner.clone(),
159 [name],
160 SyntaxDef::Environment { args: Vec::new(), body },
161 quote_element(name, environment),
162 )
163 .docs(docs)
164}
165
166fn section_element(section: QuoteSection) -> Arc<ElementSpec> {
170 let value = Arc::new(SectionElement { section });
171 Arc::new(
172 ElementSpec::new(SECTION)
173 .docs(format!("`\\{}{{…}}`: a {} section of a quotation.", section.as_str(), section.as_str()))
174 .with::<dyn BlockRoleAspect>(Arc::clone(&value) as Arc<dyn BlockRoleAspect>)
175 .with_value(value),
176 )
177}
178
179fn section_def(owner: &FeatureName, section: QuoteSection, element: &Arc<ElementSpec>) -> ElementDef {
187 let mut content = ArgDef::mandatory(CONTENT_ARG);
188 let docs = match section {
189 QuoteSection::Text => "The quoted passage, one paragraph.",
190 QuoteSection::Lines => {
191 content = content.scoped(LINES_PACKAGE);
192 "The lines, each ended by `\\\\`; `\\indent` at the start of a line indents it by a \
193 tab."
194 }
195 QuoteSection::Attributed => "The attribution: an author, a source.",
196 QuoteSection::Block => {
197 content = content.layout(ArgLayout::InlineOrBlocks);
198 "Paragraphs and blocks; content written on one line is one paragraph."
199 }
200 };
201 let name = section.as_str();
202 ElementDef::new(
203 owner.clone(),
204 [name],
205 SyntaxDef::Macro { args: vec![content.docs(docs)] },
206 Arc::clone(element),
207 )
208 .docs(match section {
209 QuoteSection::Text => "Writes a quoted passage, a text section of the quotation around it.",
210 QuoteSection::Lines => "Writes a lines section of the quotation around it.",
211 QuoteSection::Attributed => "Writes the attribution of the quotation around it.",
212 QuoteSection::Block => "Writes a block section of the quotation around it.",
213 })
214}
215
216pub(super) fn sections_packages<'c>(
227 owner: &FeatureName,
228 environments: impl IntoIterator<Item = (&'c String, &'c QuoteEnvironment)>,
229) -> Vec<ScopedPackageDef> {
230 let elements: Vec<(QuoteSection, Arc<ElementSpec>)> =
231 QuoteSection::ALL.into_iter().map(|section| (section, section_element(section))).collect();
232 environments
233 .into_iter()
234 .filter(|(_, environment)| !environment.sections.is_empty())
235 .map(|(name, environment)| {
236 let defs = environment
237 .sections
238 .iter()
239 .filter_map(|section| elements.iter().find(|(kind, _)| kind == section))
240 .map(|(section, element)| section_def(owner, *section, element))
241 .collect();
242 ScopedPackageDef {
243 owner: owner.clone(),
244 name: Name::from(sections_package(name)),
245 elements: defs,
246 docs: format!(
247 "The quotation-section commands available inside the body of the quote \
248 environment `{name}`."
249 ),
250 }
251 })
252 .collect()
253}
254
255pub(super) fn lines_package(owner: &FeatureName) -> ScopedPackageDef {
261 let linebreak = ElementDef::new(
262 owner.clone(),
263 [LINEBREAK_COMMAND],
264 SyntaxDef::Macro { args: Vec::new() },
265 field_element(
266 "A `\\\\` inside a lines section of a quotation: the end of a line.",
267 ),
268 )
269 .docs("Ends a line of the lines section.");
270 let indent = ElementDef::new(
271 owner.clone(),
272 [INDENT_COMMAND],
273 SyntaxDef::Macro { args: Vec::new() },
274 field_element(
275 "An `\\indent` at the start of a line of a lines section of a quotation: one tab of \
276 indentation for the line.",
277 ),
278 )
279 .docs("Indents the line it starts by one tab; written several times, by as many tabs.");
280 ScopedPackageDef {
281 owner: owner.clone(),
282 name: Name::from(LINES_PACKAGE),
283 elements: vec![linebreak, indent],
284 docs: String::from(
285 "The commands available inside a lines section of a quotation: `\\\\`, which ends a \
286 line, and `\\indent`, which indents the line it starts.",
287 ),
288 }
289}