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