Skip to main content

asciidoc_parser/blocks/
is_block.rs

1use std::{fmt::Debug, slice::Iter};
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 an iterator over the nested blocks contained within
126    /// this block.
127    ///
128    /// Many block types do not have nested blocks so the default implementation
129    /// returns an empty iterator.
130    fn nested_blocks(&'src self) -> Iter<'src, Block<'src>> {
131        const NO_BLOCKS: &[Block<'static>] = &[];
132        NO_BLOCKS.iter()
133    }
134
135    /// Returns a mutable slice of the nested blocks contained within this
136    /// block.
137    ///
138    /// This is the mutable counterpart of [`nested_blocks()`]. The default
139    /// returns an empty slice; container blocks override it to expose their
140    /// children for in-place passes such as cross-reference resolution.
141    ///
142    /// [`nested_blocks()`]: Self::nested_blocks
143    fn nested_blocks_mut(&mut self) -> &mut [Block<'src>] {
144        &mut []
145    }
146
147    /// Returns a mutable reference to this block's own resolvable content — its
148    /// body or description-list term — if any.
149    ///
150    /// The default returns `None`; content-bearing blocks override it. This is
151    /// used by in-place passes such as cross-reference resolution. A section
152    /// keeps the default: its heading is resolved by the document-order title
153    /// pass, not the per-content pass.
154    fn content_mut(&mut self) -> Option<&mut Content<'src>> {
155        None
156    }
157
158    /// Returns the ID for this block, if present.
159    ///
160    /// You can assign an ID to a block using the shorthand syntax, the longhand
161    /// syntax, or a legacy block anchor.
162    ///
163    /// In the shorthand syntax, you prefix the name with a hash (`#`) in the
164    /// first position attribute:
165    ///
166    /// ```asciidoc
167    /// [#goals]
168    /// * Goal 1
169    /// * Goal 2
170    /// ```
171    ///
172    /// In the longhand syntax, you use a standard named attribute:
173    ///
174    /// ```asciidoc
175    /// [id=goals]
176    /// * Goal 1
177    /// * Goal 2
178    /// ```
179    ///
180    /// In the legacy block anchor syntax, you surround the name with double
181    /// square brackets:
182    ///
183    /// ```asciidoc
184    /// [[goals]]
185    /// * Goal 1
186    /// * Goal 2
187    /// ```
188    fn id(&'src self) -> Option<&'src str> {
189        self.anchor()
190            .map(|a| a.data())
191            .or_else(|| self.attrlist().and_then(|attrlist| attrlist.id()))
192    }
193
194    /// Returns any role attributes that were found.
195    ///
196    /// You can assign one or more roles to blocks and most inline elements
197    /// using the `role` attribute. The `role` attribute is a [named attribute].
198    /// Even though the attribute name is singular, it may contain multiple
199    /// (space-separated) roles. Roles may also be defined using a shorthand
200    /// (dot-prefixed) syntax.
201    ///
202    /// A role:
203    /// 1. adds additional semantics to an element
204    /// 2. can be used to apply additional styling to a group of elements (e.g.,
205    ///    via a CSS class selector)
206    /// 3. may activate additional behavior if recognized by the converter
207    ///
208    /// **TIP:** The `role` attribute in AsciiDoc always get mapped to the
209    /// `class` attribute in the HTML output. In other words, role names are
210    /// synonymous with HTML class names, thus allowing output elements to be
211    /// identified and styled in CSS using class selectors (e.g.,
212    /// `sidebarblock.role1`).
213    ///
214    /// [named attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/positional-and-named-attributes/#named
215    fn roles(&'src self) -> Vec<&'src str> {
216        match self.attrlist() {
217            Some(attrlist) => attrlist.roles(),
218            None => vec![],
219        }
220    }
221
222    /// Returns any option attributes that were found.
223    ///
224    /// The `options` attribute (often abbreviated as `opts`) is a versatile
225    /// [named attribute] that can be assigned one or more values. It can be
226    /// defined globally as document attribute as well as a block attribute on
227    /// an individual block.
228    ///
229    /// There is no strict schema for options. Any options which are not
230    /// recognized are ignored.
231    ///
232    /// You can assign one or more options to a block using the shorthand or
233    /// formal syntax for the options attribute.
234    ///
235    /// # Shorthand options syntax for blocks
236    ///
237    /// To assign an option to a block, prefix the value with a percent sign
238    /// (`%`) in an attribute list. The percent sign implicitly sets the
239    /// `options` attribute.
240    ///
241    /// ## Example 1: Sidebar block with an option assigned using the shorthand dot
242    ///
243    /// ```asciidoc
244    /// [%option]
245    /// ****
246    /// This is a sidebar with an option assigned to it, named option.
247    /// ****
248    /// ```
249    ///
250    /// You can assign multiple options to a block by prest
251    /// fixing each value with
252    /// a percent sign (`%`).
253    ///
254    /// ## Example 2: Sidebar with two options assigned using the shorthand dot
255    /// ```asciidoc
256    /// [%option1%option2]
257    /// ****
258    /// This is a sidebar with two options assigned to it, named option1 and option2.
259    /// ****
260    /// ```
261    ///
262    /// # Formal options syntax for blocks
263    ///
264    /// Explicitly set `options` or `opts`, followed by the equals sign (`=`),
265    /// and then the value in an attribute list.
266    ///
267    /// ## Example 3. Sidebar block with an option assigned using the formal syntax
268    /// ```asciidoc
269    /// [opts=option]
270    /// ****
271    /// This is a sidebar with an option assigned to it, named option.
272    /// ****
273    /// ```
274    ///
275    /// Separate multiple option values with commas (`,`).
276    ///
277    /// ## Example 4. Sidebar with three options assigned using the formal syntax
278    /// ```asciidoc
279    /// [opts="option1,option2"]
280    /// ****
281    /// This is a sidebar with two options assigned to it, option1 and option2.
282    /// ****
283    /// ```
284    ///
285    /// [named attribute]: https://docs.asciidoctor.org/asciidoc/latest/attributes/positional-and-named-attributes/#named
286    fn options(&'src self) -> Vec<&'src str> {
287        match self.attrlist() {
288            Some(attrlist) => attrlist.options(),
289            None => vec![],
290        }
291    }
292
293    /// Returns `true` if this block has the named option.
294    ///
295    /// See [`options()`] for a description of option syntax.
296    ///
297    /// [`options()`]: Self::options
298    fn has_option<N: AsRef<str>>(&'src self, name: N) -> bool {
299        self.attrlist()
300            .is_some_and(|attrlist| attrlist.has_option(name))
301    }
302
303    /// Returns the source text for the title for this block, if present.
304    fn title_source(&'src self) -> Option<Span<'src>>;
305
306    /// Returns the rendered title for this block, if present.
307    fn title(&self) -> Option<&str>;
308
309    /// Returns the caption prefix for this block, if it has one.
310    ///
311    /// A *captionable* block (e.g. an example block or a table) that has a
312    /// [title](Self::title) is given a caption: a label and an automatically
313    /// incremented number that a converter prepends to the title (e.g.
314    /// `"Example 1. "`, including the trailing separator and space). The prefix
315    /// combines a label drawn from a document attribute (e.g.
316    /// `example-caption`) with the block's [number](Self::number).
317    ///
318    /// The caption is absent when the block has no title, when its caption
319    /// attribute has been unset, or when an explicitly empty caption was
320    /// supplied. An explicit `caption` attribute overrides the prefix with a
321    /// verbatim, unnumbered label. The default implementation returns `None`.
322    fn caption(&self) -> Option<&str> {
323        None
324    }
325
326    /// Returns the automatically assigned number for this block, if it has one.
327    ///
328    /// Captionable blocks are numbered, per context, in document order as they
329    /// finish parsing (so a nested captioned block is numbered before its
330    /// container). The number is the bare counter value that appears in the
331    /// block's [caption](Self::caption) prefix. It is absent when the block is
332    /// not captioned, or when its caption comes from an explicit (unnumbered)
333    /// `caption` attribute. The default implementation returns `None`.
334    fn number(&self) -> Option<usize> {
335        None
336    }
337
338    /// Returns the anchor for this block, if present.
339    fn anchor(&'src self) -> Option<Span<'src>>;
340
341    /// Returns the reference text for this block's anchor, if present.
342    fn anchor_reftext(&'src self) -> Option<Span<'src>>;
343
344    /// Returns the attribute list for this block, if present.
345    fn attrlist(&'src self) -> Option<&'src Attrlist<'src>>;
346
347    /// Returns the default substitution group that is applied unless you
348    /// customize the substitutions for a particular element.
349    fn substitution_group(&'src self) -> SubstitutionGroup {
350        SubstitutionGroup::Normal
351    }
352}
353
354/// The content model of a block determines what kind of content the block can
355/// have (if any) and how that content is processed.
356#[derive(Clone, Copy, Eq, PartialEq)]
357pub enum ContentModel {
358    /// A block that may only contain other blocks (e.g., a section)
359    Compound,
360
361    /// A block that's treated as contiguous lines of paragraph text (and
362    /// subject to normal substitutions) (e.g., a paragraph block)
363    Simple,
364
365    /// A block that holds verbatim text (displayed "as is") (and subject to
366    /// verbatim substitutions) (e.g., a listing block)
367    Verbatim,
368
369    /// A block that holds unprocessed content passed directly through to the
370    /// output with no substitutions applied (e.g., a passthrough block)
371    Raw,
372
373    /// A block that has no content (e.g., an image block)
374    Empty,
375
376    /// A special content model reserved for tables that enforces a fixed
377    /// structure
378    Table,
379}
380
381impl std::fmt::Debug for ContentModel {
382    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
383        match self {
384            ContentModel::Compound => write!(f, "ContentModel::Compound"),
385            ContentModel::Simple => write!(f, "ContentModel::Simple"),
386            ContentModel::Verbatim => write!(f, "ContentModel::Verbatim"),
387            ContentModel::Raw => write!(f, "ContentModel::Raw"),
388            ContentModel::Empty => write!(f, "ContentModel::Empty"),
389            ContentModel::Table => write!(f, "ContentModel::Table"),
390        }
391    }
392}
393
394#[cfg(test)]
395mod tests {
396    #![allow(clippy::unwrap_used)]
397
398    mod content_model {
399        mod impl_debug {
400            use crate::blocks::ContentModel;
401
402            #[test]
403            fn compound() {
404                let content_model = ContentModel::Compound;
405                let debug_output = format!("{:?}", content_model);
406                assert_eq!(debug_output, "ContentModel::Compound");
407            }
408
409            #[test]
410            fn simple() {
411                let content_model = ContentModel::Simple;
412                let debug_output = format!("{:?}", content_model);
413                assert_eq!(debug_output, "ContentModel::Simple");
414            }
415
416            #[test]
417            fn verbatim() {
418                let content_model = ContentModel::Verbatim;
419                let debug_output = format!("{:?}", content_model);
420                assert_eq!(debug_output, "ContentModel::Verbatim");
421            }
422
423            #[test]
424            fn raw() {
425                let content_model = ContentModel::Raw;
426                let debug_output = format!("{:?}", content_model);
427                assert_eq!(debug_output, "ContentModel::Raw");
428            }
429
430            #[test]
431            fn empty() {
432                let content_model = ContentModel::Empty;
433                let debug_output = format!("{:?}", content_model);
434                assert_eq!(debug_output, "ContentModel::Empty");
435            }
436
437            #[test]
438            fn table() {
439                let content_model = ContentModel::Table;
440                let debug_output = format!("{:?}", content_model);
441                assert_eq!(debug_output, "ContentModel::Table");
442            }
443        }
444    }
445}