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