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