Debian Codegraph @

src/plugins/syntect.rs

raw
1 //! Adapter for the Syntect syntax highlighter plugin.
2
3 use std::borrow::Cow;
4 use std::collections::{HashMap, hash_map};
5 use std::fmt::{self, Write};
6 use syntect::Error;
7 use syntect::easy::HighlightLines;
8 use syntect::highlighting::{Color, ThemeSet};
9 use syntect::html::{
10 ClassStyle, ClassedHTMLGenerator, IncludeBackground, append_highlighted_html_for_styled_line,
11 };
12 use syntect::parsing::{SyntaxReference, SyntaxSet};
13 use syntect::util::LinesWithEndings;
14
15 use crate::adapters::SyntaxHighlighterAdapter;
16 use crate::html;
17
18 #[derive(Debug)]
19 /// Syntect syntax highlighter plugin.
20 pub struct SyntectAdapter {
21 theme: Option<String>,
22 syntax_set: SyntaxSet,
23 theme_set: ThemeSet,
24 css_class_prefix: Option<&'static str>, // syntect::html::ClassStyle::SpacePrefixed requires prefix to be &'static str
25 }
26
27 impl SyntectAdapter {
28 /// Construct a new `SyntectAdapter` object and set the syntax highlighting theme.
29 /// If `None` is specified, apply CSS classes instead.
30 pub fn new(theme: Option<&str>) -> Self {
31 SyntectAdapter {
32 theme: theme.map(String::from),
33 syntax_set: SyntaxSet::load_defaults_newlines(),
34 theme_set: ThemeSet::load_defaults(),
35 css_class_prefix: None,
36 }
37 }
38
39 fn highlight_html(&self, code: &str, syntax: &SyntaxReference) -> Result<String, Error> {
40 match &self.theme {
41 Some(theme) => {
42 // syntect::html::highlighted_html_for_string, without the opening/closing <pre>.
43 let theme = &self.theme_set.themes[theme];
44 let mut highlighter = HighlightLines::new(syntax, theme);
45
46 let bg = theme.settings.background.unwrap_or(Color::WHITE);
47
48 let mut output = String::new();
49 for line in LinesWithEndings::from(code) {
50 let regions = highlighter.highlight_line(line, &self.syntax_set)?;
51 append_highlighted_html_for_styled_line(
52 &regions[..],
53 IncludeBackground::IfDifferent(bg),
54 &mut output,
55 )?;
56 }
57 Ok(output)
58 }
59 None => {
60 // fall back to HTML classes.
61 let class_style = match &self.css_class_prefix {
62 None => ClassStyle::Spaced,
63 Some(prefix) => ClassStyle::SpacedPrefixed { prefix },
64 };
65 let mut html_generator = ClassedHTMLGenerator::new_with_class_style(
66 syntax,
67 &self.syntax_set,
68 class_style,
69 );
70 for line in LinesWithEndings::from(code) {
71 html_generator.parse_html_for_line_which_includes_newline(line)?;
72 }
73 Ok(html_generator.finalize())
74 }
75 }
76 }
77 }
78
79 impl SyntaxHighlighterAdapter for SyntectAdapter {
80 fn write_highlighted(
81 &self,
82 output: &mut dyn Write,
83 lang: Option<&str>,
84 code: &str,
85 ) -> fmt::Result {
86 let fallback_syntax = "Plain Text";
87
88 let lang: &str = match lang {
89 Some(l) if !l.is_empty() => l.split_once(',').map(|(left, _)| left).unwrap_or(l),
90 _ => fallback_syntax,
91 };
92
93 let syntax = self
94 .syntax_set
95 .find_syntax_by_token(lang)
96 .unwrap_or_else(|| {
97 self.syntax_set
98 .find_syntax_by_first_line(code)
99 .unwrap_or_else(|| self.syntax_set.find_syntax_plain_text())
100 });
101
102 match self.highlight_html(code, syntax) {
103 Ok(highlighted_code) => output.write_str(&highlighted_code),
104 Err(_) => output.write_str(code),
105 }
106 }
107
108 fn write_pre_tag(
109 &self,
110 output: &mut dyn Write,
111 attributes: HashMap<&'static str, Cow<'_, str>>,
112 ) -> fmt::Result {
113 match &self.theme {
114 Some(theme) => {
115 let theme = &self.theme_set.themes[theme];
116 let colour = theme.settings.background.unwrap_or(Color::WHITE);
117
118 let style = format!(
119 "background-color:#{:02x}{:02x}{:02x};",
120 colour.r, colour.g, colour.b
121 );
122
123 let mut pre_attributes = SyntectPreAttributes::new(attributes, &style);
124 html::write_opening_tag(output, "pre", pre_attributes.iter_mut())
125 }
126 None => html::write_opening_tag(output, "pre", vec![("class", "syntax-highlighting")]),
127 }
128 }
129
130 fn write_code_tag(
131 &self,
132 output: &mut dyn Write,
133 attributes: HashMap<&'static str, Cow<'_, str>>,
134 ) -> fmt::Result {
135 html::write_opening_tag(output, "code", attributes)
136 }
137 }
138
139 struct SyntectPreAttributes<'s> {
140 syntect_style: String,
141 attributes: HashMap<&'static str, Cow<'s, str>>,
142 }
143
144 impl<'s> SyntectPreAttributes<'s> {
145 fn new(attributes: HashMap<&'static str, Cow<'s, str>>, syntect_style: &str) -> Self {
146 Self {
147 syntect_style: syntect_style.into(),
148 attributes,
149 }
150 }
151
152 fn iter_mut(&mut self) -> SyntectPreAttributesIter<'_, 's> {
153 SyntectPreAttributesIter {
154 iter_mut: self.attributes.iter_mut(),
155 syntect_style: &self.syntect_style,
156 style_written: false,
157 }
158 }
159 }
160
161 struct SyntectPreAttributesIter<'a, 's> {
162 iter_mut: hash_map::IterMut<'a, &'static str, Cow<'s, str>>,
163 syntect_style: &'a str,
164 style_written: bool,
165 }
166
167 impl<'a> Iterator for SyntectPreAttributesIter<'a, '_> {
168 type Item = (&'a str, &'a str);
169
170 fn next(&mut self) -> Option<Self::Item> {
171 match self.iter_mut.next() {
172 Some((k, v)) if *k == "style" && !self.style_written => {
173 self.style_written = true;
174 v.to_mut().insert_str(0, self.syntect_style);
175 Some((k, v))
176 }
177 Some((k, v)) => Some((k, v)),
178 None if !self.style_written => {
179 self.style_written = true;
180 Some(("style", self.syntect_style))
181 }
182 None => None,
183 }
184 }
185 }
186
187 #[derive(Debug, Default)]
188 /// A builder for [`SyntectAdapter`].
189 ///
190 /// Allows customization of `Theme`, [`ThemeSet`], and [`SyntaxSet`].
191 pub struct SyntectAdapterBuilder {
192 theme: Option<String>,
193 syntax_set: Option<SyntaxSet>,
194 theme_set: Option<ThemeSet>,
195 css_class_prefix: Option<&'static str>,
196 }
197
198 impl SyntectAdapterBuilder {
199 /// Create a new empty [`SyntectAdapterBuilder`].
200 pub fn new() -> Self {
201 Default::default()
202 }
203
204 /// Set the theme.
205 pub fn theme(mut self, s: &str) -> Self {
206 self.theme.replace(s.into());
207 self
208 }
209
210 /// Uses CSS classes instead of a Syntect theme.
211 pub fn css(mut self) -> Self {
212 self.theme = None;
213 self
214 }
215
216 /// Uses CSS classes with the specified prefix instead of a Syntect theme.
217 pub fn css_with_class_prefix(self, prefix: &'static str) -> Self {
218 let mut builder = self.css();
219 builder.css_class_prefix = Some(prefix);
220 builder
221 }
222
223 /// Set the syntax set.
224 pub fn syntax_set(mut self, s: SyntaxSet) -> Self {
225 self.syntax_set.replace(s);
226 self
227 }
228
229 /// Set the theme set.
230 pub fn theme_set(mut self, s: ThemeSet) -> Self {
231 self.theme_set.replace(s);
232 self
233 }
234
235 /// Builds the [`SyntectAdapter`]. Default values:
236 /// - `theme`: `None` (uses CSS classes)
237 /// - `syntax_set`: [`SyntaxSet::load_defaults_newlines()`]
238 /// - `theme_set`: [`ThemeSet::load_defaults()`]
239 pub fn build(self) -> SyntectAdapter {
240 SyntectAdapter {
241 theme: self.theme,
242 syntax_set: self
243 .syntax_set
244 .unwrap_or_else(SyntaxSet::load_defaults_newlines),
245 theme_set: self.theme_set.unwrap_or_else(ThemeSet::load_defaults),
246 css_class_prefix: self.css_class_prefix,
247 }
248 }
249 }