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