mdbook_plugin_utils/markdown/
code_block.rs

1use anyhow::Result;
2use pulldown_cmark::{CodeBlockKind, Event, Tag, TagEnd};
3
4use crate::markdown::block::{Block, parse_blocks};
5
6fn is_code_block_start<IsTagsFn>(is_tags: IsTagsFn) -> Box<dyn Fn(&Event) -> bool>
7where
8    IsTagsFn: Fn(Vec<String>) -> bool + 'static,
9{
10    Box::new(move |event: &Event| match event {
11        Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(tag))) => {
12            let tags = tag
13                .split(',')
14                .map(|tag| tag.trim().to_lowercase())
15                .collect::<Vec<_>>();
16
17            is_tags(tags)
18        }
19        _ => false,
20    })
21}
22
23fn is_code_block_end(event: &Event) -> bool {
24    matches!(event, Event::End(TagEnd::CodeBlock))
25}
26
27pub fn parse_code_blocks<IsTagsFn>(content: &str, is_tags: IsTagsFn) -> Result<Vec<Block>>
28where
29    IsTagsFn: Fn(Vec<String>) -> bool + 'static,
30{
31    parse_blocks(
32        content,
33        is_code_block_start(is_tags),
34        is_code_block_end,
35        false,
36    )
37}