//! This file implements the rendering logic of cheddar with public //! functions for syntax-highlighting code and for turning Markdown //! into HTML with TVL extensions. use comrak::arena_tree::Node; use comrak::nodes::{Ast, AstNode, NodeCodeBlock, NodeHtmlBlock, NodeValue}; use comrak::{format_html, parse_document, Arena, ComrakOptions}; use lazy_static::lazy_static; use std::cell::RefCell; use std::collections::HashMap; use std::env; use std::ffi::OsStr; use std::io; use std::io::BufRead; use std::io::Write; use std::path::Path; use syntect::dumps::from_binary; use syntect::easy::HighlightLines; use syntect::highlighting::{Theme, ThemeSet}; use syntect::parsing::{SyntaxReference, SyntaxSet}; use syntect::util::LinesWithEndings; use syntect::html::{ append_highlighted_html_for_styled_line, start_highlighted_html_snippet, IncludeBackground, }; #[cfg(test)] mod tests; lazy_static! { // Load syntaxes lazily. Initialisation might not be required in // the case of Markdown rendering (if there's no code blocks // within the document). // // Note that the syntax set is included from the path pointed to // by the BAT_SYNTAXES environment variable at compile time. This // variable is populated by Nix and points to TVL's syntax set. static ref SYNTAXES: SyntaxSet = from_binary(include_bytes!(env!("BAT_SYNTAXES"))); pub static ref THEMES: ThemeSet = ThemeSet::load_defaults(); // Configure Comrak's Markdown rendering with all the bells & // whistles! static ref MD_OPTS: ComrakOptions = { let mut options = ComrakOptions::default(); // Enable non-standard Markdown features: options.extension.strikethrough = true; options.extension.tagfilter = true; options.extension.table = true; options.extension.autolink = true; options.extension.tasklist = true; options.extension.header_ids = Some(String::new()); // yyeeesss! options.extension.footnotes = true; options.extension.description_lists = true; options.extension.front_matter_delimiter = Some("---".to_owned()); // Required for tagfilter options.render.unsafe_ = true; options }; // Configures a map of specific filenames to languages, for cases // where the detection by extension or other heuristics fails. static ref FILENAME_OVERRIDES: HashMap<&'static str, &'static str> = { let mut map = HashMap::new(); // rules.pl is the canonical name of the submit rule file in // Gerrit, which is written in Prolog. map.insert("rules.pl", "Prolog"); map }; } // HTML fragment used when rendering inline blocks in Markdown documents. // Emulates the GitHub style (subtle background hue and padding). const BLOCK_PRE: &str = "
\n"; fn should_continue(res: &io::Result"); buf }; let mut block = NodeHtmlBlock::default(); block.literal = rendered.into_bytes(); NodeValue::HtmlBlock(block) } // Supported callout elements (which each have their own distinct rendering): enum Callout { Todo, Warning, Question, Tip, } // Determine whether the first child of the supplied node contains a text that // should cause a callout section to be rendered. fn has_callout<'a>(node: &Node<'a, RefCell) -> bool { match *res { Ok(n) => n > 0, Err(_) => false, } } // This function is taken from the Comrak documentation. fn iter_nodes<'a, F>(node: &'a AstNode<'a>, f: &F) where F: Fn(&'a AstNode<'a>), { f(node); for c in node.children() { iter_nodes(c, f); } } // Many of the syntaxes in the syntax list have random capitalisations, which // means that name matching for the block info of a code block in HTML fails. // // Instead, try finding a syntax match by comparing case insensitively (for // ASCII characters, anyways). fn find_syntax_case_insensitive(info: &str) -> Option<&'static SyntaxReference> { // TODO(tazjin): memoize this lookup SYNTAXES .syntaxes() .iter() .rev() .find(|&s| info.eq_ignore_ascii_case(&s.name)) } // Replaces code-block inside of a Markdown AST with HTML blocks rendered by // syntect. This enables static (i.e. no JavaScript) syntax highlighting, even // of complex languages. fn highlight_code_block(code_block: &NodeCodeBlock) -> NodeValue { let theme = &THEMES.themes["InspiredGitHub"]; let info = String::from_utf8_lossy(&code_block.info); let syntax = find_syntax_case_insensitive(&info) .or_else(|| SYNTAXES.find_syntax_by_extension(&info)) .unwrap_or_else(|| SYNTAXES.find_syntax_plain_text()); let code = String::from_utf8_lossy(&code_block.literal); let rendered = { // Write the block preamble manually to get exactly the // desired layout: let mut hl = HighlightLines::new(syntax, theme); let mut buf = BLOCK_PRE.to_string(); for line in LinesWithEndings::from(&code) { let regions = hl.highlight(line, &SYNTAXES); append_highlighted_html_for_styled_line(®ions[..], IncludeBackground::No, &mut buf); } buf.push_str("
", class).into_bytes();
NodeValue::HtmlBlock(block)
}
pub fn format_markdown