mdbook-admonish 1.7.0

A preprocessor for mdbook to add Material Design admonishments.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
use anyhow::{anyhow, Result};
use mdbook::{
    book::{Book, BookItem},
    errors::Result as MdbookResult,
    preprocess::{Preprocessor, PreprocessorContext},
    utils::unique_id_from_content,
};
use pulldown_cmark::{CodeBlockKind::*, Event, Options, Parser, Tag};
use std::{borrow::Cow, str::FromStr};

mod config;
mod types;

use crate::{config::AdmonitionInfo, types::Directive};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OnFailure {
    Bail,
    Continue,
}

impl Default for OnFailure {
    fn default() -> Self {
        Self::Continue
    }
}

impl FromStr for OnFailure {
    type Err = ();

    fn from_str(string: &str) -> Result<Self, ()> {
        match string {
            "bail" => Ok(Self::Bail),
            "continue" => Ok(Self::Continue),
            _ => Ok(Self::Continue),
        }
    }
}

impl OnFailure {
    fn from_context(context: &PreprocessorContext) -> Self {
        context
            .config
            .get("preprocessor.admonish.on_failure")
            .and_then(|value| value.as_str())
            .map(|value| OnFailure::from_str(value).unwrap_or_default())
            .unwrap_or_default()
    }
}

pub struct Admonish;

impl Preprocessor for Admonish {
    fn name(&self) -> &str {
        "admonish"
    }

    fn run(&self, ctx: &PreprocessorContext, mut book: Book) -> MdbookResult<Book> {
        ensure_compatible_assets_version(ctx)?;
        let on_failure = OnFailure::from_context(ctx);

        let mut res = None;
        book.for_each_mut(|item: &mut BookItem| {
            if let Some(Err(_)) = res {
                return;
            }

            if let BookItem::Chapter(ref mut chapter) = *item {
                res = Some(preprocess(&chapter.content, on_failure).map(|md| {
                    chapter.content = md;
                }));
            }
        });

        res.unwrap_or(Ok(())).map(|_| book)
    }

    fn supports_renderer(&self, renderer: &str) -> bool {
        renderer == "html"
    }
}

fn ensure_compatible_assets_version(ctx: &PreprocessorContext) -> Result<()> {
    use semver::{Version, VersionReq};

    const REQUIRES_ASSETS_VERSION: &str = std::include_str!("./REQUIRED_ASSETS_VERSION");
    let requirement = VersionReq::parse(REQUIRES_ASSETS_VERSION.trim()).unwrap();

    const USER_ACTION: &str = "Please run `mdbook-admonish install` to update installed assets.";
    const DOCS_REFERENCE: &str = "For more information, see: https://github.com/tommilligan/mdbook-admonish#semantic-versioning";

    let version = match ctx
        .config
        .get("preprocessor.admonish.assets_version")
        .and_then(|value| value.as_str())
    {
        Some(version) => version,
        None => {
            return Err(anyhow!(
                r#"ERROR:
  Incompatible assets installed: required mdbook-admonish assets version '{requirement}', but did not find a version.
  {USER_ACTION}
  {DOCS_REFERENCE}"#
            ))
        }
    };

    let version = Version::parse(version).unwrap();

    if !requirement.matches(&version) {
        return Err(anyhow!(
            r#"ERROR:
  Incompatible assets installed: required mdbook-admonish assets version '{requirement}', but found '{version}'.
  {USER_ACTION}
  {DOCS_REFERENCE}"#
        ));
    };
    Ok(())
}

impl Directive {
    fn classname(&self) -> &'static str {
        match self {
            Directive::Note => "note",
            Directive::Abstract => "abstract",
            Directive::Info => "info",
            Directive::Tip => "tip",
            Directive::Success => "success",
            Directive::Question => "question",
            Directive::Warning => "warning",
            Directive::Failure => "failure",
            Directive::Danger => "danger",
            Directive::Bug => "bug",
            Directive::Example => "example",
            Directive::Quote => "quote",
        }
    }
}

#[derive(Debug, PartialEq)]
struct Admonition<'a> {
    directive: Directive,
    title: Option<String>,
    content: Cow<'a, str>,
    additional_classnames: Vec<String>,
    collapsible: bool,
}

