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