Skip to content

Commit 23f9d02

Browse files
committed
chore: Extract par of the syntax highlighting code
1 parent b33bf53 commit 23f9d02

File tree

1 file changed

+26
-20
lines changed

1 file changed

+26
-20
lines changed

crates/engarde/src/syntax.rs

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -66,32 +66,38 @@ impl Syntax {
6666
self.default_theme = Some(theme.into());
6767
}
6868

69+
70+
fn format_inline_theme(&self, code: &str, theme: &str, syntax: &SyntaxReference) -> String {
71+
let theme = &self.theme_set.themes[theme];
72+
73+
// Essentially the same as `syntect::html::highlighted_html_for_string`,
74+
// but adding <code> tags between the <pre> tags
75+
// See: https://docs.rs/syntect/5.0.0/src/syntect/html.rs.html#269
76+
let mut highlighter = HighlightLines::new(syntax, theme);
77+
let (mut output, bg) = start_highlighted_html_snippet(theme);
78+
output.push_str("<code>");
79+
80+
for line in LinesWithEndings::from(code) {
81+
let regions = highlighter.highlight_line(line, &self.syntax_set).unwrap();
82+
append_highlighted_html_for_styled_line(
83+
&regions[..],
84+
IncludeBackground::IfDifferent(bg),
85+
&mut output,
86+
)
87+
.unwrap();
88+
}
89+
90+
output.push_str("</code></pre>\n");
91+
output
92+
}
93+
6994
pub fn format(&self, code: &str, lang: Option<&str>, theme: Option<&str>) -> String {
7095
if let Some(theme) = theme.or_else(|| self.default_theme()) {
71-
let theme = &self.theme_set.themes[theme];
72-
7396
let syntax = lang
7497
.and_then(|l| self.syntax_set.find_syntax_by_token(l))
7598
.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text());
7699

77-
// Essentially the same as `syntect::html::highlighted_html_for_string`,
78-
// but adding <code> tags between the <pre> tags
79-
// See: https://docs.rs/syntect/5.0.0/src/syntect/html.rs.html#269
80-
let mut highlighter = HighlightLines::new(syntax, theme);
81-
let (mut output, bg) = start_highlighted_html_snippet(theme);
82-
output.push_str("<code>");
83-
84-
for line in LinesWithEndings::from(code) {
85-
let regions = highlighter.highlight_line(line, &self.syntax_set).unwrap();
86-
append_highlighted_html_for_styled_line(
87-
&regions[..],
88-
IncludeBackground::IfDifferent(bg),
89-
&mut output,
90-
)
91-
.unwrap();
92-
}
93-
output.push_str("</code></pre>\n");
94-
output
100+
self.format_inline_theme(code, theme, syntax)
95101
} else {
96102
crate::Raw::new().format(code, lang, theme)
97103
}

0 commit comments

Comments
 (0)