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