impl<'a> Admonition<'a> {
    pub fn new(info: AdmonitionInfo, content: &'a str) -> Self {
        let AdmonitionInfo {
            directive,
            title,
            additional_classnames,
            collapsible,
        } = info;
        Self {
            directive,
            title,
            content: Cow::Borrowed(content),
            additional_classnames,
            collapsible,
        }
    }

    fn html(&self, anchor_id: &str) -> String {
        let mut additional_class = Cow::Borrowed(self.directive.classname());
        let title = &self.title;
        let content = &self.content;

        let title_block = if self.collapsible { "summary" } else { "div" };

        let title_html = title
            .as_ref()
            .map(|title| {
                Cow::Owned(format!(
                    r##"<{title_block} class="admonition-title">

{title}

<a class="admonition-anchor-link" href="#{ANCHOR_ID_PREFIX}-{anchor_id}"></a>
</{title_block}>
"##
                ))
            })
            .unwrap_or(Cow::Borrowed(""));

        if !self.additional_classnames.is_empty() {
            let mut buffer = additional_class.into_owned();
            for additional_classname in &self.additional_classnames {
                buffer.push(' ');
                buffer.push_str(additional_classname);
            }

            additional_class = Cow::Owned(buffer);
        }

        let admonition_block = if self.collapsible { "details" } else { "div" };
        // Notes on the HTML template:
        // - the additional whitespace around the content are deliberate
        //   In line with the commonmark spec, this allows the inner content to be
        //   rendered as markdown paragraphs.
        format!(
            r#"<{admonition_block} id="{ANCHOR_ID_PREFIX}-{anchor_id}" class="admonition {additional_class}">
{title_html}<div>

{content}

</div>
</{admonition_block}>"#,
        )
    }
}

const ANCHOR_ID_PREFIX: &str = "admonition";
const ANCHOR_ID_DEFAULT: &str = "default";

fn extract_admonish_body(content: &str) -> &str {
    const PRE_END: char = '\n';
    const POST: &str = "```";

    // We can't trust the info string length to find the start of the body
    // it may change length if it contains HTML or character escapes.
    //
    // So we scan for the first newline and use that.
    // If gods forbid it doesn't exist for some reason, just include the whole info string.
    let start_index = content
        // Start one character _after_ the newline
        .find(PRE_END)
        .map(|index| index + 1)
        .unwrap_or_default();
    let end_index = content.len() - POST.len();

    let admonish_content = &content[start_index..end_index];
    // The newline after a code block is technically optional, so we have to
    // trim it off dynamically.
    admonish_content.trim()
}

/// Given the content in the span of the code block, and the info string,
/// return `Some(Admonition)` if the code block is an admonition.
///
/// If there is an error parsing the admonition, either:
///
/// - Display a UI error message output in the book.
/// - If configured, break the build.
///
/// If the code block is not an admonition, return `None`.
fn parse_admonition<'a>(
    info_string: &'a str,
    content: &'a str,
    on_failure: OnFailure,
) -> Option<MdbookResult<Admonition<'a>>> {
    let info = AdmonitionInfo::from_info_string(info_string)?;
    let info = match info {
        Ok(info) => info,
        // FIXME return error messages to break build if configured
        // Err(message) => return Some(Err(content)),
        Err(message) => {
            return Some(match on_failure {
                OnFailure::Continue => Ok(Admonition {
                    directive: Directive::Bug,
                    title: Some("Error rendering admonishment".to_owned()),
                    additional_classnames: Vec::new(),
                    collapsible: false,
                    content: Cow::Owned(format!(
                        r#"Failed with: {message}

Original markdown input:

``````
{content}
``````
"#
                    )),
                }),
                OnFailure::Bail => Err(anyhow!("Error processing admonition, bailing:\n{content}")),
            })
        }
    };
    let body = extract_admonish_body(content);
    Some(Ok(Admonition::new(info, body)))
}

