asciidoc_parser/blocks/is_block.rs
1use std::fmt::Debug;
2
3use crate::{
4 Span,
5 attributes::Attrlist,
6 blocks::{Block, is_built_in_context},
7 content::{Content, SubstitutionGroup},
8 strings::CowStr,
9};
10
11/// **Block elements** form the main structure of an AsciiDoc document, starting
12/// with the document itself.
13///
14/// A block element (aka **block**) is a discrete, line-oriented chunk of
15/// content in an AsciiDoc document. Once parsed, that chunk of content becomes
16/// a block element in the parsed document model. Certain blocks may contain
17/// other blocks, so we say that blocks can be nested. The converter visits each
18/// block in turn, in document order, converting it to a corresponding chunk of
19/// output.
20///
21/// This trait implements many of the same core methods as the [`Block`] enum
22/// but provides a mechanism for third-party code to extend the behavior of
23/// blocks.
24pub trait IsBlock<'src>: Debug + Eq + PartialEq {
25 /// Returns the [`ContentModel`] for this block.
26 fn content_model(&self) -> ContentModel;
27
28 /// Returns the rendered content for this block, if any.
29 ///
30 /// Some blocks (especially compound blocks) do not directly contain
31 /// content. In such cases, this function will return `None`.
32 ///
33 /// This content will contain the text _after_ substitutions have been
34 /// applied.
35 fn rendered_content(&'src self) -> Option<&'src str> {
36 None
37 }
38
39 /// Returns the resolved context for this block.
40 ///
41 /// A block’s context is also sometimes referred to as a name, such as an
42 /// example block, a sidebar block, an admonition block, or a section.
43 ///
44 /// Every block has a context. The context is often implied by the syntax,
45 /// but can be declared explicitly in certain cases. The context is what
46 /// distinguishes one kind of block from another. You can think of the
47 /// context as the block’s type.
48 ///
49 /// For that reason, the context is not defined as an enumeration, but
50 /// rather as a string type that is optimized for the case where predefined
51 /// constants are viable.
52 ///
53 /// A block's context can be replaced by a block style that matches a
54 /// built-in context. Unlike [`raw_context()`], that transformation _is_
55 /// performed by this function.
56 ///
57 /// [`raw_context()`]: Self::raw_context
58 fn resolved_context(&'src self) -> CowStr<'src> {
59 if let Some(declared_style) = self.declared_style() {
60 if is_built_in_context(declared_style) {
61 return declared_style.into();
62 }
63
64 // The `source` style is not itself a context; it specializes the
65 // `listing` context (a source block is a listing block with syntax
66 // highlighting). A `source` style therefore resolves the context to
67 // `listing` – for example, `[source]` placed over a `....` literal
68 // block makes it a listing block.
69 if declared_style == "source" {
70 return "listing".into();
71 }
72
73 // The `abstract` style is not itself a context; it specializes the
74 // `open` context. Asciidoctor rebuilds an `[abstract]` paragraph as
75 // an open block (keeping the simple content model), so the style
76 // resolves a paragraph's context to `open`. On any other context
77 // (including the `--` delimited form, which is already `open`), the
78 // declared style is preserved without changing the context.
79 if declared_style == "abstract" && self.raw_context().as_ref() == "paragraph" {
80 return "open".into();
81 }
82 }
83
84 self.raw_context()
85 }
86
87 /// Returns the raw (uninterpreted) context for this block.
88 ///
89 /// A block’s context is also sometimes referred to as a name, such as an
90 /// example block, a sidebar block, an admonition block, or a section.
91 ///
92 /// Every block has a context. The context is often implied by the syntax,
93 /// but can be declared explicitly in certain cases. The context is what
94 /// distinguishes one kind of block from another. You can think of the
95 /// context as the block’s type.
96 ///
97 /// For that reason, the context is not defined as an enumeration, but
98 /// rather as a string type that is optimized for the case where predefined
99 /// constants are viable.
100 ///
101 /// A block's context can be replaced by a block style that matches a
102 /// built-in context. That transformation is only performed by
103 /// [`resolved_context()`], not this function.
104 ///
105 /// [`resolved_context()`]: Self::resolved_context
106 fn raw_context(&self) -> CowStr<'src>;
107
108 /// Returns the declared (uninterpreted) style for this block.
109 ///
110 /// Above some blocks, you may notice a name at the start of the block
111 /// attribute list (e.g., `[source]` or `[verse]`). The first positional
112 /// (unnamed) attribute in the block attribute list is used to declare the
113 /// block style.
114 ///
115 /// The declared block style is the value the author supplies.
116 ///
117 /// That value is then interpreted and resolved. That interpretation is not
118 /// performed by this function.
119 fn declared_style(&'src self) -> Option<&'src str> {
120 self.attrlist()
121 .and_then(|attrlist| attrlist.nth_attribute(1))
122 .and_then(|attr| attr.block_style())
123 }
124
125 /// Returns a mutable slice of the child blocks contained within this block.
126 ///
127 /// The default returns an empty slice; container blocks override it to
128 /// expose their children for in-place passes such as cross-reference
129 /// resolution. This is a low-level extension hook; to read a block's
130 /// children, use its inherent `child_blocks()` accessor or
131 /// [`FindBlocks::child_blocks()`].
132 ///
133 /// [`FindBlocks::child_blocks()`]: crate::blocks::FindBlocks::child_blocks
134 fn child_blocks_mut(&mut self) -> &mut [Block<'src>] {
135 &mut []
136 }
137
138 /// Returns a mutable reference to this block's own resolvable content – its
139 /// body or description-list term – if any.
140 ///
141 /// The default returns `None`; content-bearing blocks override it. This is
142 /// used by in-place passes such as cross-reference resolution. A section
143 /// keeps the default: its heading is resolved by the document-order title
144 /// pass, not the per-content pass.
145 fn content_mut(&mut self) -> Option<&mut Content<'src>> {
146 None
147 }
148
149 /// Returns the ID for this block, if present.
150 ///
151 /// You can assign an ID to a block using the shorthand syntax, the longhand
152 /// syntax, or a legacy block anchor.
153 ///
154 /// In the shorthand syntax, you prefix the name with a hash (`#`) in the
155 /// first position attribute:
156 ///
157 /// ```asciidoc
158 /// [#goals]
159 /// * Goal 1
160 /// * Goal 2
161 /// ```
162 ///
163 /// In the longhand syntax, you use a standard named attribute:
164 ///
165 /// ```asciidoc
166 /// [id=goals]
167 /// * Goal 1
168 /// * Goal 2
169 /// ```
170 ///
171 /// In the legacy block anchor syntax, you surround the name with double
172 /// square brackets:
173 ///
174 /// ```asciidoc
175 /// [[goals]]
176 /// * Goal 1
177 /// * Goal 2
178 /// ```
179 fn id(&'src self) -> Option<&'src str> {
180 self.anchor()
181 .map(|a| a.data())
182 .or_else(|| self.attrlist().and_then(|attrlist| attrlist.id()))
183 }
184
185 /// Returns any role attributes that were found.
186 ///
187 /// You can assign one or more roles to blocks and most inline elements
188 /// using the `role` attribute. The `role` attribute is a [named attribute].
189 /// Even though the attribute name is singular, it may contain multiple
190 /// (space-separated) roles. Roles may also be defined using a shorthand
191 /// (dot-prefixed) syntax.
192 ///
193 /// A role:
194 /// 1. adds additional semantics to an element
195 /// 2. can be used to apply additional styling to a group of elements (e.g.,
196 /// via a CSS class selector)
197 /// 3. may activate additional behavior if recognized by the converter
198 ///
199 /// **TIP:** The `role` attribute in AsciiDoc always get mapped to the
200 /// `class` attribute in the HTML output. In other words, role names are
201 /// synonymous with HTML class names, thus allowing output elements to be
202 /// identified and styled in CSS using class selectors (e.g.,
203 /// `sidebarblock.role1`).
204 ///
205 /// [named attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/positional-and-named-attributes/#named
206 fn roles(&'src self) -> Vec<&'src str> {
207 match self.attrlist() {
208 Some(attrlist) => attrlist.roles(),
209 None => vec![],
210 }
211 }
212
213 /// Returns any option attributes that were found.
214 ///
215 /// The `options` attribute (often abbreviated as `opts`) is a versatile
216 /// [named attribute] that can be assigned one or more values. It can be
217 /// defined globally as document attribute as well as a block attribute on
218 /// an individual block.
219 ///
220 /// There is no strict schema for options. Any options which are not
221 /// recognized are ignored.
222 ///
223 /// You can assign one or more options to a block using the shorthand or
224 /// formal syntax for the options attribute.
225 ///
226 /// # Shorthand options syntax for blocks
227 ///
228 /// To assign an option to a block, prefix the value with a percent sign
229 /// (`%`) in an attribute list. The percent sign implicitly sets the
230 /// `options` attribute.
231 ///
232 /// ## Example 1: Sidebar block with an option assigned using the shorthand dot
233 ///
234 /// ```asciidoc
235 /// [%option]
236 /// ****
237 /// This is a sidebar with an option assigned to it, named option.
238 /// ****
239 /// ```
240 ///
241 /// You can assign multiple options to a block by prest
242 /// fixing each value with
243 /// a percent sign (`%`).
244 ///
245 /// ## Example 2: Sidebar with two options assigned using the shorthand dot
246 /// ```asciidoc
247 /// [%option1%option2]
248 /// ****
249 /// This is a sidebar with two options assigned to it, named option1 and option2.
250 /// ****
251 /// ```
252 ///
253 /// # Formal options syntax for blocks
254 ///
255 /// Explicitly set `options` or `opts`, followed by the equals sign (`=`),
256 /// and then the value in an attribute list.
257 ///
258 /// ## Example 3. Sidebar block with an option assigned using the formal syntax
259 /// ```asciidoc
260 /// [opts=option]
261 /// ****
262 /// This is a sidebar with an option assigned to it, named option.
263 /// ****
264 /// ```
265 ///
266 /// Separate multiple option values with commas (`,`).
267 ///
268 /// ## Example 4. Sidebar with three options assigned using the formal syntax
269 /// ```asciidoc
270 /// [opts="option1,option2"]
271 /// ****
272 /// This is a sidebar with two options assigned to it, option1 and option2.
273 /// ****
274 /// ```
275 ///
276 /// [named attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/positional-and-named-attributes/#named
277 fn options(&'src self) -> Vec<&'src str> {
278 match self.attrlist() {
279 Some(attrlist) => attrlist.options(),
280 None => vec![],
281 }
282 }
283
284 /// Returns `true` if this block has the named option.
285 ///
286 /// See [`options()`] for a description of option syntax.
287 ///
288 /// [`options()`]: Self::options
289 fn has_option<N: AsRef<str>>(&'src self, name: N) -> bool {
290 self.attrlist()
291 .is_some_and(|attrlist| attrlist.has_option(name))
292 }
293
294 /// Returns the source text for the title for this block, if present.
295 fn title_source(&'src self) -> Option<Span<'src>>;
296
297 /// Returns the rendered title for this block, if present.
298 fn title(&self) -> Option<&str>;
299
300 /// Returns the caption prefix for this block, if it has one.
301 ///
302 /// A *captionable* block (e.g. an example block or a table) that has a
303 /// [title](Self::title) is given a caption: a label and an automatically
304 /// incremented number that a converter prepends to the title (e.g.
305 /// `"Example 1. "`, including the trailing separator and space). The prefix
306 /// combines a label drawn from a document attribute (e.g.
307 /// `example-caption`) with the block's [number](Self::number).
308 ///
309 /// The caption is absent when the block has no title, when its caption
310 /// attribute has been unset, or when an explicitly empty caption was
311 /// supplied. An explicit `caption` attribute overrides the prefix with a
312 /// verbatim, unnumbered label. The default implementation returns `None`.
313 fn caption(&self) -> Option<&str> {
314 None
315 }
316
317 /// Returns the automatically assigned number for this block, if it has one.
318 ///
319 /// Captionable blocks are numbered, per context, in document order as they
320 /// finish parsing (so a nested captioned block is numbered before its
321 /// container). The number is the bare counter value that appears in the
322 /// block's [caption](Self::caption) prefix. It is absent when the block is
323 /// not captioned, or when its caption comes from an explicit (unnumbered)
324 /// `caption` attribute. The default implementation returns `None`.
325 fn number(&self) -> Option<usize> {
326 None
327 }
328
329 /// Returns the anchor for this block, if present.
330 fn anchor(&'src self) -> Option<Span<'src>>;
331
332 /// Returns the reference text for this block's anchor, if present.
333 fn anchor_reftext(&'src self) -> Option<Span<'src>>;
334
335 /// Returns the attribute list for this block, if present.
336 fn attrlist(&'src self) -> Option<&'src Attrlist<'src>>;
337
338 /// Returns the default substitution group that is applied unless you
339 /// customize the substitutions for a particular element.
340 fn substitution_group(&'src self) -> SubstitutionGroup {
341 SubstitutionGroup::Normal
342 }
343}
344
345/// The content model of a block determines what kind of content the block can
346/// have (if any) and how that content is processed.
347#[derive(Clone, Copy, Eq, Hash, PartialEq)]
348pub enum ContentModel {
349 /// A block that may only contain other blocks (e.g., a section)
350 Compound,
351
352 /// A block that's treated as contiguous lines of paragraph text (and
353 /// subject to normal substitutions) (e.g., a paragraph block)
354 Simple,
355
356 /// A block that holds verbatim text (displayed "as is") (and subject to
357 /// verbatim substitutions) (e.g., a listing block)
358 Verbatim,
359
360 /// A block that holds unprocessed content passed directly through to the
361 /// output with no substitutions applied (e.g., a passthrough block)
362 Raw,
363
364 /// A block that has no content (e.g., an image block).
365 Empty,
366
367 /// A special content model reserved for tables that enforces a fixed
368 /// structure.
369 Table,
370}
371
372impl std::fmt::Debug for ContentModel {
373 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374 match self {
375 ContentModel::Compound => write!(f, "ContentModel::Compound"),
376 ContentModel::Simple => write!(f, "ContentModel::Simple"),
377 ContentModel::Verbatim => write!(f, "ContentModel::Verbatim"),
378 ContentModel::Raw => write!(f, "ContentModel::Raw"),
379 ContentModel::Empty => write!(f, "ContentModel::Empty"),
380 ContentModel::Table => write!(f, "ContentModel::Table"),
381 }
382 }
383}
384
385#[cfg(test)]
386mod tests {
387 #![allow(clippy::unwrap_used)]
388
389 mod content_model {
390 mod impl_debug {
391 use crate::blocks::ContentModel;
392
393 #[test]
394 fn compound() {
395 let content_model = ContentModel::Compound;
396 let debug_output = format!("{:?}", content_model);
397 assert_eq!(debug_output, "ContentModel::Compound");
398 }
399
400 #[test]
401 fn simple() {
402 let content_model = ContentModel::Simple;
403 let debug_output = format!("{:?}", content_model);
404 assert_eq!(debug_output, "ContentModel::Simple");
405 }
406
407 #[test]
408 fn verbatim() {
409 let content_model = ContentModel::Verbatim;
410 let debug_output = format!("{:?}", content_model);
411 assert_eq!(debug_output, "ContentModel::Verbatim");
412 }
413
414 #[test]
415 fn raw() {
416 let content_model = ContentModel::Raw;
417 let debug_output = format!("{:?}", content_model);
418 assert_eq!(debug_output, "ContentModel::Raw");
419 }
420
421 #[test]
422 fn empty() {
423 let content_model = ContentModel::Empty;
424 let debug_output = format!("{:?}", content_model);
425 assert_eq!(debug_output, "ContentModel::Empty");
426 }
427
428 #[test]
429 fn table() {
430 let content_model = ContentModel::Table;
431 let debug_output = format!("{:?}", content_model);
432 assert_eq!(debug_output, "ContentModel::Table");
433 }
434 }
435 }
436}