Debian Codegraph @

helix-term/src/ui/markdown.rs

raw symbols SCIP
1 use crate::compositor::{Component, Context};
2 use arc_swap::ArcSwap;
3 use tui::{
4 buffer::Buffer as Surface,
5 text::{Span, Spans, Text},
6 };
7
8 use std::sync::Arc;
9
10 use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
11
12 use helix_core::{
13 syntax::{self, HighlightEvent, OverlayHighlights},
14 RopeSlice, Syntax,
15 };
16 use helix_view::{
17 graphics::{Margin, Rect, Style},
18 theme::Modifier,
19 Theme,
20 };
21
22 fn styled_multiline_text<'a>(text: &str, style: Style) -> Text<'a> {
23 let spans: Vec<_> = text
24 .lines()
25 .map(|line| Span::styled(line.to_string(), style))
26 .map(Spans::from)
27 .collect();
28 Text::from(spans)
29 }
30
31 pub fn highlighted_code_block<'a>(
32 text: &str,
33 language: &str,
34 theme: Option<&Theme>,
35 loader: &syntax::Loader,
36 // Optional overlay highlights to mix in with the syntax highlights.
37 //
38 // Note that `OverlayHighlights` is typically used with char indexing but the only caller
39 // which passes this parameter currently passes **byte indices** instead.
40 additional_highlight_spans: Option<OverlayHighlights>,
41 ) -> Text<'a> {
42 let mut spans = Vec::new();
43 let mut lines = Vec::new();
44
45 let get_theme = |key: &str| -> Style { theme.map(|t| t.get(key)).unwrap_or_default() };
46 let text_style = get_theme(Markdown::TEXT_STYLE);
47 let code_style = get_theme(Markdown::BLOCK_STYLE);
48
49 let theme = match theme {
50 Some(t) => t,
51 None => return styled_multiline_text(text, code_style),
52 };
53
54 let ropeslice = RopeSlice::from(text);
55 let Some(syntax) = loader
56 .language_for_match(RopeSlice::from(language))
57 .and_then(|lang| Syntax::new(ropeslice, lang, loader).ok())
58 else {
59 return styled_multiline_text(text, code_style);
60 };
61
62 let mut syntax_highlighter = syntax.highlighter(ropeslice, loader, ..);
63 let mut syntax_highlight_stack = Vec::new();
64 let mut overlay_highlight_stack = Vec::new();
65 let mut overlay_highlighter = syntax::OverlayHighlighter::new(additional_highlight_spans);
66 let mut pos = 0;
67
68 while pos < ropeslice.len_bytes() as u32 {
69 if pos == syntax_highlighter.next_event_offset() {
70 let (event, new_highlights) = syntax_highlighter.advance();
71 if event == HighlightEvent::Refresh {
72 syntax_highlight_stack.clear();
73 }
74 syntax_highlight_stack.extend(new_highlights);
75 } else if pos == overlay_highlighter.next_event_offset() as u32 {
76 let (event, new_highlights) = overlay_highlighter.advance();
77 if event == HighlightEvent::Refresh {
78 overlay_highlight_stack.clear();
79 }
80 overlay_highlight_stack.extend(new_highlights)
81 }
82
83 let start = pos;
84 pos = syntax_highlighter
85 .next_event_offset()
86 .min(overlay_highlighter.next_event_offset() as u32);
87 if pos == u32::MAX {
88 pos = ropeslice.len_bytes() as u32;
89 }
90 if pos == start {
91 continue;
92 }
93 // The highlighter should always move forward.
94 // If the highlighter malfunctions, bail on syntax highlighting and log an error.
95 debug_assert!(pos > start);
96 if pos < start {
97 log::error!("Failed to highlight '{language}': {text:?}");
98 return styled_multiline_text(text, code_style);
99 }
100
101 let style = syntax_highlight_stack
102 .iter()
103 .chain(overlay_highlight_stack.iter())
104 .fold(text_style, |acc, highlight| {
105 acc.patch(theme.highlight(*highlight))
106 });
107
108 let mut slice = &text[start as usize..pos as usize];
109 // TODO: do we need to handle all unicode line endings
110 // here, or is just '\n' okay?
111 while let Some(end) = slice.find('\n') {
112 // emit span up to newline
113 let text = &slice[..end];
114 let text = text.replace('\t', " "); // replace tabs
115 let span = Span::styled(text, style);
116 spans.push(span);
117
118 // truncate slice to after newline
119 slice = &slice[end + 1..];
120
121 // make a new line
122 let spans = std::mem::take(&mut spans);
123 lines.push(Spans::from(spans));
124 }
125
126 if !slice.is_empty() {
127 let span = Span::styled(slice.replace('\t', " "), style);
128 spans.push(span);
129 }
130 }
131
132 if !spans.is_empty() {
133 let spans = std::mem::take(&mut spans);
134 lines.push(Spans::from(spans));
135 }
136
137 Text::from(lines)
138 }
139
140 pub struct Markdown {
141 contents: String,
142
143 config_loader: Arc<ArcSwap<syntax::Loader>>,
144 }
145
146 // TODO: pre-render and self reference via Pin
147 // better yet, just use Tendril + subtendril for references
148
149 impl Markdown {
150 const TEXT_STYLE: &'static str = "ui.text";
151 const BLOCK_STYLE: &'static str = "markup.raw.inline";
152 const RULE_STYLE: &'static str = "punctuation.special";
153 const UNNUMBERED_LIST_STYLE: &'static str = "markup.list.unnumbered";
154 const NUMBERED_LIST_STYLE: &'static str = "markup.list.numbered";
155 const HEADING_STYLES: [&'static str; 6] = [
156 "markup.heading.1",
157 "markup.heading.2",
158 "markup.heading.3",
159 "markup.heading.4",
160 "markup.heading.5",
161 "markup.heading.6",
162 ];
163 const INDENT: &'static str = " ";
164
165 pub fn new(contents: String, config_loader: Arc<ArcSwap<syntax::Loader>>) -> Self {
166 Self {
167 contents,
168 config_loader,
169 }
170 }
171
172 pub fn parse(&self, theme: Option<&Theme>) -> tui::text::Text<'_> {
173 fn push_line<'a>(spans: &mut Vec<Span<'a>>, lines: &mut Vec<Spans<'a>>) {
174 let spans = std::mem::take(spans);
175 if !spans.is_empty() {
176 lines.push(Spans::from(spans));
177 }
178 }
179
180 let mut options = Options::empty();
181 options.insert(Options::ENABLE_STRIKETHROUGH);
182 let parser = Parser::new_ext(&self.contents, options);
183
184 // TODO: if possible, render links as terminal hyperlinks: https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
185 let mut tags = Vec::new();
186 let mut spans = Vec::new();
187 let mut lines = Vec::new();
188 let mut list_stack = Vec::new();
189
190 let get_indent = |level: usize| {
191 if level < 1 {
192 String::new()
193 } else {
194 Self::INDENT.repeat(level - 1)
195 }
196 };
197
198 let get_theme = |key: &str| -> Style { theme.map(|t| t.get(key)).unwrap_or_default() };
199 let text_style = get_theme(Self::TEXT_STYLE);
200 let code_style = get_theme(Self::BLOCK_STYLE);
201 let numbered_list_style = get_theme(Self::NUMBERED_LIST_STYLE);
202 let unnumbered_list_style = get_theme(Self::UNNUMBERED_LIST_STYLE);
203 let rule_style = get_theme(Self::RULE_STYLE);
204 let heading_styles: Vec<Style> = Self::HEADING_STYLES
205 .iter()
206 .map(|key| get_theme(key))
207 .collect();
208
209 // Transform text in `<code>` blocks into `Event::Code`
210 let mut in_code = false;
211 let parser = parser.filter_map(|event| match event {
212 Event::Html(tag)
213 if tag.starts_with("<code") && matches!(tag.chars().nth(5), Some(' ' | '>')) =>
214 {
215 in_code = true;
216 None
217 }
218 Event::Html(tag) if *tag == *"</code>" => {
219 in_code = false;
220 None
221 }
222 Event::Text(text) if in_code => Some(Event::Code(text)),
223 _ => Some(event),
224 });
225
226 for event in parser {
227 match event {
228 Event::Start(Tag::List(list)) => {
229 // if the list stack is not empty this is a sub list, in that
230 // case we need to push the current line before proceeding
231 if !list_stack.is_empty() {
232 push_line(&mut spans, &mut lines);
233 }
234
235 list_stack.push(list);
236 }
237 Event::End(TagEnd::List(_)) => {
238 list_stack.pop();
239
240 // whenever top-level list closes, empty line
241 if list_stack.is_empty() {
242 lines.push(Spans::default());
243 }
244 }
245 Event::Start(Tag::Item) => {
246 if list_stack.is_empty() {
247 log::warn!("markdown parsing error, list item without list");
248 }
249
250 tags.push(Tag::Item);
251
252 // get the appropriate bullet for the current list
253 let (bullet, bullet_style) = list_stack
254 .last()
255 .unwrap_or(&None) // use the '- ' bullet in case the list stack would be empty
256 .map_or((String::from("• "), unnumbered_list_style), |number| {
257 (format!("{}. ", number), numbered_list_style)
258 });
259
260 // increment the current list number if there is one
261 if let Some(v) = list_stack.last_mut().unwrap_or(&mut None).as_mut() {
262 *v += 1;
263 }
264
265 let prefix = get_indent(list_stack.len()) + bullet.as_str();
266 spans.push(Span::styled(prefix, bullet_style));
267 }
268 Event::Start(tag) => {
269 tags.push(tag);
270 if spans.is_empty() && !list_stack.is_empty() {
271 // TODO: could push indent + 2 or 3 spaces to align with
272 // the rest of the list.
273 spans.push(Span::from(get_indent(list_stack.len())));
274 }
275 }
276 Event::End(tag) => {
277 tags.pop();
278 match tag {
279 TagEnd::Heading(_)
280 | TagEnd::Paragraph
281 | TagEnd::CodeBlock
282 | TagEnd::Item => {
283 push_line(&mut spans, &mut lines);
284 }
285 _ => (),
286 }
287
288 // whenever heading, code block or paragraph closes, empty line
289 match tag {
290 TagEnd::Heading(_) | TagEnd::Paragraph | TagEnd::CodeBlock => {
291 lines.push(Spans::default());
292 }
293 _ => (),
294 }
295 }
296 Event::Text(text) => {
297 if let Some(Tag::CodeBlock(kind)) = tags.last() {
298 let language = match kind {
299 CodeBlockKind::Fenced(language) => language,
300 CodeBlockKind::Indented => "",
301 };
302 let tui_text = highlighted_code_block(
303 &text,
304 language,
305 theme,
306 &self.config_loader.load(),
307 None,
308 );
309 lines.extend(tui_text.lines);
310 } else {
311 let style = match tags.last() {
312 Some(Tag::Heading { level, .. }) => match level {
313 HeadingLevel::H1 => heading_styles[0],
314 HeadingLevel::H2 => heading_styles[1],
315 HeadingLevel::H3 => heading_styles[2],
316 HeadingLevel::H4 => heading_styles[3],
317 HeadingLevel::H5 => heading_styles[4],
318 HeadingLevel::H6 => heading_styles[5],
319 },
320 Some(Tag::Emphasis) => text_style.add_modifier(Modifier::ITALIC),
321 Some(Tag::Strong) => text_style.add_modifier(Modifier::BOLD),
322 Some(Tag::Strikethrough) => {
323 text_style.add_modifier(Modifier::CROSSED_OUT)
324 }
325 _ => text_style,
326 };
327 spans.push(Span::styled(text, style));
328 }
329 }
330 Event::Code(text) | Event::Html(text) => {
331 spans.push(Span::styled(text, code_style));
332 }
333 Event::SoftBreak | Event::HardBreak => {
334 push_line(&mut spans, &mut lines);
335 if !list_stack.is_empty() {
336 // TODO: could push indent + 2 or 3 spaces to align with
337 // the rest of the list.
338 spans.push(Span::from(get_indent(list_stack.len())));
339 }
340 }
341 Event::Rule => {
342 lines.push(Spans::from(Span::styled("───", rule_style)));
343 lines.push(Spans::default());
344 }
345 // TaskListMarker(bool) true if checked
346 _ => {
347 log::warn!("unhandled markdown event {:?}", event);
348 }
349 }
350 // build up a vec of Paragraph tui widgets
351 }
352
353 if !spans.is_empty() {
354 lines.push(Spans::from(spans));
355 }
356
357 // if last line is empty, remove it
358 if let Some(line) = lines.last() {
359 if line.0.is_empty() {
360 lines.pop();
361 }
362 }
363
364 Text::from(lines)
365 }
366 }
367
368 impl Component for Markdown {
369 fn render(&mut self, area: Rect, surface: &mut Surface, cx: &mut Context) {
370 use tui::widgets::{Paragraph, Widget, Wrap};
371
372 let text = self.parse(Some(&cx.editor.theme));
373
374 let par = Paragraph::new(&text)
375 .wrap(Wrap { trim: false })
376 .scroll((cx.scroll.unwrap_or_default() as u16, 0));
377
378 let margin = Margin::all(1);
379 par.render(area.inner(margin), surface);
380 }
381
382 fn required_size(&mut self, viewport: (u16, u16)) -> Option<(u16, u16)> {
383 let padding = 2;
384 let contents = self.parse(None);
385
386 // TODO: account for tab width
387 let max_text_width = (viewport.0.saturating_sub(padding)).min(120);
388 let (width, height) = crate::ui::text::required_size(&contents, max_text_width);
389
390 Some((width + padding, height + padding))
391 }
392 }