From 03acae2f85a1cda6057ab17549941c2ce16464ed Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Sat, 21 Dec 2019 16:18:26 +0000 Subject: feat(cheddar): Style pre-elements for better readability Uses GitHub-like styling for
 elements, i.e. slight padding and
background colour highlighting.
---
 tools/cheddar/src/main.rs | 26 ++++++++++++++++++++++----
 1 file changed, 22 insertions(+), 4 deletions(-)

(limited to 'tools')

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 = "
\n";
+
 fn args_extension() -> Option {
     // 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(
+                            ®ions[..], IncludeBackground::No, &mut buf,
+                        );
+                    }
+
+                    buf.push_str("
"); + buf + }; let block = NodeHtmlBlock { block_type: 1, // It's unclear what behaviour is toggled by this -- cgit 1.4.1