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
use pulldown_cmark::{html, CodeBlockKind, CowStr, Event, Options, Parser, Tag};
use syntect::highlighting::ThemeSet;
use syntect::html::highlighted_html_for_string;
use syntect::parsing::SyntaxSet;

use crate::config_handler::Config;
use crate::content_processor::katex;
use crate::debug_print::dprintln;

/// Processes markdown
///
/// Processes markdown with syntax highlighting and katex
/// doesn't include css
pub(crate) fn process_md(markdown_input: &str) -> String {
    let mut options = Options::all();
    options.set(Options::ENABLE_SMART_PUNCTUATION, false);

    // Vars for KaTeX processing
    let mut in_math_block = false;
    let mut katex_code = String::new();

    // Vars for syntax hl
    let theme_set = ThemeSet::load_defaults();
    let syntax_set = SyntaxSet::load_defaults_newlines();

    let mut in_code_block = false;
    let mut syntax = syntax_set.find_syntax_by_name("Rust").unwrap();
    let mut code = String::new();

    let parser = Parser::new_ext(markdown_input, options)
        // Compile KaTex
        .map(|event| {
            if !Config::global().compile_katex {
                return event;
            } // if KaTeX disabled, return straight away
            match &event {
                Event::Start(Tag::CodeBlock(language)) => {
                    if language == &CodeBlockKind::Fenced(CowStr::from("math")) {
                        dprintln!("Processing a katex block");
                        in_math_block = true;
                        katex_code = "".to_string();
                        return Event::Html(CowStr::from("<div class=\"math\">"));
                    }
                    event
                }
                Event::End(Tag::CodeBlock(_language)) => {
                    if in_math_block {
                        let mut out_html;
                        in_math_block = false;

                        out_html = if let Ok(processed_katex) =
                            katex::process_katex(katex_code.as_str())
                        {
                            processed_katex
                        } else {
                            String::new()
                        };
                        out_html.push_str("</div>");
                        return Event::Html(CowStr::from(out_html));
                    }
                    event
                }
                Event::Text(text) => {
                    if in_math_block {
                        katex_code += text;
                        return Event::Text(CowStr::from(""));
                    }
                    event
                }
                _ => event,
            }
        })
        // Do syntax highlighting
        .map(|event| {
            if !Config::global().highlight_code {
                return event;
            } // if highlighting disabled, return straight away
            match &event {
                Event::Start(Tag::CodeBlock(language)) => {
                    if language == &CodeBlockKind::Fenced(CowStr::from("math")) {
                        panic!("this shouldn't happen")
                    }
                    if let CodeBlockKind::Fenced(lang_name) = language {
                        if let Some(syntax_from_name) = syntax_set.find_syntax_by_name(&lang_name) {
                            dprintln!("Processing a fenced codeblock - highlighting enabled");
                            in_code_block = true;
                            code = "".to_string();

                            syntax = syntax_from_name;
                            return Event::Html(CowStr::from("<div class=\"code\"><pre><code>"));
                        }
                    }
                    event
                }
                Event::End(Tag::CodeBlock(_language)) => {
                    if in_code_block {
                        in_code_block = false;

                        let mut out_html = highlighted_html_for_string(
                            code.as_str(),
                            &syntax_set,
                            syntax,
                            &theme_set.themes[&Config::global().hl_theme],
                        );

                        out_html.push_str("</div></code></pre>");

                        return Event::Html(CowStr::from(out_html));
                    }
                    event
                }
                Event::Text(text) => {
                    if in_code_block {
                        code += text;
                        return Event::Text(CowStr::from(""));
                    }
                    event
                }
                _ => event,
            }
        });

    let mut output_html = String::new();
    html::push_html(&mut output_html, parser);
    return output_html;
}

// Use with --nocapture to see highlighted output
// fails due to global config not being initialized for tests rn
#[test]
fn test_highlighting() {
    let example = r#"
# Ree
```math
\relax{x} = \int_{-\infty}^\infty
    \hat\xi\,e^{2 \pi i \xi x}
    \,d\xi
```
```Rust
pub(crate) fn process_md(markdown_input: &str) -> String {
    let mut options = Options::all();
    options.set(Options::ENABLE_SMART_PUNCTUATION, false);

    let parser = Parser::new_ext(markdown_input, options);
    let mut output_html = String::new();
    html::push_html(&mut output_html, parser);
    return output_html
}
```
    "#;
    println!("{}", process_md(example));
}