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
use crate::{utils::config::CarbonHTML, CarbonError, Config};
use carbon_dump::{SYNTAX_SET, THEME_SET};
use lazy_static::lazy_static;
use std::ops::Deref;
use syntect::{
dumps::from_binary,
easy::HighlightLines,
highlighting::{Color, Style, ThemeSet},
html::{highlighted_html_for_file, highlighted_html_for_string},
parsing::SyntaxSet,
util::{as_24_bit_terminal_escaped, as_latex_escaped, LinesWithEndings},
};
impl Config {
pub fn render_terminal(&self, input: &str) -> Result<String, CarbonError> {
let set = SYNTAX_SET.deref();
let syntax = set.find_syntax_by_extension(&self.syntax).ok_or(CarbonError::no_theme(self))?;
let theme = THEME_SET.themes.get(&self.theme).ok_or(CarbonError::no_theme(self))?;
let mut h = HighlightLines::new(syntax, theme);
let mut out = String::with_capacity(2 * input.len());
for line in LinesWithEndings::from(input) {
let ranges: Vec<(Style, &str)> = h.highlight(line, set);
let escaped = as_24_bit_terminal_escaped(&ranges[..], true);
out.push_str(&escaped)
}
return Ok(out);
}
pub fn render_latex(&self, input: &str) -> Result<String, CarbonError> {
let set = SYNTAX_SET.deref();
let syntax = set.find_syntax_by_extension(&self.syntax).ok_or(CarbonError::no_theme(self))?;
let theme = THEME_SET.themes.get(&self.theme).ok_or(CarbonError::no_theme(self))?;
let mut h = HighlightLines::new(syntax, theme);
let mut out = String::with_capacity(10 * input.len());
for line in LinesWithEndings::from(input) {
let ranges: Vec<(Style, &str)> = h.highlight(line, set);
let escaped = as_latex_escaped(&ranges[..]);
out.push_str(&escaped);
out.push_str("\n\n")
}
return Ok(out);
}
pub fn render_html(&self, input: &str) -> Result<String, CarbonError> {
let all = SYNTAX_SET.deref();
let syntax = all.find_syntax_by_extension(&self.syntax).ok_or(CarbonError::no_theme(self))?;
let theme = THEME_SET.themes.get(&self.theme).ok_or(CarbonError::no_theme(self))?;
let mut out = String::with_capacity(25 * input.len());
let c = theme.settings.background.unwrap_or(Color::WHITE);
match self.html_type {
CarbonHTML::Raw => {
out.push_str(&format!(
"<div class=\"carbon\" style=\"background-color:#{:02x}{:02x}{:02x};\">\n",
c.r, c.g, c.b
));
out.push_str(&highlighted_html_for_string(input, all, syntax, theme));
out.push_str(&format!("</div>"));
}
CarbonHTML::Full => {
out.push_str(&format!("<head><style>pre{{{}}}</style></head>", self.html_font));
out.push_str(&format!("<body style=\"background-color:#{:02x}{:02x}{:02x};\">\n", c.r, c.g, c.b));
out.push_str(&format!("{}", highlighted_html_for_string(input, all, syntax, theme)));
out.push_str(&format!("</body>"));
}
};
return Ok(out);
}
}