1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use liquid;
use liquid::Token::{self, Identifier};
use liquid::lexer::Element::{self, Expression, Tag, Raw};

use pulldown_cmark as cmark;

use error;

pub fn has_syntax_theme(_name: &str) -> error::Result<bool> {
    bail!("Themes are unsupported in this build.");
}

pub fn list_syntax_themes<'a>() -> Vec<&'a String> {
    vec![]
}

pub fn list_syntaxes() -> Vec<String> {
    vec![]
}

// The code is taken from Liquid which was adapted from
// https://github.com/rust-lang/rust/blob/master/src/librustdoc/html/escape.rs
// Retrieved 2016-11-19.
fn html_escape(input: &str) -> String {
    let mut result = String::new();
    let mut last = 0;
    let mut skip = 0;
    for (i, c) in input.chars().enumerate() {
        if skip > 0 {
            skip -= 1;
            continue;
        }
        let c: char = c;
        match c {
            '<' | '>' | '\'' | '"' | '&' => {
                result.push_str(&input[last..i]);
                last = i + 1;
                let escaped = match c {
                    '<' => "&lt;",
                    '>' => "&gt;",
                    '\'' => "&#39;",
                    '"' => "&quot;",
                    '&' => "&amp;",
                    _ => unreachable!(),
                };
                result.push_str(escaped);
            }
            _ => {}
        }
    }
    if last < input.len() {
        result.push_str(&input[last..]);
    }
    result
}

struct CodeBlock {
    lang: Option<String>,
    code: String,
}

impl liquid::Renderable for CodeBlock {
    fn render(&self, _: &mut liquid::Context) -> Result<Option<String>, liquid::Error> {
        if let Some(ref lang) = self.lang {
            Ok(Some(format!("<pre><code class=\"language-{}\">{}</code></pre>",
                            lang,
                            self.code)))
        } else {
            Ok(Some(format!("<pre><code>{}</code></pre>", self.code)))
        }
    }
}

#[derive(Clone)]
pub struct CodeBlockParser {}

impl CodeBlockParser {
    pub fn new(_syntax_theme: String) -> Self {
        Self {}
    }
}

impl liquid::ParseBlock for CodeBlockParser {
    fn parse(&self,
             _tag_name: &str,
             arguments: &[Token],
             tokens: &[Element],
             _options: &liquid::LiquidOptions)
             -> Result<Box<liquid::Renderable>, liquid::Error> {
        let content = tokens.iter().fold("".to_owned(), |a, b| {
            match *b {
                Expression(_, ref text) |
                Tag(_, ref text) |
                Raw(ref text) => text,
            }.to_owned() + &a
        });

        let lang = match arguments.iter().next() {
            Some(&Identifier(ref x)) => Some(x.clone()),
            _ => None,
        };

        let content = html_escape(&content);

        Ok(Box::new(CodeBlock {
                        lang: lang,
                        code: content,
                    }))
    }
}

pub type DecoratedParser<'a> = cmark::Parser<'a>;

pub fn decorate_markdown<'a>(parser: cmark::Parser<'a>, _theme_name: &str) -> DecoratedParser<'a> {
    parser
}

#[cfg(test)]
mod test {

    use std::default::Default;
    use liquid::{self, Renderable, LiquidOptions, Context};

    use super::*;

    const CODE_BLOCK: &'static str = "mod test {
        fn hello(arg: int) -> bool {
            \
                                      true
        }
    }
";

    const CODEBLOCK_RENDERED: &'static str = r#"<pre><code class="language-rust">mod test {
        fn hello(arg: int) -&gt; bool {
            true
        }
    }
</code></pre>"#;

    #[test]
    fn codeblock_renders_rust() {
        let mut options: LiquidOptions = Default::default();
        options.blocks.insert("codeblock".to_string(),
                              Box::new(CodeBlockParser::new("base16-ocean.dark".to_owned())));
        let template = liquid::parse(&format!("{{% codeblock rust %}}{}{{% endcodeblock %}}",
                                              CODE_BLOCK),
                                     options)
            .unwrap();
        let mut data = Context::new();
        let output = template.render(&mut data);
        assert_eq!(output.unwrap(), Some(CODEBLOCK_RENDERED.to_string()));
    }

    const MARKDOWN_RENDERED: &'static str = r#"<pre><code class="language-rust">mod test {
        fn hello(arg: int) -&gt; bool {
            true
        }
    }

</code></pre>
"#;

    #[test]
    fn decorate_markdown_renders_rust() {
        let html = format!(
            "```rust
{}
```",
            CODE_BLOCK
        );

        let mut buf = String::new();
        let parser = cmark::Parser::new(&html);
        cmark::html::push_html(&mut buf, decorate_markdown(parser, "base16-ocean.dark"));
        assert_eq!(buf, MARKDOWN_RENDERED);
    }
}