diff --git a/cot-site-macros/src/md_pages/rendering.rs b/cot-site-macros/src/md_pages/rendering.rs index d1b52a0..5199c4a 100644 --- a/cot-site-macros/src/md_pages/rendering.rs +++ b/cot-site-macros/src/md_pages/rendering.rs @@ -3,7 +3,7 @@ use std::fmt::Write; use comrak::html::{ ChildRendering, Context, format_document_with_formatter, format_node_default, render_sourcepos, }; -use comrak::nodes::{AstNode, NodeLink, NodeValue}; +use comrak::nodes::{AstNode, NodeCodeBlock, NodeLink, NodeValue}; use comrak::options::Plugins; use comrak::{Arena, Options, parse_document}; use cot_site_common::Version; @@ -47,10 +47,36 @@ fn format_node_custom<'a>( match node.data.borrow().value { NodeValue::Table(_) => render_table_custom(context, node, entering), NodeValue::Link(ref ln) => render_link_custom(context, node, entering, ln), + NodeValue::CodeBlock(ref cb) => render_code_block_custom(context, node, entering, cb), _ => format_node_default(context, node, entering), } } +fn render_code_block_custom<'a>( + context: &mut Context, + _node: &'a AstNode<'a>, + entering: bool, + cb: &NodeCodeBlock, +) -> Result { + let mut new_cb = cb.clone(); + new_cb.literal = remove_hidden_lines(&cb.literal); + + let node = AstNode::from(NodeValue::CodeBlock(Box::new(new_cb))); + + format_node_default(context, &node, entering) +} + +fn remove_hidden_lines(input: &str) -> String { + let mut literal = String::new(); + for line in input.lines() { + if !line.starts_with("# ") { + literal.push_str(line); + literal.push('\n'); + } + } + literal +} + fn render_table_custom<'a>( context: &mut Context, node: &'a AstNode<'a>, @@ -234,4 +260,18 @@ mod tests { ); test_resolve!("cot", "cot"); } + + #[test] + fn test_code_block_filtering() { + let md = "```rust\n# hidden\nvisible\n```"; + let mut options = Options::default(); + options.render.r#unsafe = true; + let plugins = Plugins::default(); + let version = Version::new(0, 5, 0); + + let html = markdown_to_html(md, &options, &plugins, version); + + assert!(html.contains("visible")); + assert!(!html.contains("hidden")); + } }