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