fn preprocess(content: &str, on_failure: OnFailure) -> MdbookResult<String> {
    let mut id_counter = Default::default();
    let mut opts = Options::empty();
    opts.insert(Options::ENABLE_TABLES);
    opts.insert(Options::ENABLE_FOOTNOTES);
    opts.insert(Options::ENABLE_STRIKETHROUGH);
    opts.insert(Options::ENABLE_TASKLISTS);

    let mut admonish_blocks = vec![];

    let events = Parser::new_ext(content, opts);
    for (e, span) in events.into_offset_iter() {
        if let Event::Start(Tag::CodeBlock(Fenced(info_string))) = e.clone() {
            let span_content = &content[span.start..span.end];
            let admonition = match parse_admonition(info_string.as_ref(), span_content, on_failure)
            {
                Some(admonition) => admonition,
                None => continue,
            };
            let admonition = admonition?;
            let anchor_id = unique_id_from_content(
                admonition.title.as_deref().unwrap_or(ANCHOR_ID_DEFAULT),
                &mut id_counter,
            );
            admonish_blocks.push((span, admonition.html(&anchor_id)));
        }
    }

    let mut content = content.to_string();
    for (span, block) in admonish_blocks.iter().rev() {
        let pre_content = &content[..span.start];
        let post_content = &content[span.end..];
        content = format!("{}\n{}{}", pre_content, block, post_content);
    }
    Ok(content)
}

#[cfg(test)]
mod test {
    use super::*;
    use pretty_assertions::assert_eq;

    fn prep(content: &str) -> String {
        preprocess(content, OnFailure::Continue).unwrap()
    }

