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 code_block: StyleRefinement,
58 pub code_block_overflow_x_scroll: bool,
59 pub inline_code: TextStyleRefinement,
60 pub block_quote: TextStyleRefinement,
61 pub link: TextStyleRefinement,
62 pub link_callback: Option<LinkStyleCallback>,
63 pub rule_color: Hsla,
64 pub block_quote_border_color: Hsla,
65 pub syntax: Arc<SyntaxTheme>,
66 pub selection_background_color: Hsla,
67 pub heading: StyleRefinement,
68 pub heading_level_styles: Option<HeadingLevelStyles>,
69 pub table_overflow_x_scroll: bool,
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 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 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 Element for MarkdownElement {
754 type RequestLayoutState = RenderedMarkdown;
755 type PrepaintState = Hitbox;
756
757 fn id(&self) -> Option<ElementId> {
758 None
759 }
760
761 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
762 None
763 }
764
765 fn request_layout(
766 &mut self,
767 _id: Option<&GlobalElementId>,
768 _inspector_id: Option<&gpui::InspectorElementId>,
769 window: &mut Window,
770 cx: &mut App,
771 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
772 let mut builder = MarkdownElementBuilder::new(
773 self.style.base_text_style.clone(),
774 self.style.syntax.clone(),
775 );
776 let (parsed_markdown, images) = {
777 let markdown = self.markdown.read(cx);
778 (
779 markdown.parsed_markdown.clone(),
780 markdown.images_by_source_offset.clone(),
781 )
782 };
783 let markdown_end = if let Some(last) = parsed_markdown.events.last() {
784 last.0.end
785 } else {
786 0
787 };
788 let mut code_block_ids = HashSet::default();
789
790 let mut current_img_block_range: Option<Range<usize>> = None;
791 for (range, event) in parsed_markdown.events.iter() {
792 // Skip alt text for images that rendered
793 if let Some(current_img_block_range) = ¤t_img_block_range
794 && current_img_block_range.end > range.end
795 {
796 continue;
797 }
798
799 match event {
800 MarkdownEvent::Start(tag) => {
801 match tag {
802 MarkdownTag::Image { .. } => {
803 if let Some(image) = images.get(&range.start) {
804 current_img_block_range = Some(range.clone());
805 builder.modify_current_div(|el| {
806 el.items_center()
807 .flex()
808 .flex_row()
809 .child(img(image.clone()))
810 });
811 }
812 }
813 MarkdownTag::Paragraph => {
814 builder.push_div(
815 div().when(!self.style.height_is_multiple_of_line_height, |el| {
816 el.mb_2().line_height(rems(1.3))
817 }),
818 range,
819 markdown_end,
820 );
821 }
822 MarkdownTag::Heading { level, .. } => {
823 let mut heading = div().mb_2();
824
825 heading = apply_heading_style(
826 heading,
827 *level,
828 self.style.heading_level_styles.as_ref(),
829 );
830
831 heading.style().refine(&self.style.heading);
832
833 let text_style =
834 self.style.heading.text_style().clone().unwrap_or_default();
835
836 builder.push_text_style(text_style);
837 builder.push_div(heading, range, markdown_end);
838 }
839 MarkdownTag::BlockQuote => {
840 builder.push_text_style(self.style.block_quote.clone());
841 builder.push_div(
842 div()
843 .pl_4()
844 .mb_2()
845 .border_l_4()
846 .border_color(self.style.block_quote_border_color),
847 range,
848 markdown_end,
849 );
850 }
851 MarkdownTag::CodeBlock { kind, .. } => {
852 let language = match kind {
853 CodeBlockKind::Fenced => None,
854 CodeBlockKind::FencedLang(language) => {
855 parsed_markdown.languages_by_name.get(language).cloned()
856 }
857 CodeBlockKind::FencedSrc(path_range) => parsed_markdown
858 .languages_by_path
859 .get(&path_range.path)
860 .cloned(),
861 _ => None,
862 };
863
864 let is_indented = matches!(kind, CodeBlockKind::Indented);
865 let scroll_handle = if self.style.code_block_overflow_x_scroll {
866 code_block_ids.insert(range.start);
867 Some(self.markdown.update(cx, |markdown, _| {
868 markdown.code_block_scroll_handle(range.start)
869 }))
870 } else {
871 None
872 };
873
874 match (&self.code_block_renderer, is_indented) {
875 (CodeBlockRenderer::Default { .. }, _) | (_, true) => {
876 // This is a parent container that we can position the copy button inside.
877 let parent_container =
878 div().group("code_block").relative().w_full();
879
880 let mut parent_container: AnyDiv = if let Some(scroll_handle) =
881 scroll_handle.as_ref()
882 {
883 let scrollbars = Scrollbars::new(ScrollAxes::Horizontal)
884 .id(("markdown-code-block-scrollbar", range.start))
885 .tracked_scroll_handle(scroll_handle.clone())
886 .with_track_along(
887 ScrollAxes::Horizontal,
888 cx.theme().colors().editor_background,
889 )
890 .notify_content();
891
892 parent_container
893 .rounded_lg()
894 .custom_scrollbars(scrollbars, window, cx)
895 .into()
896 } else {
897 parent_container.into()
898 };
899
900 if let CodeBlockRenderer::Default { border: true, .. } =
901 &self.code_block_renderer
902 {
903 parent_container = parent_container
904 .rounded_md()
905 .border_1()
906 .border_color(cx.theme().colors().border_variant);
907 }
908
909 parent_container.style().refine(&self.style.code_block);
910 builder.push_div(parent_container, range, markdown_end);
911
912 let code_block = div()
913 .id(("code-block", range.start))
914 .rounded_lg()
915 .map(|mut code_block| {
916 if let Some(scroll_handle) = scroll_handle.as_ref() {
917 code_block.style().restrict_scroll_to_axis =
918 Some(true);
919 code_block
920 .flex()
921 .overflow_x_scroll()
922 .track_scroll(scroll_handle)
923 } else {
924 code_block.w_full()
925 }
926 });
927
928 if let Some(code_block_text_style) = &self.style.code_block.text
929 {
930 builder.push_text_style(code_block_text_style.to_owned());
931 }
932 builder.push_code_block(language);
933 builder.push_div(code_block, range, markdown_end);
934 }
935 (CodeBlockRenderer::Custom { .. }, _) => {}
936 }
937 }
938 MarkdownTag::HtmlBlock => builder.push_div(div(), range, markdown_end),
939 MarkdownTag::List(bullet_index) => {
940 builder.push_list(*bullet_index);
941 builder.push_div(div().pl_4(), range, markdown_end);
942 }
943 MarkdownTag::Item => {
944 let bullet = if let Some(bullet_index) = builder.next_bullet_index() {
945 format!("{}.", bullet_index)
946 } else {
947 "•".to_string()
948 };
949 builder.push_div(
950 div()
951 .when(!self.style.height_is_multiple_of_line_height, |el| {
952 el.mb_1().gap_1().line_height(rems(1.3))
953 })
954 .h_flex()
955 .items_start()
956 .child(bullet),
957 range,
958 markdown_end,
959 );
960 // Without `w_0`, text doesn't wrap to the width of the container.
961 builder.push_div(div().flex_1().w_0(), range, markdown_end);
962 }
963 MarkdownTag::Emphasis => builder.push_text_style(TextStyleRefinement {
964 font_style: Some(FontStyle::Italic),
965 ..Default::default()
966 }),
967 MarkdownTag::Strong => builder.push_text_style(TextStyleRefinement {
968 font_weight: Some(FontWeight::BOLD),
969 ..Default::default()
970 }),
971 MarkdownTag::Strikethrough => {
972 builder.push_text_style(TextStyleRefinement {
973 strikethrough: Some(StrikethroughStyle {
974 thickness: px(1.),
975 color: None,
976 }),
977 ..Default::default()
978 })
979 }
980 MarkdownTag::Link { dest_url, .. } => {
981 if builder.code_block_stack.is_empty() {
982 builder.push_link(dest_url.clone(), range.clone());
983 let style = self
984 .style
985 .link_callback
986 .as_ref()
987 .and_then(|callback| callback(dest_url, cx))
988 .unwrap_or_else(|| self.style.link.clone());
989 builder.push_text_style(style)
990 }
991 }
992 MarkdownTag::MetadataBlock(_) => {}
993 MarkdownTag::Table(alignments) => {
994 builder.table_alignments = alignments.clone();
995 builder.push_div(
996 div()
997 .id(("table", range.start))
998 .flex()
999 .border_1()
1000 .border_color(cx.theme().colors().border)
1001 .rounded_sm()
1002 .when(self.style.table_overflow_x_scroll, |mut table| {
1003 table.style().restrict_scroll_to_axis = Some(true);
1004 table.overflow_x_scroll()
1005 }),
1006 range,
1007 markdown_end,
1008 );
1009 // This inner `v_flex` is so the table rows will stack vertically without disrupting the `overflow_x_scroll`.
1010 builder.push_div(div().v_flex().flex_grow(), range, markdown_end);
1011 }
1012 MarkdownTag::TableHead => {
1013 builder.push_div(
1014 div()
1015 .flex()
1016 .justify_between()
1017 .border_b_1()
1018 .border_color(cx.theme().colors().border),
1019 range,
1020 markdown_end,
1021 );
1022 builder.push_text_style(TextStyleRefinement {
1023 font_weight: Some(FontWeight::BOLD),
1024 ..Default::default()
1025 });
1026 }
1027 MarkdownTag::TableRow => {
1028 builder.push_div(
1029 div().h_flex().justify_between().px_1().py_0p5(),
1030 range,
1031 markdown_end,
1032 );
1033 }
1034 MarkdownTag::TableCell => {
1035 let column_count = builder.table_alignments.len();
1036
1037 builder.push_div(
1038 div()
1039 .flex()
1040 .px_1()
1041 .w(relative(1. / column_count as f32))
1042 .truncate(),
1043 range,
1044 markdown_end,
1045 );
1046 }
1047 _ => log::debug!("unsupported markdown tag {:?}", tag),
1048 }
1049 }
1050 MarkdownEvent::End(tag) => match tag {
1051 MarkdownTagEnd::Image => {
1052 current_img_block_range.take();
1053 }
1054 MarkdownTagEnd::Paragraph => {
1055 builder.pop_div();
1056 }
1057 MarkdownTagEnd::Heading(_) => {
1058 builder.pop_div();
1059 builder.pop_text_style()
1060 }
1061 MarkdownTagEnd::BlockQuote(_kind) => {
1062 builder.pop_text_style();
1063 builder.pop_div()
1064 }
1065 MarkdownTagEnd::CodeBlock => {
1066 builder.trim_trailing_newline();
1067
1068 builder.pop_div();
1069 builder.pop_code_block();
1070 if self.style.code_block.text.is_some() {
1071 builder.pop_text_style();
1072 }
1073
1074 if let CodeBlockRenderer::Default {
1075 copy_button: true, ..
1076 } = &self.code_block_renderer
1077 {
1078 builder.modify_current_div(|el| {
1079 let content_range = parser::extract_code_block_content_range(
1080 &parsed_markdown.source()[range.clone()],
1081 );
1082 let content_range = content_range.start + range.start
1083 ..content_range.end + range.start;
1084
1085 let code = parsed_markdown.source()[content_range].to_string();
1086 let codeblock = render_copy_code_block_button(
1087 range.end,
1088 code,
1089 self.markdown.clone(),
1090 cx,
1091 );
1092 el.child(
1093 h_flex()
1094 .w_4()
1095 .absolute()
1096 .top_1p5()
1097 .right_1p5()
1098 .justify_end()
1099 .child(codeblock),
1100 )
1101 });
1102 }
1103
1104 if let CodeBlockRenderer::Default {
1105 copy_button_on_hover: true,
1106 ..
1107 } = &self.code_block_renderer
1108 {
1109 builder.modify_current_div(|el| {
1110 let content_range = parser::extract_code_block_content_range(
1111 &parsed_markdown.source()[range.clone()],
1112 );
1113 let content_range = content_range.start + range.start
1114 ..content_range.end + range.start;
1115
1116 let code = parsed_markdown.source()[content_range].to_string();
1117 let codeblock = render_copy_code_block_button(
1118 range.end,
1119 code,
1120 self.markdown.clone(),
1121 cx,
1122 );
1123 el.child(
1124 h_flex()
1125 .w_4()
1126 .absolute()
1127 .top_0()
1128 .right_0()
1129 .justify_end()
1130 .visible_on_hover("code_block")
1131 .child(codeblock),
1132 )
1133 });
1134 }
1135
1136 // Pop the parent container.
1137 builder.pop_div();
1138 }
1139 MarkdownTagEnd::HtmlBlock => builder.pop_div(),
1140 MarkdownTagEnd::List(_) => {
1141 builder.pop_list();
1142 builder.pop_div();
1143 }
1144 MarkdownTagEnd::Item => {
1145 builder.pop_div();
1146 builder.pop_div();
1147 }
1148 MarkdownTagEnd::Emphasis => builder.pop_text_style(),
1149 MarkdownTagEnd::Strong => builder.pop_text_style(),
1150 MarkdownTagEnd::Strikethrough => builder.pop_text_style(),
1151 MarkdownTagEnd::Link => {
1152 if builder.code_block_stack.is_empty() {
1153 builder.pop_text_style()
1154 }
1155 }
1156 MarkdownTagEnd::Table => {
1157 builder.pop_div();
1158 builder.pop_div();
1159 builder.table_alignments.clear();
1160 }
1161 MarkdownTagEnd::TableHead => {
1162 builder.pop_div();
1163 builder.pop_text_style();
1164 }
1165 MarkdownTagEnd::TableRow => {
1166 builder.pop_div();
1167 }
1168 MarkdownTagEnd::TableCell => {
1169 builder.pop_div();
1170 }
1171 _ => log::debug!("unsupported markdown tag end: {:?}", tag),
1172 },
1173 MarkdownEvent::Text => {
1174 builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
1175 }
1176 MarkdownEvent::SubstitutedText(text) => {
1177 builder.push_text(text, range.clone());
1178 }
1179 MarkdownEvent::Code => {
1180 builder.push_text_style(self.style.inline_code.clone());
1181 builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
1182 builder.pop_text_style();
1183 }
1184 MarkdownEvent::Html => {
1185 let html = &parsed_markdown.source[range.clone()];
1186 if html.starts_with("<!--") {
1187 builder.html_comment = true;
1188 }
1189 if html.trim_end().ends_with("-->") {
1190 builder.html_comment = false;
1191 continue;
1192 }
1193 if builder.html_comment {
1194 continue;
1195 }
1196 builder.push_text(html, range.clone());
1197 }
1198 MarkdownEvent::InlineHtml => {
1199 builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
1200 }
1201 MarkdownEvent::Rule => {
1202 builder.push_div(
1203 div()
1204 .border_b_1()
1205 .my_2()
1206 .border_color(self.style.rule_color),
1207 range,
1208 markdown_end,
1209 );
1210 builder.pop_div()
1211 }
1212 MarkdownEvent::SoftBreak => builder.push_text(" ", range.clone()),
1213 MarkdownEvent::HardBreak => builder.push_text("\n", range.clone()),
1214 _ => log::debug!("unsupported markdown event {:?}", event),
1215 }
1216 }
1217 if self.style.code_block_overflow_x_scroll {
1218 let code_block_ids = code_block_ids;
1219 self.markdown.update(cx, move |markdown, _| {
1220 markdown.retain_code_block_scroll_handles(&code_block_ids);
1221 });
1222 } else {
1223 self.markdown
1224 .update(cx, |markdown, _| markdown.clear_code_block_scroll_handles());
1225 }
1226 let mut rendered_markdown = builder.build();
1227 let child_layout_id = rendered_markdown.element.request_layout(window, cx);
1228 let layout_id = window.request_layout(gpui::Style::default(), [child_layout_id], cx);
1229 (layout_id, rendered_markdown)
1230 }
1231
1232 fn prepaint(
1233 &mut self,
1234 _id: Option<&GlobalElementId>,
1235 _inspector_id: Option<&gpui::InspectorElementId>,
1236 bounds: Bounds<Pixels>,
1237 rendered_markdown: &mut Self::RequestLayoutState,
1238 window: &mut Window,
1239 cx: &mut App,
1240 ) -> Self::PrepaintState {
1241 let focus_handle = self.markdown.read(cx).focus_handle.clone();
1242 window.set_focus_handle(&focus_handle, cx);
1243 window.set_view_id(self.markdown.entity_id());
1244
1245 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1246 rendered_markdown.element.prepaint(window, cx);
1247 self.autoscroll(&rendered_markdown.text, window, cx);
1248 hitbox
1249 }
1250
1251 fn paint(
1252 &mut self,
1253 _id: Option<&GlobalElementId>,
1254 _inspector_id: Option<&gpui::InspectorElementId>,
1255 bounds: Bounds<Pixels>,
1256 rendered_markdown: &mut Self::RequestLayoutState,
1257 hitbox: &mut Self::PrepaintState,
1258 window: &mut Window,
1259 cx: &mut App,
1260 ) {
1261 let mut context = KeyContext::default();
1262 context.add("Markdown");
1263 window.set_key_context(context);
1264 window.on_action(std::any::TypeId::of::<crate::Copy>(), {
1265 let entity = self.markdown.clone();
1266 let text = rendered_markdown.text.clone();
1267 move |_, phase, window, cx| {
1268 let text = text.clone();
1269 if phase == DispatchPhase::Bubble {
1270 entity.update(cx, move |this, cx| this.copy(&text, window, cx))
1271 }
1272 }
1273 });
1274 window.on_action(std::any::TypeId::of::<crate::CopyAsMarkdown>(), {
1275 let entity = self.markdown.clone();
1276 move |_, phase, window, cx| {
1277 if phase == DispatchPhase::Bubble {
1278 entity.update(cx, move |this, cx| this.copy_as_markdown(window, cx))
1279 }
1280 }
1281 });
1282
1283 self.paint_mouse_listeners(hitbox, &rendered_markdown.text, window, cx);
1284 rendered_markdown.element.paint(window, cx);
1285 self.paint_selection(bounds, &rendered_markdown.text, window, cx);
1286 }
1287}
1288
1289fn apply_heading_style(
1290 mut heading: Div,
1291 level: pulldown_cmark::HeadingLevel,
1292 custom_styles: Option<&HeadingLevelStyles>,
1293) -> Div {
1294 heading = match level {
1295 pulldown_cmark::HeadingLevel::H1 => heading.text_3xl(),
1296 pulldown_cmark::HeadingLevel::H2 => heading.text_2xl(),
1297 pulldown_cmark::HeadingLevel::H3 => heading.text_xl(),
1298 pulldown_cmark::HeadingLevel::H4 => heading.text_lg(),
1299 pulldown_cmark::HeadingLevel::H5 => heading.text_base(),
1300 pulldown_cmark::HeadingLevel::H6 => heading.text_sm(),
1301 };
1302
1303 if let Some(styles) = custom_styles {
1304 let style_opt = match level {
1305 pulldown_cmark::HeadingLevel::H1 => &styles.h1,
1306 pulldown_cmark::HeadingLevel::H2 => &styles.h2,
1307 pulldown_cmark::HeadingLevel::H3 => &styles.h3,
1308 pulldown_cmark::HeadingLevel::H4 => &styles.h4,
1309 pulldown_cmark::HeadingLevel::H5 => &styles.h5,
1310 pulldown_cmark::HeadingLevel::H6 => &styles.h6,
1311 };
1312
1313 if let Some(style) = style_opt {
1314 heading.style().text = Some(style.clone());
1315 }
1316 }
1317
1318 heading
1319}
1320
1321fn render_copy_code_block_button(
1322 id: usize,
1323 code: String,
1324 markdown: Entity<Markdown>,
1325 cx: &App,
1326) -> impl IntoElement {
1327 let id = ElementId::named_usize("copy-markdown-code", id);
1328 let was_copied = markdown.read(cx).copied_code_blocks.contains(&id);
1329 IconButton::new(
1330 id.clone(),
1331 if was_copied {
1332 IconName::Check
1333 } else {
1334 IconName::Copy
1335 },
1336 )
1337 .icon_color(Color::Muted)
1338 .icon_size(IconSize::Small)
1339 .style(ButtonStyle::Filled)
1340 .shape(ui::IconButtonShape::Square)
1341 .tooltip(Tooltip::text("Copy"))
1342 .on_click({
1343 let markdown = markdown;
1344 move |_event, _window, cx| {
1345 let id = id.clone();
1346 markdown.update(cx, |this, cx| {
1347 this.copied_code_blocks.insert(id.clone());
1348
1349 cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));
1350
1351 cx.spawn(async move |this, cx| {
1352 cx.background_executor().timer(Duration::from_secs(2)).await;
1353
1354 cx.update(|cx| {
1355 this.update(cx, |this, cx| {
1356 this.copied_code_blocks.remove(&id);
1357 cx.notify();
1358 })
1359 })
1360 .ok();
1361 })
1362 .detach();
1363 });
1364 }
1365 })
1366}
1367
1368impl IntoElement for MarkdownElement {
1369 type Element = Self;
1370
1371 fn into_element(self) -> Self::Element {
1372 self
1373 }
1374}
1375
1376pub enum AnyDiv {
1377 Div(Div),
1378 Stateful(Stateful<Div>),
1379}
1380
1381impl AnyDiv {
1382 fn into_any_element(self) -> AnyElement {
1383 match self {
1384 Self::Div(div) => div.into_any_element(),
1385 Self::Stateful(div) => div.into_any_element(),
1386 }
1387 }
1388}
1389
1390impl From<Div> for AnyDiv {
1391 fn from(value: Div) -> Self {
1392 Self::Div(value)
1393 }
1394}
1395
1396impl From<Stateful<Div>> for AnyDiv {
1397 fn from(value: Stateful<Div>) -> Self {
1398 Self::Stateful(value)
1399 }
1400}
1401
1402impl Styled for AnyDiv {
1403 fn style(&mut self) -> &mut StyleRefinement {
1404 match self {
1405 Self::Div(div) => div.style(),
1406 Self::Stateful(div) => div.style(),
1407 }
1408 }
1409}
1410
1411impl ParentElement for AnyDiv {
1412 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1413 match self {
1414 Self::Div(div) => div.extend(elements),
1415 Self::Stateful(div) => div.extend(elements),
1416 }
1417 }
1418}
1419
1420struct MarkdownElementBuilder {
1421 div_stack: Vec<AnyDiv>,
1422 rendered_lines: Vec<RenderedLine>,
1423 pending_line: PendingLine,
1424 rendered_links: Vec<RenderedLink>,
1425 current_source_index: usize,
1426 html_comment: bool,
1427 base_text_style: TextStyle,
1428 text_style_stack: Vec<TextStyleRefinement>,
1429 code_block_stack: Vec<Option<Arc<Language>>>,
1430 list_stack: Vec<ListStackEntry>,
1431 table_alignments: Vec<Alignment>,
1432 syntax_theme: Arc<SyntaxTheme>,
1433}
1434
1435#[derive(Default)]
1436struct PendingLine {
1437 text: String,
1438 runs: Vec<TextRun>,
1439 source_mappings: Vec<SourceMapping>,
1440}
1441
1442struct ListStackEntry {
1443 bullet_index: Option<u64>,
1444}
1445
1446impl MarkdownElementBuilder {
1447 fn new(base_text_style: TextStyle, syntax_theme: Arc<SyntaxTheme>) -> Self {
1448 Self {
1449 div_stack: vec![div().debug_selector(|| "inner".into()).into()],
1450 rendered_lines: Vec::new(),
1451 pending_line: PendingLine::default(),
1452 rendered_links: Vec::new(),
1453 current_source_index: 0,
1454 html_comment: false,
1455 base_text_style,
1456 text_style_stack: Vec::new(),
1457 code_block_stack: Vec::new(),
1458 list_stack: Vec::new(),
1459 table_alignments: Vec::new(),
1460 syntax_theme,
1461 }
1462 }
1463
1464 fn push_text_style(&mut self, style: TextStyleRefinement) {
1465 self.text_style_stack.push(style);
1466 }
1467
1468 fn text_style(&self) -> TextStyle {
1469 let mut style = self.base_text_style.clone();
1470 for refinement in &self.text_style_stack {
1471 style.refine(refinement);
1472 }
1473 style
1474 }
1475
1476 fn pop_text_style(&mut self) {
1477 self.text_style_stack.pop();
1478 }
1479
1480 fn push_div(&mut self, div: impl Into<AnyDiv>, range: &Range<usize>, markdown_end: usize) {
1481 let mut div = div.into();
1482 self.flush_text();
1483
1484 if range.start == 0 {
1485 // Remove the top margin on the first element.
1486 div.style().refine(&StyleRefinement {
1487 margin: gpui::EdgesRefinement {
1488 top: Some(Length::Definite(px(0.).into())),
1489 left: None,
1490 right: None,
1491 bottom: None,
1492 },
1493 ..Default::default()
1494 });
1495 }
1496
1497 if range.end == markdown_end {
1498 div.style().refine(&StyleRefinement {
1499 margin: gpui::EdgesRefinement {
1500 top: None,
1501 left: None,
1502 right: None,
1503 bottom: Some(Length::Definite(rems(0.).into())),
1504 },
1505 ..Default::default()
1506 });
1507 }
1508
1509 self.div_stack.push(div);
1510 }
1511
1512 fn modify_current_div(&mut self, f: impl FnOnce(AnyDiv) -> AnyDiv) {
1513 self.flush_text();
1514 if let Some(div) = self.div_stack.pop() {
1515 self.div_stack.push(f(div));
1516 }
1517 }
1518
1519 fn pop_div(&mut self) {
1520 self.flush_text();
1521 let div = self.div_stack.pop().unwrap().into_any_element();
1522 self.div_stack.last_mut().unwrap().extend(iter::once(div));
1523 }
1524
1525 fn push_list(&mut self, bullet_index: Option<u64>) {
1526 self.list_stack.push(ListStackEntry { bullet_index });
1527 }
1528
1529 fn next_bullet_index(&mut self) -> Option<u64> {
1530 self.list_stack.last_mut().and_then(|entry| {
1531 let item_index = entry.bullet_index.as_mut()?;
1532 *item_index += 1;
1533 Some(*item_index - 1)
1534 })
1535 }
1536
1537 fn pop_list(&mut self) {
1538 self.list_stack.pop();
1539 }
1540
1541 fn push_code_block(&mut self, language: Option<Arc<Language>>) {
1542 self.code_block_stack.push(language);
1543 }
1544
1545 fn pop_code_block(&mut self) {
1546 self.code_block_stack.pop();
1547 }
1548
1549 fn push_link(&mut self, destination_url: SharedString, source_range: Range<usize>) {
1550 self.rendered_links.push(RenderedLink {
1551 source_range,
1552 destination_url,
1553 });
1554 }
1555
1556 fn push_text(&mut self, text: &str, source_range: Range<usize>) {
1557 self.pending_line.source_mappings.push(SourceMapping {
1558 rendered_index: self.pending_line.text.len(),
1559 source_index: source_range.start,
1560 });
1561 self.pending_line.text.push_str(text);
1562 self.current_source_index = source_range.end;
1563
1564 if let Some(Some(language)) = self.code_block_stack.last() {
1565 let mut offset = 0;
1566 for (range, highlight_id) in language.highlight_text(&Rope::from(text), 0..text.len()) {
1567 if range.start > offset {
1568 self.pending_line
1569 .runs
1570 .push(self.text_style().to_run(range.start - offset));
1571 }
1572
1573 let mut run_style = self.text_style();
1574 if let Some(highlight) = highlight_id.style(&self.syntax_theme) {
1575 run_style = run_style.highlight(highlight);
1576 }
1577 self.pending_line.runs.push(run_style.to_run(range.len()));
1578 offset = range.end;
1579 }
1580
1581 if offset < text.len() {
1582 self.pending_line
1583 .runs
1584 .push(self.text_style().to_run(text.len() - offset));
1585 }
1586 } else {
1587 self.pending_line
1588 .runs
1589 .push(self.text_style().to_run(text.len()));
1590 }
1591 }
1592
1593 fn trim_trailing_newline(&mut self) {
1594 if self.pending_line.text.ends_with('\n') {
1595 self.pending_line
1596 .text
1597 .truncate(self.pending_line.text.len() - 1);
1598 self.pending_line.runs.last_mut().unwrap().len -= 1;
1599 self.current_source_index -= 1;
1600 }
1601 }
1602
1603 fn flush_text(&mut self) {
1604 let line = mem::take(&mut self.pending_line);
1605 if line.text.is_empty() {
1606 return;
1607 }
1608
1609 let text = StyledText::new(line.text).with_runs(line.runs);
1610 self.rendered_lines.push(RenderedLine {
1611 layout: text.layout().clone(),
1612 source_mappings: line.source_mappings,
1613 source_end: self.current_source_index,
1614 });
1615 self.div_stack.last_mut().unwrap().extend([text.into_any()]);
1616 }
1617
1618 fn build(mut self) -> RenderedMarkdown {
1619 debug_assert_eq!(self.div_stack.len(), 1);
1620 self.flush_text();
1621 RenderedMarkdown {
1622 element: self.div_stack.pop().unwrap().into_any_element(),
1623 text: RenderedText {
1624 lines: self.rendered_lines.into(),
1625 links: self.rendered_links.into(),
1626 },
1627 }
1628 }
1629}
1630
1631struct RenderedLine {
1632 layout: TextLayout,
1633 source_mappings: Vec<SourceMapping>,
1634 source_end: usize,
1635}
1636
1637impl RenderedLine {
1638 fn rendered_index_for_source_index(&self, source_index: usize) -> usize {
1639 if source_index >= self.source_end {
1640 return self.layout.len();
1641 }
1642
1643 let mapping = match self
1644 .source_mappings
1645 .binary_search_by_key(&source_index, |probe| probe.source_index)
1646 {
1647 Ok(ix) => &self.source_mappings[ix],
1648 Err(ix) => &self.source_mappings[ix - 1],
1649 };
1650 mapping.rendered_index + (source_index - mapping.source_index)
1651 }
1652
1653 fn source_index_for_rendered_index(&self, rendered_index: usize) -> usize {
1654 if rendered_index >= self.layout.len() {
1655 return self.source_end;
1656 }
1657
1658 let mapping = match self
1659 .source_mappings
1660 .binary_search_by_key(&rendered_index, |probe| probe.rendered_index)
1661 {
1662 Ok(ix) => &self.source_mappings[ix],
1663 Err(ix) => &self.source_mappings[ix - 1],
1664 };
1665 mapping.source_index + (rendered_index - mapping.rendered_index)
1666 }
1667
1668 fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
1669 let line_rendered_index;
1670 let out_of_bounds;
1671 match self.layout.index_for_position(position) {
1672 Ok(ix) => {
1673 line_rendered_index = ix;
1674 out_of_bounds = false;
1675 }
1676 Err(ix) => {
1677 line_rendered_index = ix;
1678 out_of_bounds = true;
1679 }
1680 };
1681 let source_index = self.source_index_for_rendered_index(line_rendered_index);
1682 if out_of_bounds {
1683 Err(source_index)
1684 } else {
1685 Ok(source_index)
1686 }
1687 }
1688}
1689
1690#[derive(Copy, Clone, Debug, Default)]
1691struct SourceMapping {
1692 rendered_index: usize,
1693 source_index: usize,
1694}
1695
1696pub struct RenderedMarkdown {
1697 element: AnyElement,
1698 text: RenderedText,
1699}
1700
1701#[derive(Clone)]
1702struct RenderedText {
1703 lines: Rc<[RenderedLine]>,
1704 links: Rc<[RenderedLink]>,
1705}
1706
1707#[derive(Debug, Clone, Eq, PartialEq)]
1708struct RenderedLink {
1709 source_range: Range<usize>,
1710 destination_url: SharedString,
1711}
1712
1713impl RenderedText {
1714 fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
1715 let mut lines = self.lines.iter().peekable();
1716
1717 while let Some(line) = lines.next() {
1718 let line_bounds = line.layout.bounds();
1719 if position.y > line_bounds.bottom() {
1720 if let Some(next_line) = lines.peek()
1721 && position.y < next_line.layout.bounds().top()
1722 {
1723 return Err(line.source_end);
1724 }
1725
1726 continue;
1727 }
1728
1729 return line.source_index_for_position(position);
1730 }
1731
1732 Err(self.lines.last().map_or(0, |line| line.source_end))
1733 }
1734
1735 fn position_for_source_index(&self, source_index: usize) -> Option<(Point<Pixels>, Pixels)> {
1736 for line in self.lines.iter() {
1737 let line_source_start = line.source_mappings.first().unwrap().source_index;
1738 if source_index < line_source_start {
1739 break;
1740 } else if source_index > line.source_end {
1741 continue;
1742 } else {
1743 let line_height = line.layout.line_height();
1744 let rendered_index_within_line = line.rendered_index_for_source_index(source_index);
1745 let position = line.layout.position_for_index(rendered_index_within_line)?;
1746 return Some((position, line_height));
1747 }
1748 }
1749 None
1750 }
1751
1752 fn surrounding_word_range(&self, source_index: usize) -> Range<usize> {
1753 for line in self.lines.iter() {
1754 if source_index > line.source_end {
1755 continue;
1756 }
1757
1758 let line_rendered_start = line.source_mappings.first().unwrap().rendered_index;
1759 let rendered_index_in_line =
1760 line.rendered_index_for_source_index(source_index) - line_rendered_start;
1761 let text = line.layout.text();
1762 let previous_space = if let Some(idx) = text[0..rendered_index_in_line].rfind(' ') {
1763 idx + ' '.len_utf8()
1764 } else {
1765 0
1766 };
1767 let next_space = if let Some(idx) = text[rendered_index_in_line..].find(' ') {
1768 rendered_index_in_line + idx
1769 } else {
1770 text.len()
1771 };
1772
1773 return line.source_index_for_rendered_index(line_rendered_start + previous_space)
1774 ..line.source_index_for_rendered_index(line_rendered_start + next_space);
1775 }
1776
1777 source_index..source_index
1778 }
1779
1780 fn surrounding_line_range(&self, source_index: usize) -> Range<usize> {
1781 for line in self.lines.iter() {
1782 if source_index > line.source_end {
1783 continue;
1784 }
1785 let line_source_start = line.source_mappings.first().unwrap().source_index;
1786 return line_source_start..line.source_end;
1787 }
1788
1789 source_index..source_index
1790 }
1791
1792 fn text_for_range(&self, range: Range<usize>) -> String {
1793 let mut ret = vec![];
1794
1795 for line in self.lines.iter() {
1796 if range.start > line.source_end {
1797 continue;
1798 }
1799 let line_source_start = line.source_mappings.first().unwrap().source_index;
1800 if range.end < line_source_start {
1801 break;
1802 }
1803
1804 let text = line.layout.text();
1805
1806 let start = if range.start < line_source_start {
1807 0
1808 } else {
1809 line.rendered_index_for_source_index(range.start)
1810 };
1811 let end = if range.end > line.source_end {
1812 line.rendered_index_for_source_index(line.source_end)
1813 } else {
1814 line.rendered_index_for_source_index(range.end)
1815 }
1816 .min(text.len());
1817
1818 ret.push(text[start..end].to_string());
1819 }
1820 ret.join("\n")
1821 }
1822
1823 fn link_for_position(&self, position: Point<Pixels>) -> Option<&RenderedLink> {
1824 let source_index = self.source_index_for_position(position).ok()?;
1825 self.links
1826 .iter()
1827 .find(|link| link.source_range.contains(&source_index))
1828 }
1829}
1830
1831#[cfg(test)]
1832mod tests {
1833 use super::*;
1834 use gpui::{TestAppContext, size};
1835
1836 #[gpui::test]
1837 fn test_mappings(cx: &mut TestAppContext) {
1838 // Formatting.
1839 assert_mappings(
1840 &render_markdown("He*l*lo", cx),
1841 vec![vec![(0, 0), (1, 1), (2, 3), (3, 5), (4, 6), (5, 7)]],
1842 );
1843
1844 // Multiple lines.
1845 assert_mappings(
1846 &render_markdown("Hello\n\nWorld", cx),
1847 vec![
1848 vec![(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)],
1849 vec![(0, 7), (1, 8), (2, 9), (3, 10), (4, 11), (5, 12)],
1850 ],
1851 );
1852
1853 // Multi-byte characters.
1854 assert_mappings(
1855 &render_markdown("αβγ\n\nδεζ", cx),
1856 vec![
1857 vec![(0, 0), (2, 2), (4, 4), (6, 6)],
1858 vec![(0, 8), (2, 10), (4, 12), (6, 14)],
1859 ],
1860 );
1861
1862 // Smart quotes.
1863 assert_mappings(&render_markdown("\"", cx), vec![vec![(0, 0), (3, 1)]]);
1864 assert_mappings(
1865 &render_markdown("\"hey\"", cx),
1866 vec![vec![(0, 0), (3, 1), (4, 2), (5, 3), (6, 4), (9, 5)]],
1867 );
1868
1869 // HTML Comments are ignored
1870 assert_mappings(
1871 &render_markdown(
1872 "<!--\nrdoc-file=string.c\n- str.intern -> symbol\n- str.to_sym -> symbol\n-->\nReturns",
1873 cx,
1874 ),
1875 vec![vec![
1876 (0, 78),
1877 (1, 79),
1878 (2, 80),
1879 (3, 81),
1880 (4, 82),
1881 (5, 83),
1882 (6, 84),
1883 ]],
1884 );
1885 }
1886
1887 fn render_markdown(markdown: &str, cx: &mut TestAppContext) -> RenderedText {
1888 struct TestWindow;
1889
1890 impl Render for TestWindow {
1891 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1892 div()
1893 }
1894 }
1895
1896 let (_, cx) = cx.add_window_view(|_, _| TestWindow);
1897 let markdown = cx.new(|cx| Markdown::new(markdown.to_string().into(), None, None, cx));
1898 cx.run_until_parked();
1899 let (rendered, _) = cx.draw(
1900 Default::default(),
1901 size(px(600.0), px(600.0)),
1902 |_window, _cx| MarkdownElement::new(markdown, MarkdownStyle::default()),
1903 );
1904 rendered.text
1905 }
1906
1907 #[test]
1908 fn test_escape() {
1909 assert_eq!(Markdown::escape("hello `world`"), "hello \\`world\\`");
1910 assert_eq!(
1911 Markdown::escape("hello\n cool world"),
1912 "hello\n\ncool world"
1913 );
1914 }
1915
1916 #[track_caller]
1917 fn assert_mappings(rendered: &RenderedText, expected: Vec<Vec<(usize, usize)>>) {
1918 assert_eq!(rendered.lines.len(), expected.len(), "line count mismatch");
1919 for (line_ix, line_mappings) in expected.into_iter().enumerate() {
1920 let line = &rendered.lines[line_ix];
1921
1922 assert!(
1923 line.source_mappings.windows(2).all(|mappings| {
1924 mappings[0].source_index < mappings[1].source_index
1925 && mappings[0].rendered_index < mappings[1].rendered_index
1926 }),
1927 "line {} has duplicate mappings: {:?}",
1928 line_ix,
1929 line.source_mappings
1930 );
1931
1932 for (rendered_ix, source_ix) in line_mappings {
1933 assert_eq!(
1934 line.source_index_for_rendered_index(rendered_ix),
1935 source_ix,
1936 "line {}, rendered_ix {}",
1937 line_ix,
1938 rendered_ix
1939 );
1940
1941 assert_eq!(
1942 line.rendered_index_for_source_index(source_ix),
1943 rendered_ix,
1944 "line {}, source_ix {}",
1945 line_ix,
1946 source_ix
1947 );
1948 }
1949 }
1950 }
1951}