1pub mod parser;
2mod path_range;
3
4use base64::Engine as _;
5use futures::FutureExt as _;
6use gpui::HitboxBehavior;
7use language::LanguageName;
8use log::Level;
9pub use path_range::{LineCol, PathWithRange};
10
11use std::borrow::Cow;
12use std::collections::HashMap;
13use std::collections::HashSet;
14use std::iter;
15use std::mem;
16use std::ops::Range;
17use std::path::Path;
18use std::rc::Rc;
19use std::sync::Arc;
20use std::time::Duration;
21
22use gpui::{
23 AnyElement, App, BorderStyle, Bounds, ClipboardItem, CursorStyle, DispatchPhase, Edges, Entity,
24 FocusHandle, Focusable, FontStyle, FontWeight, GlobalElementId, Hitbox, Hsla, Image,
25 ImageFormat, KeyContext, Length, MouseDownEvent, MouseEvent, MouseMoveEvent, MouseUpEvent,
26 Point, Stateful, StrikethroughStyle, StyleRefinement, StyledText, Task, TextLayout, TextRun,
27 TextStyle, TextStyleRefinement, actions, img, point, quad,
28};
29use language::{Language, LanguageRegistry, Rope};
30use parser::CodeBlockMetadata;
31use parser::{MarkdownEvent, MarkdownTag, MarkdownTagEnd, parse_links_only, parse_markdown};
32use pulldown_cmark::Alignment;
33use sum_tree::TreeMap;
34use theme::SyntaxTheme;
35use ui::{Tooltip, prelude::*};
36use util::ResultExt;
37
38use crate::parser::CodeBlockKind;
39
40/// A callback function that can be used to customize the style of links based on the destination URL.
41/// If the callback returns `None`, the default link style will be used.
42type LinkStyleCallback = Rc<dyn Fn(&str, &App) -> Option<TextStyleRefinement>>;
43
44/// Defines custom style refinements for each heading level (H1-H6)
45#[derive(Clone, Default)]
46pub struct HeadingLevelStyles {
47 pub h1: Option<TextStyleRefinement>,
48 pub h2: Option<TextStyleRefinement>,
49 pub h3: Option<TextStyleRefinement>,
50 pub h4: Option<TextStyleRefinement>,
51 pub h5: Option<TextStyleRefinement>,
52 pub h6: Option<TextStyleRefinement>,
53}
54
55#[derive(Clone)]
56pub struct MarkdownStyle {
57 pub base_text_style: TextStyle,
58 pub code_block: StyleRefinement,
59 pub code_block_overflow_x_scroll: bool,
60 pub inline_code: TextStyleRefinement,
61 pub block_quote: TextStyleRefinement,
62 pub link: TextStyleRefinement,
63 pub link_callback: Option<LinkStyleCallback>,
64 pub rule_color: Hsla,
65 pub block_quote_border_color: Hsla,
66 pub syntax: Arc<SyntaxTheme>,
67 pub selection_background_color: Hsla,
68 pub heading: StyleRefinement,
69 pub heading_level_styles: Option<HeadingLevelStyles>,
70 pub table_overflow_x_scroll: bool,
71 pub height_is_multiple_of_line_height: bool,
72}
73
74impl Default for MarkdownStyle {
75 fn default() -> Self {
76 Self {
77 base_text_style: Default::default(),
78 code_block: Default::default(),
79 code_block_overflow_x_scroll: false,
80 inline_code: Default::default(),
81 block_quote: Default::default(),
82 link: Default::default(),
83 link_callback: None,
84 rule_color: Default::default(),
85 block_quote_border_color: Default::default(),
86 syntax: Arc::new(SyntaxTheme::default()),
87 selection_background_color: Default::default(),
88 heading: Default::default(),
89 heading_level_styles: None,
90 table_overflow_x_scroll: false,
91 height_is_multiple_of_line_height: false,
92 }
93 }
94}
95
96pub struct Markdown {
97 source: SharedString,
98 selection: Selection,
99 pressed_link: Option<RenderedLink>,
100 autoscroll_request: Option<usize>,
101 parsed_markdown: ParsedMarkdown,
102 images_by_source_offset: HashMap<usize, Arc<Image>>,
103 should_reparse: bool,
104 pending_parse: Option<Task<()>>,
105 focus_handle: FocusHandle,
106 language_registry: Option<Arc<LanguageRegistry>>,
107 fallback_code_block_language: Option<LanguageName>,
108 options: Options,
109 copied_code_blocks: HashSet<ElementId>,
110}
111
112struct Options {
113 parse_links_only: bool,
114}
115
116pub enum CodeBlockRenderer {
117 Default {
118 copy_button: bool,
119 copy_button_on_hover: bool,
120 border: bool,
121 },
122 Custom {
123 render: CodeBlockRenderFn,
124 /// A function that can modify the parent container after the code block
125 /// content has been appended as a child element.
126 transform: Option<CodeBlockTransformFn>,
127 },
128}
129
130pub type CodeBlockRenderFn = Arc<
131 dyn Fn(
132 &CodeBlockKind,
133 &ParsedMarkdown,
134 Range<usize>,
135 CodeBlockMetadata,
136 &mut Window,
137 &App,
138 ) -> Div,
139>;
140
141pub type CodeBlockTransformFn =
142 Arc<dyn Fn(AnyDiv, Range<usize>, CodeBlockMetadata, &mut Window, &App) -> AnyDiv>;
143
144actions!(markdown, [Copy, CopyAsMarkdown]);
145
146impl Markdown {
147 pub fn new(
148 source: SharedString,
149 language_registry: Option<Arc<LanguageRegistry>>,
150 fallback_code_block_language: Option<LanguageName>,
151 cx: &mut Context<Self>,
152 ) -> Self {
153 let focus_handle = cx.focus_handle();
154 let mut this = Self {
155 source,
156 selection: Selection::default(),
157 pressed_link: None,
158 autoscroll_request: None,
159 should_reparse: false,
160 images_by_source_offset: Default::default(),
161 parsed_markdown: ParsedMarkdown::default(),
162 pending_parse: None,
163 focus_handle,
164 language_registry,
165 fallback_code_block_language,
166 options: Options {
167 parse_links_only: false,
168 },
169 copied_code_blocks: HashSet::new(),
170 };
171 this.parse(cx);
172 this
173 }
174
175 pub fn new_text(source: SharedString, cx: &mut Context<Self>) -> Self {
176 let focus_handle = cx.focus_handle();
177 let mut this = Self {
178 source,
179 selection: Selection::default(),
180 pressed_link: None,
181 autoscroll_request: None,
182 should_reparse: false,
183 parsed_markdown: ParsedMarkdown::default(),
184 images_by_source_offset: Default::default(),
185 pending_parse: None,
186 focus_handle,
187 language_registry: None,
188 fallback_code_block_language: None,
189 options: Options {
190 parse_links_only: true,
191 },
192 copied_code_blocks: HashSet::new(),
193 };
194 this.parse(cx);
195 this
196 }
197
198 pub fn is_parsing(&self) -> bool {
199 self.pending_parse.is_some()
200 }
201
202 // Chunks: `Mark|down.md` You need to reparse every back tick, everytime
203 // `[foo.rs](foo.rs)` [`foo.rs`](foo.rs) `ba|r.rs`
204
205 pub fn source(&self) -> &str {
206 &self.source
207 }
208
209 pub fn append(&mut self, text: &str, cx: &mut Context<Self>) {
210 self.source = SharedString::new(self.source.to_string() + text);
211 self.parse(cx);
212 }
213
214 pub fn replace(&mut self, source: impl Into<SharedString>, cx: &mut Context<Self>) {
215 self.source = source.into();
216 self.parse(cx);
217 }
218
219 pub fn reset(&mut self, source: SharedString, cx: &mut Context<Self>) {
220 if source == self.source() {
221 return;
222 }
223 self.source = source;
224 self.selection = Selection::default();
225 self.autoscroll_request = None;
226 self.pending_parse = None;
227 self.should_reparse = false;
228 self.parsed_markdown = ParsedMarkdown::default();
229 self.parse(cx);
230 }
231
232 #[cfg(any(test, feature = "test-support"))]
233 pub fn parsed_markdown(&self) -> &ParsedMarkdown {
234 &self.parsed_markdown
235 }
236
237 pub fn escape(s: &str) -> Cow<'_, str> {
238 // Valid to use bytes since multi-byte UTF-8 doesn't use ASCII chars.
239 let count = s
240 .bytes()
241 .filter(|c| *c == b'\n' || c.is_ascii_punctuation())
242 .count();
243 if count > 0 {
244 let mut output = String::with_capacity(s.len() + count);
245 let mut is_newline = false;
246 for c in s.chars() {
247 if is_newline && c == ' ' {
248 continue;
249 }
250 is_newline = c == '\n';
251 if c == '\n' {
252 output.push('\n')
253 } else if c.is_ascii_punctuation() {
254 output.push('\\')
255 }
256 output.push(c)
257 }
258 output.into()
259 } else {
260 s.into()
261 }
262 }
263
264 fn copy(&self, text: &RenderedText, _: &mut Window, cx: &mut Context<Self>) {
265 if self.selection.end <= self.selection.start {
266 return;
267 }
268 let text = text.text_for_range(self.selection.start..self.selection.end);
269 cx.write_to_clipboard(ClipboardItem::new_string(text));
270 }
271
272 fn copy_as_markdown(&self, _: &mut Window, cx: &mut Context<Self>) {
273 if self.selection.end <= self.selection.start {
274 return;
275 }
276 let text = self.source[self.selection.start..self.selection.end].to_string();
277 cx.write_to_clipboard(ClipboardItem::new_string(text));
278 }
279
280 fn parse(&mut self, cx: &mut Context<Self>) {
281 if self.source.is_empty() {
282 return;
283 }
284
285 if self.pending_parse.is_some() {
286 self.should_reparse = true;
287 return;
288 }
289 self.should_reparse = false;
290 self.pending_parse = Some(self.start_background_parse(cx));
291 }
292
293 fn start_background_parse(&self, cx: &Context<Self>) -> Task<()> {
294 let source = self.source.clone();
295 let should_parse_links_only = self.options.parse_links_only;
296 let language_registry = self.language_registry.clone();
297 let fallback = self.fallback_code_block_language.clone();
298
299 let parsed = cx.background_spawn(async move {
300 if should_parse_links_only {
301 return (
302 ParsedMarkdown {
303 events: Arc::from(parse_links_only(source.as_ref())),
304 source,
305 languages_by_name: TreeMap::default(),
306 languages_by_path: TreeMap::default(),
307 },
308 Default::default(),
309 );
310 }
311
312 let (events, language_names, paths) = parse_markdown(&source);
313 let mut images_by_source_offset = HashMap::default();
314 let mut languages_by_name = TreeMap::default();
315 let mut languages_by_path = TreeMap::default();
316 if let Some(registry) = language_registry.as_ref() {
317 for name in language_names {
318 let language = if !name.is_empty() {
319 registry.language_for_name_or_extension(&name).left_future()
320 } else if let Some(fallback) = &fallback {
321 registry.language_for_name(fallback.as_ref()).right_future()
322 } else {
323 continue;
324 };
325 if let Ok(language) = language.await {
326 languages_by_name.insert(name, language);
327 }
328 }
329
330 for path in paths {
331 if let Ok(language) = registry.language_for_file_path(&path).await {
332 languages_by_path.insert(path, language);
333 }
334 }
335 }
336
337 for (range, event) in &events {
338 if let MarkdownEvent::Start(MarkdownTag::Image { dest_url, .. }) = event {
339 if let Some(data_url) = dest_url.strip_prefix("data:") {
340 let Some((mime_info, data)) = data_url.split_once(',') else {
341 continue;
342 };
343 let Some((mime_type, encoding)) = mime_info.split_once(';') else {
344 continue;
345 };
346 let Some(format) = ImageFormat::from_mime_type(mime_type) else {
347 continue;
348 };
349 let is_base64 = encoding == "base64";
350 if is_base64 {
351 if let Some(bytes) = base64::prelude::BASE64_STANDARD
352 .decode(data)
353 .log_with_level(Level::Debug)
354 {
355 let image = Arc::new(Image::from_bytes(format, bytes));
356 images_by_source_offset.insert(range.start, image);
357 }
358 }
359 }
360 }
361 }
362
363 (
364 ParsedMarkdown {
365 source,
366 events: Arc::from(events),
367 languages_by_name,
368 languages_by_path,
369 },
370 images_by_source_offset,
371 )
372 });
373
374 cx.spawn(async move |this, cx| {
375 let (parsed, images_by_source_offset) = parsed.await;
376
377 this.update(cx, |this, cx| {
378 this.parsed_markdown = parsed;
379 this.images_by_source_offset = images_by_source_offset;
380 this.pending_parse.take();
381 if this.should_reparse {
382 this.parse(cx);
383 }
384 cx.refresh_windows();
385 })
386 .ok();
387 })
388 }
389}
390
391impl Focusable for Markdown {
392 fn focus_handle(&self, _cx: &App) -> FocusHandle {
393 self.focus_handle.clone()
394 }
395}
396
397#[derive(Copy, Clone, Default, Debug)]
398struct Selection {
399 start: usize,
400 end: usize,
401 reversed: bool,
402 pending: bool,
403}
404
405impl Selection {
406 fn set_head(&mut self, head: usize) {
407 if head < self.tail() {
408 if !self.reversed {
409 self.end = self.start;
410 self.reversed = true;
411 }
412 self.start = head;
413 } else {
414 if self.reversed {
415 self.start = self.end;
416 self.reversed = false;
417 }
418 self.end = head;
419 }
420 }
421
422 fn tail(&self) -> usize {
423 if self.reversed { self.end } else { self.start }
424 }
425}
426
427#[derive(Clone, Default)]
428pub struct ParsedMarkdown {
429 pub source: SharedString,
430 pub events: Arc<[(Range<usize>, MarkdownEvent)]>,
431 pub languages_by_name: TreeMap<SharedString, Arc<Language>>,
432 pub languages_by_path: TreeMap<Arc<Path>, Arc<Language>>,
433}
434
435impl ParsedMarkdown {
436 pub fn source(&self) -> &SharedString {
437 &self.source
438 }
439
440 pub fn events(&self) -> &Arc<[(Range<usize>, MarkdownEvent)]> {
441 &self.events
442 }
443}
444
445// pub trait TextClickHandler {
446// fn pattern(&self) ->
447// fn hovered(&mut self, text: &str) -> bool;
448// fn clicked(&mut self, text: &str);
449// }
450// const WORD_REGEX: &str =
451// r#"[\$\+\w.\[\]:/\\@\-~()]+(?:\((?:\d+|\d+,\d+)\))|[\$\+\w.\[\]:/\\@\-~()]+"#;
452
453pub struct UrlHandler {
454 pub on_hover: Box<dyn Fn(&str, &mut Window, &mut App) -> bool>,
455 pub on_click: Box<dyn Fn(&str, &mut Window, &mut App)>,
456}
457
458pub struct MarkdownElement {
459 markdown: Entity<Markdown>,
460 style: MarkdownStyle,
461 code_block_renderer: CodeBlockRenderer,
462 on_link_click: Option<Box<dyn Fn(SharedString, &mut Window, &mut App)>>,
463 url_handler: Option<UrlHandler>,
464}
465
466impl MarkdownElement {
467 pub fn new(markdown: Entity<Markdown>, style: MarkdownStyle) -> Self {
468 Self {
469 markdown,
470 style,
471 code_block_renderer: CodeBlockRenderer::Default {
472 copy_button: true,
473 copy_button_on_hover: false,
474 border: false,
475 },
476 on_link_click: None,
477 url_handler: None,
478 }
479 }
480
481 #[cfg(any(test, feature = "test-support"))]
482 pub fn rendered_text(
483 markdown: Entity<Markdown>,
484 cx: &mut gpui::VisualTestContext,
485 style: impl FnOnce(&Window, &App) -> MarkdownStyle,
486 ) -> String {
487 use gpui::size;
488
489 let (text, _) = cx.draw(
490 Default::default(),
491 size(px(600.0), px(600.0)),
492 |window, cx| Self::new(markdown, style(window, cx)),
493 );
494 text.text
495 .lines
496 .iter()
497 .map(|line| line.layout.wrapped_text())
498 .collect::<Vec<_>>()
499 .join("\n")
500 }
501
502 pub fn code_block_renderer(mut self, variant: CodeBlockRenderer) -> Self {
503 self.code_block_renderer = variant;
504 self
505 }
506
507 pub fn on_url_click(
508 mut self,
509 handler: impl Fn(SharedString, &mut Window, &mut App) + 'static,
510 ) -> Self {
511 self.on_link_click = Some(Box::new(handler));
512 self
513 }
514
515 pub fn handle_urls(mut self, handler: UrlHandler) -> Self {
516 self.url_handler = Some(handler);
517 self
518 }
519
520 fn paint_selection(
521 &self,
522 bounds: Bounds<Pixels>,
523 rendered_text: &RenderedText,
524 window: &mut Window,
525 cx: &mut App,
526 ) {
527 let selection = self.markdown.read(cx).selection;
528 let selection_start = rendered_text.position_for_source_index(selection.start);
529 let selection_end = rendered_text.position_for_source_index(selection.end);
530 if let Some(((start_position, start_line_height), (end_position, end_line_height))) =
531 selection_start.zip(selection_end)
532 {
533 if start_position.y == end_position.y {
534 window.paint_quad(quad(
535 Bounds::from_corners(
536 start_position,
537 point(end_position.x, end_position.y + end_line_height),
538 ),
539 Pixels::ZERO,
540 self.style.selection_background_color,
541 Edges::default(),
542 Hsla::transparent_black(),
543 BorderStyle::default(),
544 ));
545 } else {
546 window.paint_quad(quad(
547 Bounds::from_corners(
548 start_position,
549 point(bounds.right(), start_position.y + start_line_height),
550 ),
551 Pixels::ZERO,
552 self.style.selection_background_color,
553 Edges::default(),
554 Hsla::transparent_black(),
555 BorderStyle::default(),
556 ));
557
558 if end_position.y > start_position.y + start_line_height {
559 window.paint_quad(quad(
560 Bounds::from_corners(
561 point(bounds.left(), start_position.y + start_line_height),
562 point(bounds.right(), end_position.y),
563 ),
564 Pixels::ZERO,
565 self.style.selection_background_color,
566 Edges::default(),
567 Hsla::transparent_black(),
568 BorderStyle::default(),
569 ));
570 }
571
572 window.paint_quad(quad(
573 Bounds::from_corners(
574 point(bounds.left(), end_position.y),
575 point(end_position.x, end_position.y + end_line_height),
576 ),
577 Pixels::ZERO,
578 self.style.selection_background_color,
579 Edges::default(),
580 Hsla::transparent_black(),
581 BorderStyle::default(),
582 ));
583 }
584 }
585 }
586
587 fn paint_mouse_listeners(
588 &mut self,
589 hitbox: &Hitbox,
590 rendered_text: &RenderedText,
591 window: &mut Window,
592 cx: &mut App,
593 ) {
594 let is_hovering_link = hitbox.is_hovered(window)
595 && !self.markdown.read(cx).selection.pending
596 && rendered_text
597 .link_for_position(window.mouse_position())
598 .is_some();
599
600 if is_hovering_link {
601 window.set_cursor_style(CursorStyle::PointingHand, hitbox);
602 } else {
603 window.set_cursor_style(CursorStyle::IBeam, hitbox);
604 }
605
606 let on_open_url = self.on_link_click.take();
607
608 self.on_mouse_event(window, cx, {
609 let rendered_text = rendered_text.clone();
610 let hitbox = hitbox.clone();
611 move |markdown, event: &MouseDownEvent, phase, window, cx| {
612 if hitbox.is_hovered(window) {
613 if phase.bubble() {
614 if let Some(link) = rendered_text.link_for_position(event.position) {
615 markdown.pressed_link = Some(link.clone());
616 } else {
617 // if
618
619 let source_index =
620 match rendered_text.source_index_for_position(event.position) {
621 Ok(ix) | Err(ix) => ix,
622 };
623 let range = if event.click_count == 2 {
624 rendered_text.surrounding_word_range(source_index)
625 } else if event.click_count == 3 {
626 rendered_text.surrounding_line_range(source_index)
627 } else {
628 source_index..source_index
629 };
630 markdown.selection = Selection {
631 start: range.start,
632 end: range.end,
633 reversed: false,
634 pending: true,
635 };
636 window.focus(&markdown.focus_handle);
637 }
638
639 window.prevent_default();
640 cx.notify();
641 }
642 } else if phase.capture() {
643 markdown.selection = Selection::default();
644 markdown.pressed_link = None;
645 cx.notify();
646 }
647 }
648 });
649 self.on_mouse_event(window, cx, {
650 let rendered_text = rendered_text.clone();
651 let hitbox = hitbox.clone();
652 let was_hovering_link = is_hovering_link;
653 move |markdown, event: &MouseMoveEvent, phase, window, cx| {
654 if phase.capture() {
655 return;
656 }
657
658 if markdown.selection.pending {
659 let source_index = match rendered_text.source_index_for_position(event.position)
660 {
661 Ok(ix) | Err(ix) => ix,
662 };
663 markdown.selection.set_head(source_index);
664 markdown.autoscroll_request = Some(source_index);
665 cx.notify();
666 } else {
667 let is_hovering_link = hitbox.is_hovered(window)
668 && rendered_text.link_for_position(event.position).is_some();
669 if is_hovering_link != was_hovering_link {
670 cx.notify();
671 }
672 }
673 }
674 });
675 self.on_mouse_event(window, cx, {
676 let rendered_text = rendered_text.clone();
677 move |markdown, event: &MouseUpEvent, phase, window, cx| {
678 if phase.bubble() {
679 if let Some(pressed_link) = markdown.pressed_link.take() {
680 if Some(&pressed_link) == rendered_text.link_for_position(event.position) {
681 if let Some(open_url) = on_open_url.as_ref() {
682 open_url(pressed_link.destination_url, window, cx);
683 } else {
684 cx.open_url(&pressed_link.destination_url);
685 }
686 }
687 }
688 } else if markdown.selection.pending {
689 markdown.selection.pending = false;
690 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
691 {
692 let text = rendered_text
693 .text_for_range(markdown.selection.start..markdown.selection.end);
694 cx.write_to_primary(ClipboardItem::new_string(text))
695 }
696 cx.notify();
697 }
698 }
699 });
700 }
701
702 fn autoscroll(
703 &self,
704 rendered_text: &RenderedText,
705 window: &mut Window,
706 cx: &mut App,
707 ) -> Option<()> {
708 let autoscroll_index = self
709 .markdown
710 .update(cx, |markdown, _| markdown.autoscroll_request.take())?;
711 let (position, line_height) = rendered_text.position_for_source_index(autoscroll_index)?;
712
713 let text_style = self.style.base_text_style.clone();
714 let font_id = window.text_system().resolve_font(&text_style.font());
715 let font_size = text_style.font_size.to_pixels(window.rem_size());
716 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
717 window.request_autoscroll(Bounds::from_corners(
718 point(position.x - 3. * em_width, position.y - 3. * line_height),
719 point(position.x + 3. * em_width, position.y + 3. * line_height),
720 ));
721 Some(())
722 }
723
724 fn on_mouse_event<T: MouseEvent>(
725 &self,
726 window: &mut Window,
727 _cx: &mut App,
728 mut f: impl 'static
729 + FnMut(&mut Markdown, &T, DispatchPhase, &mut Window, &mut Context<Markdown>),
730 ) {
731 window.on_mouse_event({
732 let markdown = self.markdown.downgrade();
733 move |event, phase, window, cx| {
734 markdown
735 .update(cx, |markdown, cx| f(markdown, event, phase, window, cx))
736 .log_err();
737 }
738 });
739 }
740}
741
742impl Element for MarkdownElement {
743 type RequestLayoutState = RenderedMarkdown;
744 type PrepaintState = Hitbox;
745
746 fn id(&self) -> Option<ElementId> {
747 None
748 }
749
750 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
751 None
752 }
753
754 fn request_layout(
755 &mut self,
756 _id: Option<&GlobalElementId>,
757 _inspector_id: Option<&gpui::InspectorElementId>,
758 window: &mut Window,
759 cx: &mut App,
760 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
761 let mut builder = MarkdownElementBuilder::new(
762 self.style.base_text_style.clone(),
763 self.style.syntax.clone(),
764 );
765 let markdown = self.markdown.read(cx);
766 let parsed_markdown = &markdown.parsed_markdown;
767 let images = &markdown.images_by_source_offset;
768 let markdown_end = if let Some(last) = parsed_markdown.events.last() {
769 last.0.end
770 } else {
771 0
772 };
773
774 let mut current_code_block_metadata = None;
775 let mut current_img_block_range: Option<Range<usize>> = None;
776 for (range, event) in parsed_markdown.events.iter() {
777 // Skip alt text for images that rendered
778 if let Some(current_img_block_range) = ¤t_img_block_range {
779 if current_img_block_range.end > range.end {
780 continue;
781 }
782 }
783
784 match event {
785 MarkdownEvent::Start(tag) => {
786 match tag {
787 MarkdownTag::Image { .. } => {
788 if let Some(image) = images.get(&range.start) {
789 current_img_block_range = Some(range.clone());
790 builder.modify_current_div(|el| {
791 el.items_center()
792 .flex()
793 .flex_row()
794 .child(img(image.clone()))
795 });
796 }
797 }
798 MarkdownTag::Paragraph => {
799 builder.push_div(
800 div().when(!self.style.height_is_multiple_of_line_height, |el| {
801 el.mb_2().line_height(rems(1.3))
802 }),
803 range,
804 markdown_end,
805 );
806 }
807 MarkdownTag::Heading { level, .. } => {
808 let mut heading = div().mb_2();
809
810 heading = apply_heading_style(
811 heading,
812 *level,
813 self.style.heading_level_styles.as_ref(),
814 );
815
816 heading.style().refine(&self.style.heading);
817
818 let text_style =
819 self.style.heading.text_style().clone().unwrap_or_default();
820
821 builder.push_text_style(text_style);
822 builder.push_div(heading, range, markdown_end);
823 }
824 MarkdownTag::BlockQuote => {
825 builder.push_text_style(self.style.block_quote.clone());
826 builder.push_div(
827 div()
828 .pl_4()
829 .mb_2()
830 .border_l_4()
831 .border_color(self.style.block_quote_border_color),
832 range,
833 markdown_end,
834 );
835 }
836 MarkdownTag::CodeBlock { kind, metadata } => {
837 let language = match kind {
838 CodeBlockKind::Fenced => None,
839 CodeBlockKind::FencedLang(language) => {
840 parsed_markdown.languages_by_name.get(language).cloned()
841 }
842 CodeBlockKind::FencedSrc(path_range) => parsed_markdown
843 .languages_by_path
844 .get(&path_range.path)
845 .cloned(),
846 _ => None,
847 };
848
849 current_code_block_metadata = Some(metadata.clone());
850
851 let is_indented = matches!(kind, CodeBlockKind::Indented);
852
853 match (&self.code_block_renderer, is_indented) {
854 (CodeBlockRenderer::Default { .. }, _) | (_, true) => {
855 // This is a parent container that we can position the copy button inside.
856 builder.push_div(
857 div().group("code_block").relative().w_full(),
858 range,
859 markdown_end,
860 );
861
862 let mut code_block = div()
863 .id(("code-block", range.start))
864 .rounded_lg()
865 .map(|mut code_block| {
866 if self.style.code_block_overflow_x_scroll {
867 code_block.style().restrict_scroll_to_axis =
868 Some(true);
869 code_block.flex().overflow_x_scroll()
870 } else {
871 code_block.w_full()
872 }
873 });
874
875 if let CodeBlockRenderer::Default { border: true, .. } =
876 &self.code_block_renderer
877 {
878 code_block = code_block
879 .rounded_md()
880 .border_1()
881 .border_color(cx.theme().colors().border_variant);
882 }
883
884 code_block.style().refine(&self.style.code_block);
885 if let Some(code_block_text_style) = &self.style.code_block.text
886 {
887 builder.push_text_style(code_block_text_style.to_owned());
888 }
889 builder.push_code_block(language);
890 builder.push_div(code_block, range, markdown_end);
891 }
892 (CodeBlockRenderer::Custom { render, .. }, _) => {
893 let parent_container = render(
894 kind,
895 &parsed_markdown,
896 range.clone(),
897 metadata.clone(),
898 window,
899 cx,
900 );
901
902 builder.push_div(parent_container, range, markdown_end);
903
904 let mut code_block = div()
905 .id(("code-block", range.start))
906 .rounded_b_lg()
907 .map(|mut code_block| {
908 if self.style.code_block_overflow_x_scroll {
909 code_block.style().restrict_scroll_to_axis =
910 Some(true);
911 code_block
912 .flex()
913 .overflow_x_scroll()
914 .overflow_y_hidden()
915 } else {
916 code_block.w_full().overflow_hidden()
917 }
918 });
919
920 code_block.style().refine(&self.style.code_block);
921
922 if let Some(code_block_text_style) = &self.style.code_block.text
923 {
924 builder.push_text_style(code_block_text_style.to_owned());
925 }
926
927 builder.push_code_block(language);
928 builder.push_div(code_block, range, markdown_end);
929 }
930 }
931 }
932 MarkdownTag::HtmlBlock => builder.push_div(div(), range, markdown_end),
933 MarkdownTag::List(bullet_index) => {
934 builder.push_list(*bullet_index);
935 builder.push_div(div().pl_4(), range, markdown_end);
936 }
937 MarkdownTag::Item => {
938 let bullet = if let Some(bullet_index) = builder.next_bullet_index() {
939 format!("{}.", bullet_index)
940 } else {
941 "•".to_string()
942 };
943 builder.push_div(
944 div()
945 .when(!self.style.height_is_multiple_of_line_height, |el| {
946 el.mb_1().gap_1().line_height(rems(1.3))
947 })
948 .h_flex()
949 .items_start()
950 .child(bullet),
951 range,
952 markdown_end,
953 );
954 // Without `w_0`, text doesn't wrap to the width of the container.
955 builder.push_div(div().flex_1().w_0(), range, markdown_end);
956 }
957 MarkdownTag::Emphasis => builder.push_text_style(TextStyleRefinement {
958 font_style: Some(FontStyle::Italic),
959 ..Default::default()
960 }),
961 MarkdownTag::Strong => builder.push_text_style(TextStyleRefinement {
962 font_weight: Some(FontWeight::BOLD),
963 ..Default::default()
964 }),
965 MarkdownTag::Strikethrough => {
966 builder.push_text_style(TextStyleRefinement {
967 strikethrough: Some(StrikethroughStyle {
968 thickness: px(1.),
969 color: None,
970 }),
971 ..Default::default()
972 })
973 }
974 MarkdownTag::Link { dest_url, .. } => {
975 if builder.code_block_stack.is_empty() {
976 builder.push_link(dest_url.clone(), range.clone());
977 let style = self
978 .style
979 .link_callback
980 .as_ref()
981 .and_then(|callback| callback(dest_url, cx))
982 .unwrap_or_else(|| self.style.link.clone());
983 builder.push_text_style(style)
984 }
985 }
986 MarkdownTag::MetadataBlock(_) => {}
987 MarkdownTag::Table(alignments) => {
988 builder.table_alignments = alignments.clone();
989 builder.push_div(
990 div()
991 .id(("table", range.start))
992 .flex()
993 .border_1()
994 .border_color(cx.theme().colors().border)
995 .rounded_sm()
996 .when(self.style.table_overflow_x_scroll, |mut table| {
997 table.style().restrict_scroll_to_axis = Some(true);
998 table.overflow_x_scroll()
999 }),
1000 range,
1001 markdown_end,
1002 );
1003 // This inner `v_flex` is so the table rows will stack vertically without disrupting the `overflow_x_scroll`.
1004 builder.push_div(div().v_flex().flex_grow(), range, markdown_end);
1005 }
1006 MarkdownTag::TableHead => {
1007 builder.push_div(
1008 div()
1009 .flex()
1010 .justify_between()
1011 .border_b_1()
1012 .border_color(cx.theme().colors().border),
1013 range,
1014 markdown_end,
1015 );
1016 builder.push_text_style(TextStyleRefinement {
1017 font_weight: Some(FontWeight::BOLD),
1018 ..Default::default()
1019 });
1020 }
1021 MarkdownTag::TableRow => {
1022 builder.push_div(
1023 div().h_flex().justify_between().px_1().py_0p5(),
1024 range,
1025 markdown_end,
1026 );
1027 }
1028 MarkdownTag::TableCell => {
1029 let column_count = builder.table_alignments.len();
1030
1031 builder.push_div(
1032 div()
1033 .flex()
1034 .px_1()
1035 .w(relative(1. / column_count as f32))
1036 .truncate(),
1037 range,
1038 markdown_end,
1039 );
1040 }
1041 _ => log::debug!("unsupported markdown tag {:?}", tag),
1042 }
1043 }
1044 MarkdownEvent::End(tag) => match tag {
1045 MarkdownTagEnd::Image => {
1046 current_img_block_range.take();
1047 }
1048 MarkdownTagEnd::Paragraph => {
1049 builder.pop_div();
1050 }
1051 MarkdownTagEnd::Heading(_) => {
1052 builder.pop_div();
1053 builder.pop_text_style()
1054 }
1055 MarkdownTagEnd::BlockQuote(_kind) => {
1056 builder.pop_text_style();
1057 builder.pop_div()
1058 }
1059 MarkdownTagEnd::CodeBlock => {
1060 builder.trim_trailing_newline();
1061
1062 builder.pop_div();
1063 builder.pop_code_block();
1064 if self.style.code_block.text.is_some() {
1065 builder.pop_text_style();
1066 }
1067
1068 let metadata = current_code_block_metadata.take();
1069
1070 if let CodeBlockRenderer::Custom {
1071 transform: Some(transform),
1072 ..
1073 } = &self.code_block_renderer
1074 {
1075 builder.modify_current_div(|el| {
1076 transform(
1077 el,
1078 range.clone(),
1079 metadata.clone().unwrap_or_default(),
1080 window,
1081 cx,
1082 )
1083 });
1084 }
1085
1086 if let CodeBlockRenderer::Default {
1087 copy_button: true, ..
1088 } = &self.code_block_renderer
1089 {
1090 builder.modify_current_div(|el| {
1091 let content_range = parser::extract_code_block_content_range(
1092 parsed_markdown.source()[range.clone()].trim(),
1093 );
1094 let content_range = content_range.start + range.start
1095 ..content_range.end + range.start;
1096
1097 let code = parsed_markdown.source()[content_range].to_string();
1098 let codeblock = render_copy_code_block_button(
1099 range.end,
1100 code,
1101 self.markdown.clone(),
1102 cx,
1103 );
1104 el.child(div().absolute().top_1().right_1().w_5().child(codeblock))
1105 });
1106 }
1107
1108 if let CodeBlockRenderer::Default {
1109 copy_button_on_hover: true,
1110 ..
1111 } = &self.code_block_renderer
1112 {
1113 builder.modify_current_div(|el| {
1114 let content_range = parser::extract_code_block_content_range(
1115 parsed_markdown.source()[range.clone()].trim(),
1116 );
1117 let content_range = content_range.start + range.start
1118 ..content_range.end + range.start;
1119
1120 let code = parsed_markdown.source()[content_range].to_string();
1121 let codeblock = render_copy_code_block_button(
1122 range.end,
1123 code,
1124 self.markdown.clone(),
1125 cx,
1126 );
1127 el.child(
1128 div()
1129 .absolute()
1130 .top_0()
1131 .right_0()
1132 .w_5()
1133 .visible_on_hover("code_block")
1134 .child(codeblock),
1135 )
1136 });
1137 }
1138
1139 // Pop the parent container.
1140 builder.pop_div();
1141 }
1142 MarkdownTagEnd::HtmlBlock => builder.pop_div(),
1143 MarkdownTagEnd::List(_) => {
1144 builder.pop_list();
1145 builder.pop_div();
1146 }
1147 MarkdownTagEnd::Item => {
1148 builder.pop_div();
1149 builder.pop_div();
1150 }
1151 MarkdownTagEnd::Emphasis => builder.pop_text_style(),
1152 MarkdownTagEnd::Strong => builder.pop_text_style(),
1153 MarkdownTagEnd::Strikethrough => builder.pop_text_style(),
1154 MarkdownTagEnd::Link => {
1155 if builder.code_block_stack.is_empty() {
1156 builder.pop_text_style()
1157 }
1158 }
1159 MarkdownTagEnd::Table => {
1160 builder.pop_div();
1161 builder.pop_div();
1162 builder.table_alignments.clear();
1163 }
1164 MarkdownTagEnd::TableHead => {
1165 builder.pop_div();
1166 builder.pop_text_style();
1167 }
1168 MarkdownTagEnd::TableRow => {
1169 builder.pop_div();
1170 }
1171 MarkdownTagEnd::TableCell => {
1172 builder.pop_div();
1173 }
1174 _ => log::debug!("unsupported markdown tag end: {:?}", tag),
1175 },
1176 MarkdownEvent::Text => {
1177 builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
1178 }
1179 MarkdownEvent::SubstitutedText(text) => {
1180 builder.push_text(text, range.clone());
1181 }
1182 MarkdownEvent::Code => {
1183 builder.push_text_style(self.style.inline_code.clone());
1184 builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
1185 builder.pop_text_style();
1186 }
1187 MarkdownEvent::Html => {
1188 let html = &parsed_markdown.source[range.clone()];
1189 if html.starts_with("<!--") {
1190 builder.html_comment = true;
1191 }
1192 if html.trim_end().ends_with("-->") {
1193 builder.html_comment = false;
1194 continue;
1195 }
1196 if builder.html_comment {
1197 continue;
1198 }
1199 builder.push_text(html, range.clone());
1200 }
1201 MarkdownEvent::InlineHtml => {
1202 builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
1203 }
1204 MarkdownEvent::Rule => {
1205 builder.push_div(
1206 div()
1207 .border_b_1()
1208 .my_2()
1209 .border_color(self.style.rule_color),
1210 range,
1211 markdown_end,
1212 );
1213 builder.pop_div()
1214 }
1215 MarkdownEvent::SoftBreak => builder.push_text(" ", range.clone()),
1216 MarkdownEvent::HardBreak => builder.push_text("\n", range.clone()),
1217 _ => log::error!("unsupported markdown event {:?}", event),
1218 }
1219 }
1220 let mut rendered_markdown = builder.build();
1221 let child_layout_id = rendered_markdown.element.request_layout(window, cx);
1222 let layout_id = window.request_layout(gpui::Style::default(), [child_layout_id], cx);
1223 (layout_id, rendered_markdown)
1224 }
1225
1226 fn prepaint(
1227 &mut self,
1228 _id: Option<&GlobalElementId>,
1229 _inspector_id: Option<&gpui::InspectorElementId>,
1230 bounds: Bounds<Pixels>,
1231 rendered_markdown: &mut Self::RequestLayoutState,
1232 window: &mut Window,
1233 cx: &mut App,
1234 ) -> Self::PrepaintState {
1235 let focus_handle = self.markdown.read(cx).focus_handle.clone();
1236 window.set_focus_handle(&focus_handle, cx);
1237 window.set_view_id(self.markdown.entity_id());
1238
1239 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1240 rendered_markdown.element.prepaint(window, cx);
1241 self.autoscroll(&rendered_markdown.text, window, cx);
1242 hitbox
1243 }
1244
1245 fn paint(
1246 &mut self,
1247 _id: Option<&GlobalElementId>,
1248 _inspector_id: Option<&gpui::InspectorElementId>,
1249 bounds: Bounds<Pixels>,
1250 rendered_markdown: &mut Self::RequestLayoutState,
1251 hitbox: &mut Self::PrepaintState,
1252 window: &mut Window,
1253 cx: &mut App,
1254 ) {
1255 let mut context = KeyContext::default();
1256 context.add("Markdown");
1257 window.set_key_context(context);
1258 window.on_action(std::any::TypeId::of::<crate::Copy>(), {
1259 let entity = self.markdown.clone();
1260 let text = rendered_markdown.text.clone();
1261 move |_, phase, window, cx| {
1262 let text = text.clone();
1263 if phase == DispatchPhase::Bubble {
1264 entity.update(cx, move |this, cx| this.copy(&text, window, cx))
1265 }
1266 }
1267 });
1268 window.on_action(std::any::TypeId::of::<crate::CopyAsMarkdown>(), {
1269 let entity = self.markdown.clone();
1270 move |_, phase, window, cx| {
1271 if phase == DispatchPhase::Bubble {
1272 entity.update(cx, move |this, cx| this.copy_as_markdown(window, cx))
1273 }
1274 }
1275 });
1276
1277 self.paint_mouse_listeners(hitbox, &rendered_markdown.text, window, cx);
1278 rendered_markdown.element.paint(window, cx);
1279 self.paint_selection(bounds, &rendered_markdown.text, window, cx);
1280 }
1281}
1282
1283fn apply_heading_style(
1284 mut heading: Div,
1285 level: pulldown_cmark::HeadingLevel,
1286 custom_styles: Option<&HeadingLevelStyles>,
1287) -> Div {
1288 heading = match level {
1289 pulldown_cmark::HeadingLevel::H1 => heading.text_3xl(),
1290 pulldown_cmark::HeadingLevel::H2 => heading.text_2xl(),
1291 pulldown_cmark::HeadingLevel::H3 => heading.text_xl(),
1292 pulldown_cmark::HeadingLevel::H4 => heading.text_lg(),
1293 pulldown_cmark::HeadingLevel::H5 => heading.text_base(),
1294 pulldown_cmark::HeadingLevel::H6 => heading.text_sm(),
1295 };
1296
1297 if let Some(styles) = custom_styles {
1298 let style_opt = match level {
1299 pulldown_cmark::HeadingLevel::H1 => &styles.h1,
1300 pulldown_cmark::HeadingLevel::H2 => &styles.h2,
1301 pulldown_cmark::HeadingLevel::H3 => &styles.h3,
1302 pulldown_cmark::HeadingLevel::H4 => &styles.h4,
1303 pulldown_cmark::HeadingLevel::H5 => &styles.h5,
1304 pulldown_cmark::HeadingLevel::H6 => &styles.h6,
1305 };
1306
1307 if let Some(style) = style_opt {
1308 heading.style().text = Some(style.clone());
1309 }
1310 }
1311
1312 heading
1313}
1314
1315fn render_copy_code_block_button(
1316 id: usize,
1317 code: String,
1318 markdown: Entity<Markdown>,
1319 cx: &App,
1320) -> impl IntoElement {
1321 let id = ElementId::named_usize("copy-markdown-code", id);
1322 let was_copied = markdown.read(cx).copied_code_blocks.contains(&id);
1323 IconButton::new(
1324 id.clone(),
1325 if was_copied {
1326 IconName::Check
1327 } else {
1328 IconName::Copy
1329 },
1330 )
1331 .icon_color(Color::Muted)
1332 .shape(ui::IconButtonShape::Square)
1333 .tooltip(Tooltip::text("Copy Code"))
1334 .on_click({
1335 let id = id.clone();
1336 let markdown = markdown.clone();
1337 move |_event, _window, cx| {
1338 let id = id.clone();
1339 markdown.update(cx, |this, cx| {
1340 this.copied_code_blocks.insert(id.clone());
1341
1342 cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));
1343
1344 cx.spawn(async move |this, cx| {
1345 cx.background_executor().timer(Duration::from_secs(2)).await;
1346
1347 cx.update(|cx| {
1348 this.update(cx, |this, cx| {
1349 this.copied_code_blocks.remove(&id);
1350 cx.notify();
1351 })
1352 })
1353 .ok();
1354 })
1355 .detach();
1356 });
1357 }
1358 })
1359}
1360
1361impl IntoElement for MarkdownElement {
1362 type Element = Self;
1363
1364 fn into_element(self) -> Self::Element {
1365 self
1366 }
1367}
1368
1369pub enum AnyDiv {
1370 Div(Div),
1371 Stateful(Stateful<Div>),
1372}
1373
1374impl AnyDiv {
1375 fn into_any_element(self) -> AnyElement {
1376 match self {
1377 Self::Div(div) => div.into_any_element(),
1378 Self::Stateful(div) => div.into_any_element(),
1379 }
1380 }
1381}
1382
1383impl From<Div> for AnyDiv {
1384 fn from(value: Div) -> Self {
1385 Self::Div(value)
1386 }
1387}
1388
1389impl From<Stateful<Div>> for AnyDiv {
1390 fn from(value: Stateful<Div>) -> Self {
1391 Self::Stateful(value)
1392 }
1393}
1394
1395impl Styled for AnyDiv {
1396 fn style(&mut self) -> &mut StyleRefinement {
1397 match self {
1398 Self::Div(div) => div.style(),
1399 Self::Stateful(div) => div.style(),
1400 }
1401 }
1402}
1403
1404impl ParentElement for AnyDiv {
1405 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1406 match self {
1407 Self::Div(div) => div.extend(elements),
1408 Self::Stateful(div) => div.extend(elements),
1409 }
1410 }
1411}
1412
1413struct MarkdownElementBuilder {
1414 div_stack: Vec<AnyDiv>,
1415 rendered_lines: Vec<RenderedLine>,
1416 pending_line: PendingLine,
1417 rendered_links: Vec<RenderedLink>,
1418 current_source_index: usize,
1419 html_comment: bool,
1420 base_text_style: TextStyle,
1421 text_style_stack: Vec<TextStyleRefinement>,
1422 code_block_stack: Vec<Option<Arc<Language>>>,
1423 list_stack: Vec<ListStackEntry>,
1424 table_alignments: Vec<Alignment>,
1425 syntax_theme: Arc<SyntaxTheme>,
1426}
1427
1428#[derive(Default)]
1429struct PendingLine {
1430 text: String,
1431 runs: Vec<TextRun>,
1432 source_mappings: Vec<SourceMapping>,
1433}
1434
1435struct ListStackEntry {
1436 bullet_index: Option<u64>,
1437}
1438
1439impl MarkdownElementBuilder {
1440 fn new(base_text_style: TextStyle, syntax_theme: Arc<SyntaxTheme>) -> Self {
1441 Self {
1442 div_stack: vec![div().debug_selector(|| "inner".into()).into()],
1443 rendered_lines: Vec::new(),
1444 pending_line: PendingLine::default(),
1445 rendered_links: Vec::new(),
1446 current_source_index: 0,
1447 html_comment: false,
1448 base_text_style,
1449 text_style_stack: Vec::new(),
1450 code_block_stack: Vec::new(),
1451 list_stack: Vec::new(),
1452 table_alignments: Vec::new(),
1453 syntax_theme,
1454 }
1455 }
1456
1457 fn push_text_style(&mut self, style: TextStyleRefinement) {
1458 self.text_style_stack.push(style);
1459 }
1460
1461 fn text_style(&self) -> TextStyle {
1462 let mut style = self.base_text_style.clone();
1463 for refinement in &self.text_style_stack {
1464 style.refine(refinement);
1465 }
1466 style
1467 }
1468
1469 fn pop_text_style(&mut self) {
1470 self.text_style_stack.pop();
1471 }
1472
1473 fn push_div(&mut self, div: impl Into<AnyDiv>, range: &Range<usize>, markdown_end: usize) {
1474 let mut div = div.into();
1475 self.flush_text();
1476
1477 if range.start == 0 {
1478 // Remove the top margin on the first element.
1479 div.style().refine(&StyleRefinement {
1480 margin: gpui::EdgesRefinement {
1481 top: Some(Length::Definite(px(0.).into())),
1482 left: None,
1483 right: None,
1484 bottom: None,
1485 },
1486 ..Default::default()
1487 });
1488 }
1489
1490 if range.end == markdown_end {
1491 div.style().refine(&StyleRefinement {
1492 margin: gpui::EdgesRefinement {
1493 top: None,
1494 left: None,
1495 right: None,
1496 bottom: Some(Length::Definite(rems(0.).into())),
1497 },
1498 ..Default::default()
1499 });
1500 }
1501
1502 self.div_stack.push(div);
1503 }
1504
1505 fn modify_current_div(&mut self, f: impl FnOnce(AnyDiv) -> AnyDiv) {
1506 self.flush_text();
1507 if let Some(div) = self.div_stack.pop() {
1508 self.div_stack.push(f(div));
1509 }
1510 }
1511
1512 fn pop_div(&mut self) {
1513 self.flush_text();
1514 let div = self.div_stack.pop().unwrap().into_any_element();
1515 self.div_stack.last_mut().unwrap().extend(iter::once(div));
1516 }
1517
1518 fn push_list(&mut self, bullet_index: Option<u64>) {
1519 self.list_stack.push(ListStackEntry { bullet_index });
1520 }
1521
1522 fn next_bullet_index(&mut self) -> Option<u64> {
1523 self.list_stack.last_mut().and_then(|entry| {
1524 let item_index = entry.bullet_index.as_mut()?;
1525 *item_index += 1;
1526 Some(*item_index - 1)
1527 })
1528 }
1529
1530 fn pop_list(&mut self) {
1531 self.list_stack.pop();
1532 }
1533
1534 fn push_code_block(&mut self, language: Option<Arc<Language>>) {
1535 self.code_block_stack.push(language);
1536 }
1537
1538 fn pop_code_block(&mut self) {
1539 self.code_block_stack.pop();
1540 }
1541
1542 fn push_link(&mut self, destination_url: SharedString, source_range: Range<usize>) {
1543 self.rendered_links.push(RenderedLink {
1544 source_range,
1545 destination_url,
1546 });
1547 }
1548
1549 fn push_text(&mut self, text: &str, source_range: Range<usize>) {
1550 self.pending_line.source_mappings.push(SourceMapping {
1551 rendered_index: self.pending_line.text.len(),
1552 source_index: source_range.start,
1553 });
1554 self.pending_line.text.push_str(text);
1555 self.current_source_index = source_range.end;
1556
1557 if let Some(Some(language)) = self.code_block_stack.last() {
1558 let mut offset = 0;
1559 for (range, highlight_id) in language.highlight_text(&Rope::from(text), 0..text.len()) {
1560 if range.start > offset {
1561 self.pending_line
1562 .runs
1563 .push(self.text_style().to_run(range.start - offset));
1564 }
1565
1566 let mut run_style = self.text_style();
1567 if let Some(highlight) = highlight_id.style(&self.syntax_theme) {
1568 run_style = run_style.highlight(highlight);
1569 }
1570 self.pending_line.runs.push(run_style.to_run(range.len()));
1571 offset = range.end;
1572 }
1573
1574 if offset < text.len() {
1575 self.pending_line
1576 .runs
1577 .push(self.text_style().to_run(text.len() - offset));
1578 }
1579 } else {
1580 self.pending_line
1581 .runs
1582 .push(self.text_style().to_run(text.len()));
1583 }
1584 }
1585
1586 fn trim_trailing_newline(&mut self) {
1587 if self.pending_line.text.ends_with('\n') {
1588 self.pending_line
1589 .text
1590 .truncate(self.pending_line.text.len() - 1);
1591 self.pending_line.runs.last_mut().unwrap().len -= 1;
1592 self.current_source_index -= 1;
1593 }
1594 }
1595
1596 fn flush_text(&mut self) {
1597 let line = mem::take(&mut self.pending_line);
1598 if line.text.is_empty() {
1599 return;
1600 }
1601
1602 let text = StyledText::new(line.text).with_runs(line.runs);
1603 self.rendered_lines.push(RenderedLine {
1604 layout: text.layout().clone(),
1605 source_mappings: line.source_mappings,
1606 source_end: self.current_source_index,
1607 });
1608 self.div_stack.last_mut().unwrap().extend([text.into_any()]);
1609 }
1610
1611 fn build(mut self) -> RenderedMarkdown {
1612 debug_assert_eq!(self.div_stack.len(), 1);
1613 self.flush_text();
1614 RenderedMarkdown {
1615 element: self.div_stack.pop().unwrap().into_any_element(),
1616 text: RenderedText {
1617 lines: self.rendered_lines.into(),
1618 links: self.rendered_links.into(),
1619 },
1620 }
1621 }
1622}
1623
1624struct RenderedLine {
1625 layout: TextLayout,
1626 source_mappings: Vec<SourceMapping>,
1627 source_end: usize,
1628}
1629
1630impl RenderedLine {
1631 fn rendered_index_for_source_index(&self, source_index: usize) -> usize {
1632 if source_index >= self.source_end {
1633 return self.layout.len();
1634 }
1635
1636 let mapping = match self
1637 .source_mappings
1638 .binary_search_by_key(&source_index, |probe| probe.source_index)
1639 {
1640 Ok(ix) => &self.source_mappings[ix],
1641 Err(ix) => &self.source_mappings[ix - 1],
1642 };
1643 mapping.rendered_index + (source_index - mapping.source_index)
1644 }
1645
1646 fn source_index_for_rendered_index(&self, rendered_index: usize) -> usize {
1647 if rendered_index >= self.layout.len() {
1648 return self.source_end;
1649 }
1650
1651 let mapping = match self
1652 .source_mappings
1653 .binary_search_by_key(&rendered_index, |probe| probe.rendered_index)
1654 {
1655 Ok(ix) => &self.source_mappings[ix],
1656 Err(ix) => &self.source_mappings[ix - 1],
1657 };
1658 mapping.source_index + (rendered_index - mapping.rendered_index)
1659 }
1660
1661 fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
1662 let line_rendered_index;
1663 let out_of_bounds;
1664 match self.layout.index_for_position(position) {
1665 Ok(ix) => {
1666 line_rendered_index = ix;
1667 out_of_bounds = false;
1668 }
1669 Err(ix) => {
1670 line_rendered_index = ix;
1671 out_of_bounds = true;
1672 }
1673 };
1674 let source_index = self.source_index_for_rendered_index(line_rendered_index);
1675 if out_of_bounds {
1676 Err(source_index)
1677 } else {
1678 Ok(source_index)
1679 }
1680 }
1681}
1682
1683#[derive(Copy, Clone, Debug, Default)]
1684struct SourceMapping {
1685 rendered_index: usize,
1686 source_index: usize,
1687}
1688
1689pub struct RenderedMarkdown {
1690 element: AnyElement,
1691 text: RenderedText,
1692}
1693
1694#[derive(Clone)]
1695struct RenderedText {
1696 lines: Rc<[RenderedLine]>,
1697 links: Rc<[RenderedLink]>,
1698}
1699
1700#[derive(Clone, Eq, PartialEq)]
1701struct RenderedLink {
1702 source_range: Range<usize>,
1703 destination_url: SharedString,
1704}
1705
1706impl RenderedText {
1707 fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
1708 let mut lines = self.lines.iter().peekable();
1709
1710 while let Some(line) = lines.next() {
1711 let line_bounds = line.layout.bounds();
1712 if position.y > line_bounds.bottom() {
1713 if let Some(next_line) = lines.peek() {
1714 if position.y < next_line.layout.bounds().top() {
1715 return Err(line.source_end);
1716 }
1717 }
1718
1719 continue;
1720 }
1721
1722 return line.source_index_for_position(position);
1723 }
1724
1725 Err(self.lines.last().map_or(0, |line| line.source_end))
1726 }
1727
1728 fn position_for_source_index(&self, source_index: usize) -> Option<(Point<Pixels>, Pixels)> {
1729 for line in self.lines.iter() {
1730 let line_source_start = line.source_mappings.first().unwrap().source_index;
1731 if source_index < line_source_start {
1732 break;
1733 } else if source_index > line.source_end {
1734 continue;
1735 } else {
1736 let line_height = line.layout.line_height();
1737 let rendered_index_within_line = line.rendered_index_for_source_index(source_index);
1738 let position = line.layout.position_for_index(rendered_index_within_line)?;
1739 return Some((position, line_height));
1740 }
1741 }
1742 None
1743 }
1744
1745 fn surrounding_word_range(&self, source_index: usize) -> Range<usize> {
1746 for line in self.lines.iter() {
1747 if source_index > line.source_end {
1748 continue;
1749 }
1750
1751 let line_rendered_start = line.source_mappings.first().unwrap().rendered_index;
1752 let rendered_index_in_line =
1753 line.rendered_index_for_source_index(source_index) - line_rendered_start;
1754 let text = line.layout.text();
1755 let previous_space = if let Some(idx) = text[0..rendered_index_in_line].rfind(' ') {
1756 idx + ' '.len_utf8()
1757 } else {
1758 0
1759 };
1760 let next_space = if let Some(idx) = text[rendered_index_in_line..].find(' ') {
1761 rendered_index_in_line + idx
1762 } else {
1763 text.len()
1764 };
1765
1766 return line.source_index_for_rendered_index(line_rendered_start + previous_space)
1767 ..line.source_index_for_rendered_index(line_rendered_start + next_space);
1768 }
1769
1770 source_index..source_index
1771 }
1772
1773 fn surrounding_line_range(&self, source_index: usize) -> Range<usize> {
1774 for line in self.lines.iter() {
1775 if source_index > line.source_end {
1776 continue;
1777 }
1778 let line_source_start = line.source_mappings.first().unwrap().source_index;
1779 return line_source_start..line.source_end;
1780 }
1781
1782 source_index..source_index
1783 }
1784
1785 fn text_for_range(&self, range: Range<usize>) -> String {
1786 let mut ret = vec![];
1787
1788 for line in self.lines.iter() {
1789 if range.start > line.source_end {
1790 continue;
1791 }
1792 let line_source_start = line.source_mappings.first().unwrap().source_index;
1793 if range.end < line_source_start {
1794 break;
1795 }
1796
1797 let text = line.layout.text();
1798
1799 let start = if range.start < line_source_start {
1800 0
1801 } else {
1802 line.rendered_index_for_source_index(range.start)
1803 };
1804 let end = if range.end > line.source_end {
1805 line.rendered_index_for_source_index(line.source_end)
1806 } else {
1807 line.rendered_index_for_source_index(range.end)
1808 }
1809 .min(text.len());
1810
1811 ret.push(text[start..end].to_string());
1812 }
1813 ret.join("\n")
1814 }
1815
1816 fn link_for_position(&self, position: Point<Pixels>) -> Option<&RenderedLink> {
1817 let source_index = self.source_index_for_position(position).ok()?;
1818 self.links
1819 .iter()
1820 .find(|link| link.source_range.contains(&source_index))
1821 }
1822}
1823
1824#[cfg(test)]
1825mod tests {
1826 use std::cell::RefCell;
1827
1828 use super::*;
1829 use gpui::{Modifiers, MouseButton, TestAppContext, size};
1830
1831 #[gpui::test]
1832 fn test_mappings(cx: &mut TestAppContext) {
1833 // Formatting.
1834 assert_mappings(
1835 &render_markdown("He*l*lo", cx),
1836 vec![vec![(0, 0), (1, 1), (2, 3), (3, 5), (4, 6), (5, 7)]],
1837 );
1838
1839 // Multiple lines.
1840 assert_mappings(
1841 &render_markdown("Hello\n\nWorld", cx),
1842 vec![
1843 vec![(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)],
1844 vec![(0, 7), (1, 8), (2, 9), (3, 10), (4, 11), (5, 12)],
1845 ],
1846 );
1847
1848 // Multi-byte characters.
1849 assert_mappings(
1850 &render_markdown("αβγ\n\nδεζ", cx),
1851 vec![
1852 vec![(0, 0), (2, 2), (4, 4), (6, 6)],
1853 vec![(0, 8), (2, 10), (4, 12), (6, 14)],
1854 ],
1855 );
1856
1857 // Smart quotes.
1858 assert_mappings(&render_markdown("\"", cx), vec![vec![(0, 0), (3, 1)]]);
1859 assert_mappings(
1860 &render_markdown("\"hey\"", cx),
1861 vec![vec![(0, 0), (3, 1), (4, 2), (5, 3), (6, 4), (9, 5)]],
1862 );
1863
1864 // HTML Comments are ignored
1865 assert_mappings(
1866 &render_markdown(
1867 "<!--\nrdoc-file=string.c\n- str.intern -> symbol\n- str.to_sym -> symbol\n-->\nReturns",
1868 cx,
1869 ),
1870 vec![vec![
1871 (0, 78),
1872 (1, 79),
1873 (2, 80),
1874 (3, 81),
1875 (4, 82),
1876 (5, 83),
1877 (6, 84),
1878 ]],
1879 );
1880 }
1881
1882 fn render_markdown(markdown: &str, cx: &mut TestAppContext) -> RenderedText {
1883 struct TestWindow;
1884
1885 impl Render for TestWindow {
1886 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1887 div()
1888 }
1889 }
1890
1891 let (_, cx) = cx.add_window_view(|_, _| TestWindow);
1892 let markdown = cx.new(|cx| Markdown::new(markdown.to_string().into(), None, None, cx));
1893 cx.run_until_parked();
1894 let (rendered, _) = cx.draw(
1895 Default::default(),
1896 size(px(600.0), px(600.0)),
1897 |_window, _cx| MarkdownElement::new(markdown, MarkdownStyle::default()),
1898 );
1899 rendered.text
1900 }
1901
1902 #[test]
1903 fn test_escape() {
1904 assert_eq!(Markdown::escape("hello `world`"), "hello \\`world\\`");
1905 assert_eq!(
1906 Markdown::escape("hello\n cool world"),
1907 "hello\n\ncool world"
1908 );
1909 }
1910
1911 #[gpui::test]
1912 fn test_url_handling(cx: &mut TestAppContext) {
1913 let markdown = r#"hello `world`
1914 Check out `https://zed.dev` for a great editor!
1915 Also available locally: crates/ README.md,
1916 "#;
1917
1918 struct TestWindow;
1919
1920 impl Render for TestWindow {
1921 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1922 div()
1923 }
1924 }
1925
1926 let (_, cx) = cx.add_window_view(|_, _| TestWindow);
1927 let markdown = cx.new(|cx| Markdown::new(markdown.to_string().into(), None, None, cx));
1928 cx.run_until_parked();
1929
1930 let paths_hovered = Rc::new(RefCell::new(Vec::new()));
1931 let paths_clicked = Rc::new(RefCell::new(Vec::new()));
1932
1933 let handler = {
1934 let paths_hovered = paths_hovered.clone();
1935 let paths_clicked = paths_clicked.clone();
1936
1937 UrlHandler {
1938 on_hover: Box::new(move |path, _window, _app| {
1939 paths_hovered.borrow_mut().push(path.to_string());
1940 true
1941 }),
1942 on_click: Box::new(move |path, _window, _app| {
1943 paths_clicked.borrow_mut().push(path.to_string());
1944 }),
1945 }
1946 };
1947
1948 let (rendered, _) = cx.draw(
1949 Default::default(),
1950 size(px(600.0), px(600.0)),
1951 |_window, _cx| {
1952 MarkdownElement::new(markdown, MarkdownStyle::default()).handle_urls(handler)
1953 },
1954 );
1955
1956 cx.simulate_mouse_move(
1957 point(px(0.0), px(0.0)),
1958 MouseButton::Left,
1959 Modifiers::default(),
1960 );
1961
1962 assert_eq!(paths_hovered.borrow().len(), 1)
1963 }
1964
1965 // To have a markdown document with paths and links in it
1966 // We want to run a function
1967 // and we want to get those paths and links out?
1968
1969 #[track_caller]
1970 fn assert_mappings(rendered: &RenderedText, expected: Vec<Vec<(usize, usize)>>) {
1971 assert_eq!(rendered.lines.len(), expected.len(), "line count mismatch");
1972 for (line_ix, line_mappings) in expected.into_iter().enumerate() {
1973 let line = &rendered.lines[line_ix];
1974
1975 assert!(
1976 line.source_mappings.windows(2).all(|mappings| {
1977 mappings[0].source_index < mappings[1].source_index
1978 && mappings[0].rendered_index < mappings[1].rendered_index
1979 }),
1980 "line {} has duplicate mappings: {:?}",
1981 line_ix,
1982 line.source_mappings
1983 );
1984
1985 for (rendered_ix, source_ix) in line_mappings {
1986 assert_eq!(
1987 line.source_index_for_rendered_index(rendered_ix),
1988 source_ix,
1989 "line {}, rendered_ix {}",
1990 line_ix,
1991 rendered_ix
1992 );
1993
1994 assert_eq!(
1995 line.rendered_index_for_source_index(source_ix),
1996 rendered_ix,
1997 "line {}, source_ix {}",
1998 line_ix,
1999 source_ix
2000 );
2001 }
2002 }
2003 }
2004}