| 1 | //! Indented code block |
| 2 | //! |
| 3 | //! Parses anything indented with 4 spaces. |
| 4 | //! |
| 5 | //! <https://spec.commonmark.org/0.30/#indented-code-block> |
| 6 | use crate::parser::block::{BlockRule, BlockState}; |
| 7 | use crate::{MarkdownIt, Node, NodeValue, Renderer}; |
| 8 | |
| 9 | const CODE_INDENT: i32 = 4; |
| 10 | |
| 11 | #[derive(Debug)] |
| 12 | pub struct CodeBlock { |
| 13 | pub content: String, |
| 14 | } |
| 15 | |
| 16 | impl NodeValue for CodeBlock { |
| 17 | fn render(&self, node: &Node, fmt: &mut dyn Renderer) { |
| 18 | fmt.cr(); |
| 19 | fmt.open("pre", &[]); |
| 20 | fmt.open("code", &node.attrs); |
| 21 | fmt.text(&self.content); |
| 22 | fmt.close("code"); |
| 23 | fmt.close("pre"); |
| 24 | fmt.cr(); |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | pub fn add(md: &mut MarkdownIt) { |
| 29 | md.block.add_rule::<CodeScanner>(); |
| 30 | md.max_indent = CODE_INDENT; |
| 31 | } |
| 32 | |
| 33 | #[doc(hidden)] |
| 34 | pub struct CodeScanner; |
| 35 | impl BlockRule for CodeScanner { |
| 36 | fn check(_: &mut BlockState) -> Option<()> { |
| 37 | None |
| 38 | } |
| 39 | |
| 40 | fn run(state: &mut BlockState) -> Option<(Node, usize)> { |
| 41 | if state.line_indent(state.line) < CODE_INDENT { return None; } |
| 42 | |
| 43 | let mut next_line = state.line + 1; |
| 44 | let mut last = next_line; |
| 45 | |
| 46 | while next_line < state.line_max { |
| 47 | if state.is_empty(next_line) { |
| 48 | next_line += 1; |
| 49 | continue; |
| 50 | } |
| 51 | |
| 52 | if state.line_indent(next_line) >= CODE_INDENT { |
| 53 | next_line += 1; |
| 54 | last = next_line; |
| 55 | continue; |
| 56 | } |
| 57 | |
| 58 | break; |
| 59 | } |
| 60 | |
| 61 | let (mut content, _mapping) = state.get_lines(state.line, last, CODE_INDENT as usize + state.blk_indent, false); |
| 62 | content += "\n"; |
| 63 | |
| 64 | let node = Node::new(CodeBlock { content }); |
| 65 | //node.srcmap = state.get_map_from_offsets(mapping[0].1, state.line_offsets[last - 1].line_end); |
| 66 | |
| 67 | Some((node, last - state.line)) |
| 68 | } |
| 69 | } |