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