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