about summary refs log tree commit diff
path: root/tools/cheddar
diff options
context:
space:
mode:
authorVincent Ambo <tazjin@google.com>2019-12-21T16·18+0000
committerVincent Ambo <tazjin@google.com>2019-12-21T16·18+0000
commit03acae2f85a1cda6057ab17549941c2ce16464ed (patch)
tree2614c192d761cc33bf0eb3c29de67723a71a6f86 /tools/cheddar
parentf90495138483698c954620564d93e2c42a114c9f (diff)
feat(cheddar): Style pre-elements for better readability r/288
Uses GitHub-like styling for <pre> elements, i.e. slight padding and
background colour highlighting.
Diffstat (limited to 'tools/cheddar')
-rw-r--r--tools/cheddar/src/main.rs26
1 files changed, 22 insertions, 4 deletions
diff --git a/tools/cheddar/src/main.rs b/tools/cheddar/src/main.rs
index 67cd2f8bdfc0..eeb8bb6480ff 100644
--- a/tools/cheddar/src/main.rs
+++ b/tools/cheddar/src/main.rs
@@ -11,11 +11,11 @@ use syntect::dumps::from_binary;
 use syntect::easy::HighlightLines;
 use syntect::highlighting::ThemeSet;
 use syntect::parsing::{SyntaxSet, SyntaxReference};
+use syntect::util::LinesWithEndings;
 
 use syntect::html::{
     IncludeBackground,
     append_highlighted_html_for_styled_line,
-    highlighted_html_for_string,
     start_highlighted_html_snippet,
 };
 
@@ -42,6 +42,10 @@ lazy_static! {
     };
 }
 
+// HTML fragment used when rendering inline blocks in Markdown documents.
+// Emulates the GitHub style (subtle background hue and padding).
+const BLOCK_PRE: &str = "<pre style=\"background-color:#f6f8fa;padding:16px;\">\n";
+
 fn args_extension() -> Option<String> {
     // The name of the file to be formatted is usually passed in as
     // the first argument and can be used to determine a syntax set.
@@ -105,9 +109,23 @@ fn format_markdown() {
                     .unwrap_or_else(|| SYNTAXES.find_syntax_plain_text());
 
                 let code = String::from_utf8_lossy(&code_block.literal);
-                let rendered = highlighted_html_for_string(
-                    &code, &SYNTAXES, syntax, theme,
-                );
+
+                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(
+                            &regions[..], IncludeBackground::No, &mut buf,
+                        );
+                    }
+
+                    buf.push_str("</pre>");
+                    buf
+                };
 
                 let block = NodeHtmlBlock {
                     block_type: 1, // It's unclear what behaviour is toggled by this