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