    #[test]
    fn adds_admonish() {
        let content = r#"# Chapter
```admonish
A simple admonition.
```
Text
"#;

        let expected = r##"# Chapter

<div id="admonition-note" class="admonition note">
<div class="admonition-title">

Note

<a class="admonition-anchor-link" href="#admonition-note"></a>
</div>
<div>

A simple admonition.

</div>
</div>
Text
"##;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn adds_admonish_directive() {
        let content = r#"# Chapter
```admonish warning
A simple admonition.
```
Text
"#;

        let expected = r##"# Chapter

<div id="admonition-warning" class="admonition warning">
<div class="admonition-title">

Warning

<a class="admonition-anchor-link" href="#admonition-warning"></a>
</div>
<div>

A simple admonition.

</div>
</div>
Text
"##;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn adds_admonish_directive_title() {
        let content = r#"# Chapter
```admonish warning "Read **this**!"
A simple admonition.
```
Text
"#;

        let expected = r##"# Chapter

<div id="admonition-read-this" class="admonition warning">
<div class="admonition-title">

Read **this**!

<a class="admonition-anchor-link" href="#admonition-read-this"></a>
</div>
<div>

A simple admonition.

</div>
</div>
Text
"##;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn leaves_tables_untouched() {
        // Regression test.
        // Previously we forgot to enable the same markdwon extensions as mdbook itself.

        let content = r#"# Heading
| Head 1 | Head 2 |
|--------|--------|
| Row 1  | Row 2  |
"#;

        let expected = r#"# Heading
| Head 1 | Head 2 |
|--------|--------|
| Row 1  | Row 2  |
"#;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn leaves_html_untouched() {
        // Regression test.
        // Don't remove important newlines for syntax nested inside HTML

        let content = r#"# Heading
<del>
*foo*
</del>
"#;

        let expected = r#"# Heading
<del>
*foo*
</del>
"#;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn html_in_list() {
        // Regression test.
        // Don't remove important newlines for syntax nested inside HTML

        let content = r#"# Heading
1. paragraph 1
   ```
   code 1
   ```
2. paragraph 2
"#;

        let expected = r#"# Heading
1. paragraph 1
   ```
   code 1
   ```
2. paragraph 2
"#;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn info_string_that_changes_length_when_parsed() {
        let content = r#"
```admonish note "And \\"<i>in</i>\\" the title"
With <b>html</b> styling.
```
hello
"#;

        let expected = r##"

<div id="admonition-and-in-the-title" class="admonition note">
<div class="admonition-title">

And "<i>in</i>" the title

<a class="admonition-anchor-link" href="#admonition-and-in-the-title"></a>
</div>
<div>

With <b>html</b> styling.

</div>
</div>
hello
"##;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn info_string_ending_in_symbol() {
        let content = r#"
```admonish warning "Trademarkā„¢"
Should be respected
```
hello
"#;

        let expected = r##"

<div id="admonition-trademark" class="admonition warning">
<div class="admonition-title">

Trademarkā„¢

<a class="admonition-anchor-link" href="#admonition-trademark"></a>
</div>
<div>

Should be respected

</div>
</div>
hello
"##;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn block_with_additional_classname() {
        let content = r#"
```admonish tip.my-style.other-style
Will have bonus classnames
```
"#;

        let expected = r##"

<div id="admonition-tip" class="admonition tip my-style other-style">
<div class="admonition-title">

Tip

<a class="admonition-anchor-link" href="#admonition-tip"></a>
</div>
<div>

Will have bonus classnames

</div>
</div>
"##;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn block_with_additional_classname_and_title() {
        let content = r#"
```admonish tip.my-style.other-style "Developers don't want you to know this one weird tip!"
Will have bonus classnames
```
"#;

        let expected = r##"

<div id="admonition-developers-dont-want-you-to-know-this-one-weird-tip" class="admonition tip my-style other-style">
<div class="admonition-title">

Developers don't want you to know this one weird tip!

<a class="admonition-anchor-link" href="#admonition-developers-dont-want-you-to-know-this-one-weird-tip"></a>
</div>
<div>

Will have bonus classnames

</div>
</div>
"##;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn block_with_empty_additional_classnames_title_content() {
        let content = r#"
```admonish .... ""
```
"#;

        let expected = r##"

<div id="admonition-default" class="admonition note">
<div>



</div>
</div>
"##;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn unique_ids_same_title() {
        let content = r#"
```admonish note "My Note"
Content zero.
```

```admonish note "My Note"
Content one.
```
"#;

        let expected = r##"

<div id="admonition-my-note" class="admonition note">
<div class="admonition-title">

My Note

<a class="admonition-anchor-link" href="#admonition-my-note"></a>
</div>
<div>

Content zero.

</div>
</div>


<div id="admonition-my-note-1" class="admonition note">
<div class="admonition-title">

My Note

<a class="admonition-anchor-link" href="#admonition-my-note-1"></a>
</div>
<div>

Content one.

</div>
</div>
"##;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn v2_config_works() {
        let content = r#"
```admonish tip class="my other-style" title="Article Heading"
Bonus content!
```
"#;

        let expected = r##"

<div id="admonition-article-heading" class="admonition tip my other-style">
<div class="admonition-title">

Article Heading

<a class="admonition-anchor-link" href="#admonition-article-heading"></a>
</div>
<div>

Bonus content!

</div>
</div>
"##;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn continue_on_error_output() {
        let content = r#"
```admonish title="
Bonus content!
```
"#;

        let expected = r##"

<div id="admonition-error-rendering-admonishment" class="admonition bug">
<div class="admonition-title">

Error rendering admonishment

<a class="admonition-anchor-link" href="#admonition-error-rendering-admonishment"></a>
</div>
<div>

Failed with: TOML parsing error: unterminated string at line 1 column 7

Original markdown input:

``````
```admonish title="
Bonus content!
```
``````


</div>
</div>
"##;

        assert_eq!(expected, prep(content));
    }

    #[test]
    fn bail_on_error_output() {
        let content = r#"
```admonish title="
Bonus content!
```
"#;

        assert_eq!(
            preprocess(content, OnFailure::Bail)
                .unwrap_err()
                .to_string(),
            r#"Error processing admonition, bailing:
```admonish title="
Bonus content!
```"#
                .to_owned()
        )
    }

    #[test]
    fn block_collapsible() {
        let content = r#"
```admonish collapsible=true
Hidden
```
"#;

        let expected = r##"

<details id="admonition-note" class="admonition note">
<summary class="admonition-title">

Note

<a class="admonition-anchor-link" href="#admonition-note"></a>
</summary>
<div>

Hidden

</div>
</details>
"##;

        assert_eq!(expected, prep(content));
    }
}