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