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
//! Code fence
//!
//! ` ```lang ` or `~~~lang`
//!
//! <https://spec.commonmark.org/0.30/#code-fence>
use crate::{MarkdownIt, Node, NodeValue, Renderer};
use crate::parser::block::{BlockRule, BlockState};
use crate::common::utils::unescape_all;

#[derive(Debug)]
pub struct CodeFence {
    pub info: String,
    pub marker: char,
    pub marker_len: usize,
    pub content: String,
    pub lang_prefix: &'static str,
}

impl NodeValue for CodeFence {
    fn render(&self, node: &Node, fmt: &mut dyn Renderer) {
        let info = unescape_all(&self.info);
        let mut split = info.split_whitespace();
        let lang_name = split.next().unwrap_or("");
        let mut attrs = node.attrs.clone();
        let class;

        if !lang_name.is_empty() {
            class = format!("{}{}", self.lang_prefix, lang_name);
            attrs.push(("class", class));
        }

        fmt.cr();
        fmt.open("pre", &[]);
            fmt.open("code", &attrs);
            fmt.text(&self.content);
            fmt.close("code");
        fmt.close("pre");
        fmt.cr();
    }
}

#[derive(Debug, Default)]
struct FenceSettings(std::cell::Cell<&'static str>);

pub fn add(md: &mut MarkdownIt) {
    add_with_lang_prefix(md, "language-");
}

pub fn add_with_lang_prefix(md: &mut MarkdownIt, lang_prefix: &'static str) {
    md.block.add_rule::<FenceScanner>();
    md.env.get_or_insert_default::<FenceSettings>().0.set(lang_prefix);
}

#[doc(hidden)]
pub struct FenceScanner;
impl BlockRule for FenceScanner {
    fn run(state: &mut BlockState, silent: bool) -> bool {
        // if it's indented more than 3 spaces, it should be a code block
        if state.line_indent(state.line) >= 4 { return false; }

        let line = state.get_line(state.line);
        let mut chars = line.chars();

        let marker = if let Some(ch @ ('~' | '`')) = chars.next() {
            ch
        } else {
            return false;
        };

        // scan marker length
        let mut len = 1;
        while Some(marker) == chars.next() { len += 1; }

        if len < 3 { return false; }

        let params = &line[len..];

        if marker == '`' && params.contains(marker) { return false; }

        // Since start is found, we can report success here in validation mode
        if silent { return true; }

        let start_line = state.line;
        let mut next_line = state.line;
        let mut have_end_marker = false;

        // search end of block
        'outer: loop {
            next_line += 1;
            if next_line >= state.line_max {
                // unclosed block should be autoclosed by end of document.
                // also block seems to be autoclosed by end of parent
                break;
            }

            let line = state.get_line(next_line);

            if !line.is_empty() && state.line_indent(next_line) < 0 {
                // non-empty line with negative indent should stop the list:
                // - ```
                //  test
                break;
            }

            let mut chars = line.chars().peekable();

            if Some(marker) != chars.next() { continue; }

            if state.line_indent(next_line) >= 4 {
                // closing fence should be indented less than 4 spaces
                continue;
            }

            // scan marker length
            let mut len_end = 1;
            while Some(&marker) == chars.peek() {
                chars.next();
                len_end += 1;
            }

            // closing code fence must be at least as long as the opening one
            if len_end < len { continue; }

            // make sure tail has spaces only
            loop {
                match chars.next() {
                    Some(' ' | '\t') => {},
                    Some(_) => continue 'outer,
                    None => {
                        have_end_marker = true;
                        break 'outer;
                    }
                }
            }
        }

        // If a fence has heading spaces, they should be removed from its inner block
        let indent = state.line_offsets[start_line].indent_nonspace;
        let (content, _) = state.get_lines(start_line + 1, next_line, indent as usize, true);
        let params = params.to_owned();

        let lang_prefix = state.md.env.get::<FenceSettings>().unwrap().0.get();
        let mut node = Node::new(CodeFence {
            info: params,
            marker,
            marker_len: len,
            content,
            lang_prefix,
        });
        node.srcmap = state.get_map(start_line, next_line - if have_end_marker { 0 } else { 1 });
        state.node.children.push(node);

        state.line = next_line + if have_end_marker { 1 } else { 0 };

        true
    }
}