1pub mod parser;
2
3use std::collections::{HashMap, HashSet};
4use std::iter;
5use std::mem;
6use std::ops::Range;
7use std::rc::Rc;
8use std::sync::Arc;
9
10use gpui::{
11 actions, point, quad, AnyElement, App, Bounds, ClipboardItem, CursorStyle, DispatchPhase,
12 Edges, Entity, FocusHandle, Focusable, FontStyle, FontWeight, GlobalElementId, Hitbox, Hsla,
13 KeyContext, Length, MouseDownEvent, MouseEvent, MouseMoveEvent, MouseUpEvent, Point, Render,
14 Stateful, StrikethroughStyle, StyleRefinement, StyledText, Task, TextLayout, TextRun,
15 TextStyle, TextStyleRefinement,
16};
17use language::{Language, LanguageRegistry, Rope};
18use parser::{parse_links_only, parse_markdown, MarkdownEvent, MarkdownTag, MarkdownTagEnd};
19use pulldown_cmark::Alignment;
20use theme::SyntaxTheme;
21use ui::{prelude::*, Tooltip};
22use util::{ResultExt, TryFutureExt};
23
24use crate::parser::CodeBlockKind;
25
26#[derive(Clone)]
27pub struct MarkdownStyle {
28 pub base_text_style: TextStyle,
29 pub code_block: StyleRefinement,
30 pub code_block_overflow_x_scroll: bool,
31 pub inline_code: TextStyleRefinement,
32 pub block_quote: TextStyleRefinement,
33 pub link: TextStyleRefinement,
34 pub rule_color: Hsla,
35 pub block_quote_border_color: Hsla,
36 pub syntax: Arc<SyntaxTheme>,
37 pub selection_background_color: Hsla,
38 pub heading: StyleRefinement,
39 pub table_overflow_x_scroll: bool,
40}
41
42impl Default for MarkdownStyle {
43 fn default() -> Self {
44 Self {
45 base_text_style: Default::default(),
46 code_block: Default::default(),
47 code_block_overflow_x_scroll: false,
48 inline_code: Default::default(),
49 block_quote: Default::default(),
50 link: Default::default(),
51 rule_color: Default::default(),
52 block_quote_border_color: Default::default(),
53 syntax: Arc::new(SyntaxTheme::default()),
54 selection_background_color: Default::default(),
55 heading: Default::default(),
56 table_overflow_x_scroll: false,
57 }
58 }
59}
60
61pub struct Markdown {
62 source: SharedString,
63 selection: Selection,
64 pressed_link: Option<RenderedLink>,
65 autoscroll_request: Option<usize>,
66 style: MarkdownStyle,
67 parsed_markdown: ParsedMarkdown,
68 should_reparse: bool,
69 pending_parse: Option<Task<Option<()>>>,
70 focus_handle: FocusHandle,
71 language_registry: Option<Arc<LanguageRegistry>>,
72 fallback_code_block_language: Option<String>,
73 open_url: Option<Box<dyn Fn(SharedString, &mut Window, &mut App)>>,
74 options: Options,
75 copied_code_blocks: HashSet<ElementId>,
76}
77
78#[derive(Debug)]
79struct Options {
80 parse_links_only: bool,
81 copy_code_block_buttons: bool,
82}
83
84actions!(markdown, [Copy]);
85
86impl Markdown {
87 pub fn new(
88 source: SharedString,
89 style: MarkdownStyle,
90 language_registry: Option<Arc<LanguageRegistry>>,
91 fallback_code_block_language: Option<String>,
92 cx: &mut Context<Self>,
93 ) -> Self {
94 let focus_handle = cx.focus_handle();
95 let mut this = Self {
96 source,
97 selection: Selection::default(),
98 pressed_link: None,
99 autoscroll_request: None,
100 style,
101 should_reparse: false,
102 parsed_markdown: ParsedMarkdown::default(),
103 pending_parse: None,
104 focus_handle,
105 language_registry,
106 fallback_code_block_language,
107 options: Options {
108 parse_links_only: false,
109 copy_code_block_buttons: true,
110 },
111 open_url: None,
112 copied_code_blocks: HashSet::new(),
113 };
114 this.parse(cx);
115 this
116 }
117
118 pub fn open_url(
119 self,
120 open_url: impl Fn(SharedString, &mut Window, &mut App) + 'static,
121 ) -> Self {
122 Self {
123 open_url: Some(Box::new(open_url)),
124 ..self
125 }
126 }
127
128 pub fn new_text(source: SharedString, style: MarkdownStyle, cx: &mut Context<Self>) -> Self {
129 let focus_handle = cx.focus_handle();
130 let mut this = Self {
131 source,
132 selection: Selection::default(),
133 pressed_link: None,
134 autoscroll_request: None,
135 style,
136 should_reparse: false,
137 parsed_markdown: ParsedMarkdown::default(),
138 pending_parse: None,
139 focus_handle,
140 language_registry: None,
141 fallback_code_block_language: None,
142 options: Options {
143 parse_links_only: true,
144 copy_code_block_buttons: true,
145 },
146 open_url: None,
147 copied_code_blocks: HashSet::new(),
148 };
149 this.parse(cx);
150 this
151 }
152
153 pub fn source(&self) -> &str {
154 &self.source
155 }
156
157 pub fn append(&mut self, text: &str, cx: &mut Context<Self>) {
158 self.source = SharedString::new(self.source.to_string() + text);
159 self.parse(cx);
160 }
161
162 pub fn reset(&mut self, source: SharedString, cx: &mut Context<Self>) {
163 if source == self.source() {
164 return;
165 }
166 self.source = source;
167 self.selection = Selection::default();
168 self.autoscroll_request = None;
169 self.pending_parse = None;
170 self.should_reparse = false;
171 self.parsed_markdown = ParsedMarkdown::default();
172 self.parse(cx);
173 }
174
175 pub fn parsed_markdown(&self) -> &ParsedMarkdown {
176 &self.parsed_markdown
177 }
178
179 fn copy(&self, text: &RenderedText, _: &mut Window, cx: &mut Context<Self>) {
180 if self.selection.end <= self.selection.start {
181 return;
182 }
183 let text = text.text_for_range(self.selection.start..self.selection.end);
184 cx.write_to_clipboard(ClipboardItem::new_string(text));
185 }
186
187 fn parse(&mut self, cx: &mut Context<Self>) {
188 if self.source.is_empty() {
189 return;
190 }
191
192 if self.pending_parse.is_some() {
193 self.should_reparse = true;
194 return;
195 }
196
197 let source = self.source.clone();
198 let parse_text_only = self.options.parse_links_only;
199 let language_registry = self.language_registry.clone();
200 let fallback = self.fallback_code_block_language.clone();
201 let parsed = cx.background_spawn(async move {
202 if parse_text_only {
203 return anyhow::Ok(ParsedMarkdown {
204 events: Arc::from(parse_links_only(source.as_ref())),
205 source,
206 languages: HashMap::default(),
207 });
208 }
209 let (events, language_names) = parse_markdown(&source);
210 let mut languages = HashMap::with_capacity(language_names.len());
211 for name in language_names {
212 if let Some(registry) = language_registry.as_ref() {
213 let language = if !name.is_empty() {
214 registry.language_for_name(&name)
215 } else if let Some(fallback) = &fallback {
216 registry.language_for_name(fallback)
217 } else {
218 continue;
219 };
220 if let Ok(language) = language.await {
221 languages.insert(name, language);
222 }
223 }
224 }
225 anyhow::Ok(ParsedMarkdown {
226 source,
227 events: Arc::from(events),
228 languages,
229 })
230 });
231
232 self.should_reparse = false;
233 self.pending_parse = Some(cx.spawn(|this, mut cx| {
234 async move {
235 let parsed = parsed.await?;
236 this.update(&mut cx, |this, cx| {
237 this.parsed_markdown = parsed;
238 this.pending_parse.take();
239 if this.should_reparse {
240 this.parse(cx);
241 }
242 cx.notify();
243 })
244 .ok();
245 anyhow::Ok(())
246 }
247 .log_err()
248 }));
249 }
250
251 pub fn copy_code_block_buttons(mut self, should_copy: bool) -> Self {
252 self.options.copy_code_block_buttons = should_copy;
253 self
254 }
255}
256
257impl Render for Markdown {
258 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
259 MarkdownElement::new(cx.entity().clone(), self.style.clone())
260 }
261}
262
263impl Focusable for Markdown {
264 fn focus_handle(&self, _cx: &App) -> FocusHandle {
265 self.focus_handle.clone()
266 }
267}
268
269#[derive(Copy, Clone, Default, Debug)]
270struct Selection {
271 start: usize,
272 end: usize,
273 reversed: bool,
274 pending: bool,
275}
276
277impl Selection {
278 fn set_head(&mut self, head: usize) {
279 if head < self.tail() {
280 if !self.reversed {
281 self.end = self.start;
282 self.reversed = true;
283 }
284 self.start = head;
285 } else {
286 if self.reversed {
287 self.start = self.end;
288 self.reversed = false;
289 }
290 self.end = head;
291 }
292 }
293
294 fn tail(&self) -> usize {
295 if self.reversed {
296 self.end
297 } else {
298 self.start
299 }
300 }
301}
302
303#[derive(Default)]
304pub struct ParsedMarkdown {
305 source: SharedString,
306 events: Arc<[(Range<usize>, MarkdownEvent)]>,
307 languages: HashMap<SharedString, Arc<Language>>,
308}
309
310impl ParsedMarkdown {
311 pub fn source(&self) -> &SharedString {
312 &self.source
313 }
314
315 pub fn events(&self) -> &Arc<[(Range<usize>, MarkdownEvent)]> {
316 &self.events
317 }
318}
319
320pub struct MarkdownElement {
321 markdown: Entity<Markdown>,
322 style: MarkdownStyle,
323}
324
325impl MarkdownElement {
326 fn new(markdown: Entity<Markdown>, style: MarkdownStyle) -> Self {
327 Self { markdown, style }
328 }
329
330 fn paint_selection(
331 &self,
332 bounds: Bounds<Pixels>,
333 rendered_text: &RenderedText,
334 window: &mut Window,
335 cx: &mut App,
336 ) {
337 let selection = self.markdown.read(cx).selection;
338 let selection_start = rendered_text.position_for_source_index(selection.start);
339 let selection_end = rendered_text.position_for_source_index(selection.end);
340
341 if let Some(((start_position, start_line_height), (end_position, end_line_height))) =
342 selection_start.zip(selection_end)
343 {
344 if start_position.y == end_position.y {
345 window.paint_quad(quad(
346 Bounds::from_corners(
347 start_position,
348 point(end_position.x, end_position.y + end_line_height),
349 ),
350 Pixels::ZERO,
351 self.style.selection_background_color,
352 Edges::default(),
353 Hsla::transparent_black(),
354 ));
355 } else {
356 window.paint_quad(quad(
357 Bounds::from_corners(
358 start_position,
359 point(bounds.right(), start_position.y + start_line_height),
360 ),
361 Pixels::ZERO,
362 self.style.selection_background_color,
363 Edges::default(),
364 Hsla::transparent_black(),
365 ));
366
367 if end_position.y > start_position.y + start_line_height {
368 window.paint_quad(quad(
369 Bounds::from_corners(
370 point(bounds.left(), start_position.y + start_line_height),
371 point(bounds.right(), end_position.y),
372 ),
373 Pixels::ZERO,
374 self.style.selection_background_color,
375 Edges::default(),
376 Hsla::transparent_black(),
377 ));
378 }
379
380 window.paint_quad(quad(
381 Bounds::from_corners(
382 point(bounds.left(), end_position.y),
383 point(end_position.x, end_position.y + end_line_height),
384 ),
385 Pixels::ZERO,
386 self.style.selection_background_color,
387 Edges::default(),
388 Hsla::transparent_black(),
389 ));
390 }
391 }
392 }
393
394 fn paint_mouse_listeners(
395 &self,
396 hitbox: &Hitbox,
397 rendered_text: &RenderedText,
398 window: &mut Window,
399 cx: &mut App,
400 ) {
401 let is_hovering_link = hitbox.is_hovered(window)
402 && !self.markdown.read(cx).selection.pending
403 && rendered_text
404 .link_for_position(window.mouse_position())
405 .is_some();
406
407 if is_hovering_link {
408 window.set_cursor_style(CursorStyle::PointingHand, hitbox);
409 } else {
410 window.set_cursor_style(CursorStyle::IBeam, hitbox);
411 }
412
413 self.on_mouse_event(window, cx, {
414 let rendered_text = rendered_text.clone();
415 let hitbox = hitbox.clone();
416 move |markdown, event: &MouseDownEvent, phase, window, cx| {
417 if hitbox.is_hovered(window) {
418 if phase.bubble() {
419 if let Some(link) = rendered_text.link_for_position(event.position) {
420 markdown.pressed_link = Some(link.clone());
421 } else {
422 let source_index =
423 match rendered_text.source_index_for_position(event.position) {
424 Ok(ix) | Err(ix) => ix,
425 };
426 let range = if event.click_count == 2 {
427 rendered_text.surrounding_word_range(source_index)
428 } else if event.click_count == 3 {
429 rendered_text.surrounding_line_range(source_index)
430 } else {
431 source_index..source_index
432 };
433 markdown.selection = Selection {
434 start: range.start,
435 end: range.end,
436 reversed: false,
437 pending: true,
438 };
439 window.focus(&markdown.focus_handle);
440 window.prevent_default();
441 }
442
443 cx.notify();
444 }
445 } else if phase.capture() {
446 markdown.selection = Selection::default();
447 markdown.pressed_link = None;
448 cx.notify();
449 }
450 }
451 });
452 self.on_mouse_event(window, cx, {
453 let rendered_text = rendered_text.clone();
454 let hitbox = hitbox.clone();
455 let was_hovering_link = is_hovering_link;
456 move |markdown, event: &MouseMoveEvent, phase, window, cx| {
457 if phase.capture() {
458 return;
459 }
460
461 if markdown.selection.pending {
462 let source_index = match rendered_text.source_index_for_position(event.position)
463 {
464 Ok(ix) | Err(ix) => ix,
465 };
466 markdown.selection.set_head(source_index);
467 markdown.autoscroll_request = Some(source_index);
468 cx.notify();
469 } else {
470 let is_hovering_link = hitbox.is_hovered(window)
471 && rendered_text.link_for_position(event.position).is_some();
472 if is_hovering_link != was_hovering_link {
473 cx.notify();
474 }
475 }
476 }
477 });
478 self.on_mouse_event(window, cx, {
479 let rendered_text = rendered_text.clone();
480 move |markdown, event: &MouseUpEvent, phase, window, cx| {
481 if phase.bubble() {
482 if let Some(pressed_link) = markdown.pressed_link.take() {
483 if Some(&pressed_link) == rendered_text.link_for_position(event.position) {
484 if let Some(open_url) = markdown.open_url.as_mut() {
485 open_url(pressed_link.destination_url, window, cx);
486 } else {
487 cx.open_url(&pressed_link.destination_url);
488 }
489 }
490 }
491 } else if markdown.selection.pending {
492 markdown.selection.pending = false;
493 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
494 {
495 let text = rendered_text
496 .text_for_range(markdown.selection.start..markdown.selection.end);
497 cx.write_to_primary(ClipboardItem::new_string(text))
498 }
499 cx.notify();
500 }
501 }
502 });
503 }
504
505 fn autoscroll(
506 &self,
507 rendered_text: &RenderedText,
508 window: &mut Window,
509 cx: &mut App,
510 ) -> Option<()> {
511 let autoscroll_index = self
512 .markdown
513 .update(cx, |markdown, _| markdown.autoscroll_request.take())?;
514 let (position, line_height) = rendered_text.position_for_source_index(autoscroll_index)?;
515
516 let text_style = self.style.base_text_style.clone();
517 let font_id = window.text_system().resolve_font(&text_style.font());
518 let font_size = text_style.font_size.to_pixels(window.rem_size());
519 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
520 window.request_autoscroll(Bounds::from_corners(
521 point(position.x - 3. * em_width, position.y - 3. * line_height),
522 point(position.x + 3. * em_width, position.y + 3. * line_height),
523 ));
524 Some(())
525 }
526
527 fn on_mouse_event<T: MouseEvent>(
528 &self,
529 window: &mut Window,
530 _cx: &mut App,
531 mut f: impl 'static
532 + FnMut(&mut Markdown, &T, DispatchPhase, &mut Window, &mut Context<Markdown>),
533 ) {
534 window.on_mouse_event({
535 let markdown = self.markdown.downgrade();
536 move |event, phase, window, cx| {
537 markdown
538 .update(cx, |markdown, cx| f(markdown, event, phase, window, cx))
539 .log_err();
540 }
541 });
542 }
543}
544
545impl Element for MarkdownElement {
546 type RequestLayoutState = RenderedMarkdown;
547 type PrepaintState = Hitbox;
548
549 fn id(&self) -> Option<ElementId> {
550 None
551 }
552
553 fn request_layout(
554 &mut self,
555 _id: Option<&GlobalElementId>,
556 window: &mut Window,
557 cx: &mut App,
558 ) -> (gpui::LayoutId, Self::RequestLayoutState) {
559 let mut builder = MarkdownElementBuilder::new(
560 self.style.base_text_style.clone(),
561 self.style.syntax.clone(),
562 );
563 let parsed_markdown = &self.markdown.read(cx).parsed_markdown;
564 let markdown_end = if let Some(last) = parsed_markdown.events.last() {
565 last.0.end
566 } else {
567 0
568 };
569 for (range, event) in parsed_markdown.events.iter() {
570 match event {
571 MarkdownEvent::Start(tag) => {
572 match tag {
573 MarkdownTag::Paragraph => {
574 builder.push_div(
575 div().mb_2().line_height(rems(1.3)),
576 range,
577 markdown_end,
578 );
579 }
580 MarkdownTag::Heading { level, .. } => {
581 let mut heading = div().mb_2();
582 heading = match level {
583 pulldown_cmark::HeadingLevel::H1 => heading.text_3xl(),
584 pulldown_cmark::HeadingLevel::H2 => heading.text_2xl(),
585 pulldown_cmark::HeadingLevel::H3 => heading.text_xl(),
586 pulldown_cmark::HeadingLevel::H4 => heading.text_lg(),
587 _ => heading,
588 };
589 heading.style().refine(&self.style.heading);
590 builder.push_text_style(
591 self.style.heading.text_style().clone().unwrap_or_default(),
592 );
593 builder.push_div(heading, range, markdown_end);
594 }
595 MarkdownTag::BlockQuote => {
596 builder.push_text_style(self.style.block_quote.clone());
597 builder.push_div(
598 div()
599 .pl_4()
600 .mb_2()
601 .border_l_4()
602 .border_color(self.style.block_quote_border_color),
603 range,
604 markdown_end,
605 );
606 }
607 MarkdownTag::CodeBlock(kind) => {
608 let language = if let CodeBlockKind::Fenced(language) = kind {
609 parsed_markdown.languages.get(language).cloned()
610 } else {
611 None
612 };
613
614 let mut code_block = div()
615 .id(("code-block", range.start))
616 .rounded_lg()
617 .map(|mut code_block| {
618 if self.style.code_block_overflow_x_scroll {
619 code_block.style().restrict_scroll_to_axis = Some(true);
620 code_block.flex().overflow_x_scroll()
621 } else {
622 code_block.w_full()
623 }
624 });
625 code_block.style().refine(&self.style.code_block);
626 if let Some(code_block_text_style) = &self.style.code_block.text {
627 builder.push_text_style(code_block_text_style.to_owned());
628 }
629 builder.push_code_block(language);
630 builder.push_div(code_block, range, markdown_end);
631 }
632 MarkdownTag::HtmlBlock => builder.push_div(div(), range, markdown_end),
633 MarkdownTag::List(bullet_index) => {
634 builder.push_list(*bullet_index);
635 builder.push_div(div().pl_4(), range, markdown_end);
636 }
637 MarkdownTag::Item => {
638 let bullet = if let Some(bullet_index) = builder.next_bullet_index() {
639 format!("{}.", bullet_index)
640 } else {
641 "•".to_string()
642 };
643 builder.push_div(
644 div()
645 .mb_1()
646 .h_flex()
647 .items_start()
648 .gap_1()
649 .line_height(rems(1.3))
650 .child(bullet),
651 range,
652 markdown_end,
653 );
654 // Without `w_0`, text doesn't wrap to the width of the container.
655 builder.push_div(div().flex_1().w_0(), range, markdown_end);
656 }
657 MarkdownTag::Emphasis => builder.push_text_style(TextStyleRefinement {
658 font_style: Some(FontStyle::Italic),
659 ..Default::default()
660 }),
661 MarkdownTag::Strong => builder.push_text_style(TextStyleRefinement {
662 font_weight: Some(FontWeight::BOLD),
663 ..Default::default()
664 }),
665 MarkdownTag::Strikethrough => {
666 builder.push_text_style(TextStyleRefinement {
667 strikethrough: Some(StrikethroughStyle {
668 thickness: px(1.),
669 color: None,
670 }),
671 ..Default::default()
672 })
673 }
674 MarkdownTag::Link { dest_url, .. } => {
675 if builder.code_block_stack.is_empty() {
676 builder.push_link(dest_url.clone(), range.clone());
677 builder.push_text_style(self.style.link.clone())
678 }
679 }
680 MarkdownTag::MetadataBlock(_) => {}
681 MarkdownTag::Table(alignments) => {
682 builder.table_alignments = alignments.clone();
683 builder.push_div(
684 div()
685 .id(("table", range.start))
686 .flex()
687 .border_1()
688 .border_color(cx.theme().colors().border)
689 .rounded_md()
690 .when(self.style.table_overflow_x_scroll, |mut table| {
691 table.style().restrict_scroll_to_axis = Some(true);
692 table.overflow_x_scroll()
693 }),
694 range,
695 markdown_end,
696 );
697 // This inner `v_flex` is so the table rows will stack vertically without disrupting the `overflow_x_scroll`.
698 builder.push_div(div().v_flex().flex_grow(), range, markdown_end);
699 }
700 MarkdownTag::TableHead => {
701 builder.push_div(
702 div()
703 .flex()
704 .justify_between()
705 .border_b_1()
706 .border_color(cx.theme().colors().border),
707 range,
708 markdown_end,
709 );
710 builder.push_text_style(TextStyleRefinement {
711 font_weight: Some(FontWeight::BOLD),
712 ..Default::default()
713 });
714 }
715 MarkdownTag::TableRow => {
716 builder.push_div(
717 div().h_flex().justify_between().px_1().py_0p5(),
718 range,
719 markdown_end,
720 );
721 }
722 MarkdownTag::TableCell => {
723 let column_count = builder.table_alignments.len();
724
725 builder.push_div(
726 div()
727 .flex()
728 .px_1()
729 .w(relative(1. / column_count as f32))
730 .truncate(),
731 range,
732 markdown_end,
733 );
734 }
735 _ => log::error!("unsupported markdown tag {:?}", tag),
736 }
737 }
738 MarkdownEvent::End(tag) => match tag {
739 MarkdownTagEnd::Paragraph => {
740 builder.pop_div();
741 }
742 MarkdownTagEnd::Heading(_) => {
743 builder.pop_div();
744 builder.pop_text_style()
745 }
746 MarkdownTagEnd::BlockQuote(_kind) => {
747 builder.pop_text_style();
748 builder.pop_div()
749 }
750 MarkdownTagEnd::CodeBlock => {
751 builder.trim_trailing_newline();
752
753 if self.markdown.read(cx).options.copy_code_block_buttons {
754 builder.flush_text();
755 builder.modify_current_div(|el| {
756 let id =
757 ElementId::NamedInteger("copy-markdown-code".into(), range.end);
758 let was_copied =
759 self.markdown.read(cx).copied_code_blocks.contains(&id);
760 let copy_button = div().absolute().top_1().right_1().w_5().child(
761 IconButton::new(
762 id.clone(),
763 if was_copied {
764 IconName::Check
765 } else {
766 IconName::Copy
767 },
768 )
769 .icon_color(Color::Muted)
770 .shape(ui::IconButtonShape::Square)
771 .tooltip(Tooltip::text("Copy Code"))
772 .on_click({
773 let id = id.clone();
774 let markdown = self.markdown.clone();
775 let code = without_fences(
776 parsed_markdown.source()[range.clone()].trim(),
777 )
778 .to_string();
779 move |_event, _window, cx| {
780 markdown.update(cx, |this, cx| {
781 this.copied_code_blocks.insert(id.clone());
782
783 cx.write_to_clipboard(ClipboardItem::new_string(
784 code.clone(),
785 ));
786 });
787 }
788 }),
789 );
790
791 el.child(copy_button)
792 });
793 }
794
795 builder.pop_div();
796 builder.pop_code_block();
797 if self.style.code_block.text.is_some() {
798 builder.pop_text_style();
799 }
800 }
801 MarkdownTagEnd::HtmlBlock => builder.pop_div(),
802 MarkdownTagEnd::List(_) => {
803 builder.pop_list();
804 builder.pop_div();
805 }
806 MarkdownTagEnd::Item => {
807 builder.pop_div();
808 builder.pop_div();
809 }
810 MarkdownTagEnd::Emphasis => builder.pop_text_style(),
811 MarkdownTagEnd::Strong => builder.pop_text_style(),
812 MarkdownTagEnd::Strikethrough => builder.pop_text_style(),
813 MarkdownTagEnd::Link => {
814 if builder.code_block_stack.is_empty() {
815 builder.pop_text_style()
816 }
817 }
818 MarkdownTagEnd::Table => {
819 builder.pop_div();
820 builder.pop_div();
821 builder.table_alignments.clear();
822 }
823 MarkdownTagEnd::TableHead => {
824 builder.pop_div();
825 builder.pop_text_style();
826 }
827 MarkdownTagEnd::TableRow => {
828 builder.pop_div();
829 }
830 MarkdownTagEnd::TableCell => {
831 builder.pop_div();
832 }
833 _ => log::error!("unsupported markdown tag end: {:?}", tag),
834 },
835 MarkdownEvent::Text(parsed) => {
836 builder.push_text(parsed, range.start);
837 }
838 MarkdownEvent::Code => {
839 builder.push_text_style(self.style.inline_code.clone());
840 builder.push_text(&parsed_markdown.source[range.clone()], range.start);
841 builder.pop_text_style();
842 }
843 MarkdownEvent::Html => {
844 builder.push_text(&parsed_markdown.source[range.clone()], range.start);
845 }
846 MarkdownEvent::InlineHtml => {
847 builder.push_text(&parsed_markdown.source[range.clone()], range.start);
848 }
849 MarkdownEvent::Rule => {
850 builder.push_div(
851 div()
852 .border_b_1()
853 .my_2()
854 .border_color(self.style.rule_color),
855 range,
856 markdown_end,
857 );
858 builder.pop_div()
859 }
860 MarkdownEvent::SoftBreak => builder.push_text(" ", range.start),
861 MarkdownEvent::HardBreak => builder.push_text("\n", range.start),
862 _ => log::error!("unsupported markdown event {:?}", event),
863 }
864 }
865 let mut rendered_markdown = builder.build();
866 let child_layout_id = rendered_markdown.element.request_layout(window, cx);
867 let layout_id = window.request_layout(gpui::Style::default(), [child_layout_id], cx);
868 (layout_id, rendered_markdown)
869 }
870
871 fn prepaint(
872 &mut self,
873 _id: Option<&GlobalElementId>,
874 bounds: Bounds<Pixels>,
875 rendered_markdown: &mut Self::RequestLayoutState,
876 window: &mut Window,
877 cx: &mut App,
878 ) -> Self::PrepaintState {
879 let focus_handle = self.markdown.read(cx).focus_handle.clone();
880 window.set_focus_handle(&focus_handle, cx);
881
882 let hitbox = window.insert_hitbox(bounds, false);
883 rendered_markdown.element.prepaint(window, cx);
884 self.autoscroll(&rendered_markdown.text, window, cx);
885 hitbox
886 }
887
888 fn paint(
889 &mut self,
890 _id: Option<&GlobalElementId>,
891 bounds: Bounds<Pixels>,
892 rendered_markdown: &mut Self::RequestLayoutState,
893 hitbox: &mut Self::PrepaintState,
894 window: &mut Window,
895 cx: &mut App,
896 ) {
897 let mut context = KeyContext::default();
898 context.add("Markdown");
899 window.set_key_context(context);
900 let entity = self.markdown.clone();
901 window.on_action(std::any::TypeId::of::<crate::Copy>(), {
902 let text = rendered_markdown.text.clone();
903 move |_, phase, window, cx| {
904 let text = text.clone();
905 if phase == DispatchPhase::Bubble {
906 entity.update(cx, move |this, cx| this.copy(&text, window, cx))
907 }
908 }
909 });
910
911 self.paint_mouse_listeners(hitbox, &rendered_markdown.text, window, cx);
912 rendered_markdown.element.paint(window, cx);
913 self.paint_selection(bounds, &rendered_markdown.text, window, cx);
914 }
915}
916
917impl IntoElement for MarkdownElement {
918 type Element = Self;
919
920 fn into_element(self) -> Self::Element {
921 self
922 }
923}
924
925enum AnyDiv {
926 Div(Div),
927 Stateful(Stateful<Div>),
928}
929
930impl AnyDiv {
931 fn into_any_element(self) -> AnyElement {
932 match self {
933 Self::Div(div) => div.into_any_element(),
934 Self::Stateful(div) => div.into_any_element(),
935 }
936 }
937}
938
939impl From<Div> for AnyDiv {
940 fn from(value: Div) -> Self {
941 Self::Div(value)
942 }
943}
944
945impl From<Stateful<Div>> for AnyDiv {
946 fn from(value: Stateful<Div>) -> Self {
947 Self::Stateful(value)
948 }
949}
950
951impl Styled for AnyDiv {
952 fn style(&mut self) -> &mut StyleRefinement {
953 match self {
954 Self::Div(div) => div.style(),
955 Self::Stateful(div) => div.style(),
956 }
957 }
958}
959
960impl ParentElement for AnyDiv {
961 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
962 match self {
963 Self::Div(div) => div.extend(elements),
964 Self::Stateful(div) => div.extend(elements),
965 }
966 }
967}
968
969struct MarkdownElementBuilder {
970 div_stack: Vec<AnyDiv>,
971 rendered_lines: Vec<RenderedLine>,
972 pending_line: PendingLine,
973 rendered_links: Vec<RenderedLink>,
974 current_source_index: usize,
975 base_text_style: TextStyle,
976 text_style_stack: Vec<TextStyleRefinement>,
977 code_block_stack: Vec<Option<Arc<Language>>>,
978 list_stack: Vec<ListStackEntry>,
979 table_alignments: Vec<Alignment>,
980 syntax_theme: Arc<SyntaxTheme>,
981}
982
983#[derive(Default)]
984struct PendingLine {
985 text: String,
986 runs: Vec<TextRun>,
987 source_mappings: Vec<SourceMapping>,
988}
989
990struct ListStackEntry {
991 bullet_index: Option<u64>,
992}
993
994impl MarkdownElementBuilder {
995 fn new(base_text_style: TextStyle, syntax_theme: Arc<SyntaxTheme>) -> Self {
996 Self {
997 div_stack: vec![div().debug_selector(|| "inner".into()).into()],
998 rendered_lines: Vec::new(),
999 pending_line: PendingLine::default(),
1000 rendered_links: Vec::new(),
1001 current_source_index: 0,
1002 base_text_style,
1003 text_style_stack: Vec::new(),
1004 code_block_stack: Vec::new(),
1005 list_stack: Vec::new(),
1006 table_alignments: Vec::new(),
1007 syntax_theme,
1008 }
1009 }
1010
1011 fn push_text_style(&mut self, style: TextStyleRefinement) {
1012 self.text_style_stack.push(style);
1013 }
1014
1015 fn text_style(&self) -> TextStyle {
1016 let mut style = self.base_text_style.clone();
1017 for refinement in &self.text_style_stack {
1018 style.refine(refinement);
1019 }
1020 style
1021 }
1022
1023 fn pop_text_style(&mut self) {
1024 self.text_style_stack.pop();
1025 }
1026
1027 fn push_div(&mut self, div: impl Into<AnyDiv>, range: &Range<usize>, markdown_end: usize) {
1028 let mut div = div.into();
1029 self.flush_text();
1030
1031 if range.start == 0 {
1032 // Remove the top margin on the first element.
1033 div.style().refine(&StyleRefinement {
1034 margin: gpui::EdgesRefinement {
1035 top: Some(Length::Definite(px(0.).into())),
1036 left: None,
1037 right: None,
1038 bottom: None,
1039 },
1040 ..Default::default()
1041 });
1042 }
1043
1044 if range.end == markdown_end {
1045 div.style().refine(&StyleRefinement {
1046 margin: gpui::EdgesRefinement {
1047 top: None,
1048 left: None,
1049 right: None,
1050 bottom: Some(Length::Definite(rems(0.).into())),
1051 },
1052 ..Default::default()
1053 });
1054 }
1055
1056 self.div_stack.push(div);
1057 }
1058
1059 fn modify_current_div(&mut self, f: impl FnOnce(AnyDiv) -> AnyDiv) {
1060 self.flush_text();
1061 if let Some(div) = self.div_stack.pop() {
1062 self.div_stack.push(f(div));
1063 }
1064 }
1065
1066 fn pop_div(&mut self) {
1067 self.flush_text();
1068 let div = self.div_stack.pop().unwrap().into_any_element();
1069 self.div_stack.last_mut().unwrap().extend(iter::once(div));
1070 }
1071
1072 fn push_list(&mut self, bullet_index: Option<u64>) {
1073 self.list_stack.push(ListStackEntry { bullet_index });
1074 }
1075
1076 fn next_bullet_index(&mut self) -> Option<u64> {
1077 self.list_stack.last_mut().and_then(|entry| {
1078 let item_index = entry.bullet_index.as_mut()?;
1079 *item_index += 1;
1080 Some(*item_index - 1)
1081 })
1082 }
1083
1084 fn pop_list(&mut self) {
1085 self.list_stack.pop();
1086 }
1087
1088 fn push_code_block(&mut self, language: Option<Arc<Language>>) {
1089 self.code_block_stack.push(language);
1090 }
1091
1092 fn pop_code_block(&mut self) {
1093 self.code_block_stack.pop();
1094 }
1095
1096 fn push_link(&mut self, destination_url: SharedString, source_range: Range<usize>) {
1097 self.rendered_links.push(RenderedLink {
1098 source_range,
1099 destination_url,
1100 });
1101 }
1102
1103 fn push_text(&mut self, text: &str, source_index: usize) {
1104 self.pending_line.source_mappings.push(SourceMapping {
1105 rendered_index: self.pending_line.text.len(),
1106 source_index,
1107 });
1108 self.pending_line.text.push_str(text);
1109 self.current_source_index = source_index + text.len();
1110
1111 if let Some(Some(language)) = self.code_block_stack.last() {
1112 let mut offset = 0;
1113 for (range, highlight_id) in language.highlight_text(&Rope::from(text), 0..text.len()) {
1114 if range.start > offset {
1115 self.pending_line
1116 .runs
1117 .push(self.text_style().to_run(range.start - offset));
1118 }
1119
1120 let mut run_style = self.text_style();
1121 if let Some(highlight) = highlight_id.style(&self.syntax_theme) {
1122 run_style = run_style.highlight(highlight);
1123 }
1124 self.pending_line.runs.push(run_style.to_run(range.len()));
1125 offset = range.end;
1126 }
1127
1128 if offset < text.len() {
1129 self.pending_line
1130 .runs
1131 .push(self.text_style().to_run(text.len() - offset));
1132 }
1133 } else {
1134 self.pending_line
1135 .runs
1136 .push(self.text_style().to_run(text.len()));
1137 }
1138 }
1139
1140 fn trim_trailing_newline(&mut self) {
1141 if self.pending_line.text.ends_with('\n') {
1142 self.pending_line
1143 .text
1144 .truncate(self.pending_line.text.len() - 1);
1145 self.pending_line.runs.last_mut().unwrap().len -= 1;
1146 self.current_source_index -= 1;
1147 }
1148 }
1149
1150 fn flush_text(&mut self) {
1151 let line = mem::take(&mut self.pending_line);
1152 if line.text.is_empty() {
1153 return;
1154 }
1155
1156 let text = StyledText::new(line.text).with_runs(line.runs);
1157 self.rendered_lines.push(RenderedLine {
1158 layout: text.layout().clone(),
1159 source_mappings: line.source_mappings,
1160 source_end: self.current_source_index,
1161 });
1162 self.div_stack.last_mut().unwrap().extend([text.into_any()]);
1163 }
1164
1165 fn build(mut self) -> RenderedMarkdown {
1166 debug_assert_eq!(self.div_stack.len(), 1);
1167 self.flush_text();
1168 RenderedMarkdown {
1169 element: self.div_stack.pop().unwrap().into_any_element(),
1170 text: RenderedText {
1171 lines: self.rendered_lines.into(),
1172 links: self.rendered_links.into(),
1173 },
1174 }
1175 }
1176}
1177
1178struct RenderedLine {
1179 layout: TextLayout,
1180 source_mappings: Vec<SourceMapping>,
1181 source_end: usize,
1182}
1183
1184impl RenderedLine {
1185 fn rendered_index_for_source_index(&self, source_index: usize) -> usize {
1186 let mapping = match self
1187 .source_mappings
1188 .binary_search_by_key(&source_index, |probe| probe.source_index)
1189 {
1190 Ok(ix) => &self.source_mappings[ix],
1191 Err(ix) => &self.source_mappings[ix - 1],
1192 };
1193 mapping.rendered_index + (source_index - mapping.source_index)
1194 }
1195
1196 fn source_index_for_rendered_index(&self, rendered_index: usize) -> usize {
1197 let mapping = match self
1198 .source_mappings
1199 .binary_search_by_key(&rendered_index, |probe| probe.rendered_index)
1200 {
1201 Ok(ix) => &self.source_mappings[ix],
1202 Err(ix) => &self.source_mappings[ix - 1],
1203 };
1204 mapping.source_index + (rendered_index - mapping.rendered_index)
1205 }
1206
1207 fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
1208 let line_rendered_index;
1209 let out_of_bounds;
1210 match self.layout.index_for_position(position) {
1211 Ok(ix) => {
1212 line_rendered_index = ix;
1213 out_of_bounds = false;
1214 }
1215 Err(ix) => {
1216 line_rendered_index = ix;
1217 out_of_bounds = true;
1218 }
1219 };
1220 let source_index = self.source_index_for_rendered_index(line_rendered_index);
1221 if out_of_bounds {
1222 Err(source_index)
1223 } else {
1224 Ok(source_index)
1225 }
1226 }
1227}
1228
1229#[derive(Copy, Clone, Debug, Default)]
1230struct SourceMapping {
1231 rendered_index: usize,
1232 source_index: usize,
1233}
1234
1235pub struct RenderedMarkdown {
1236 element: AnyElement,
1237 text: RenderedText,
1238}
1239
1240#[derive(Clone)]
1241struct RenderedText {
1242 lines: Rc<[RenderedLine]>,
1243 links: Rc<[RenderedLink]>,
1244}
1245
1246#[derive(Clone, Eq, PartialEq)]
1247struct RenderedLink {
1248 source_range: Range<usize>,
1249 destination_url: SharedString,
1250}
1251
1252impl RenderedText {
1253 fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
1254 let mut lines = self.lines.iter().peekable();
1255
1256 while let Some(line) = lines.next() {
1257 let line_bounds = line.layout.bounds();
1258 if position.y > line_bounds.bottom() {
1259 if let Some(next_line) = lines.peek() {
1260 if position.y < next_line.layout.bounds().top() {
1261 return Err(line.source_end);
1262 }
1263 }
1264
1265 continue;
1266 }
1267
1268 return line.source_index_for_position(position);
1269 }
1270
1271 Err(self.lines.last().map_or(0, |line| line.source_end))
1272 }
1273
1274 fn position_for_source_index(&self, source_index: usize) -> Option<(Point<Pixels>, Pixels)> {
1275 for line in self.lines.iter() {
1276 let line_source_start = line.source_mappings.first().unwrap().source_index;
1277 if source_index < line_source_start {
1278 break;
1279 } else if source_index > line.source_end {
1280 continue;
1281 } else {
1282 let line_height = line.layout.line_height();
1283 let rendered_index_within_line = line.rendered_index_for_source_index(source_index);
1284 let position = line.layout.position_for_index(rendered_index_within_line)?;
1285 return Some((position, line_height));
1286 }
1287 }
1288 None
1289 }
1290
1291 fn surrounding_word_range(&self, source_index: usize) -> Range<usize> {
1292 for line in self.lines.iter() {
1293 if source_index > line.source_end {
1294 continue;
1295 }
1296
1297 let line_rendered_start = line.source_mappings.first().unwrap().rendered_index;
1298 let rendered_index_in_line =
1299 line.rendered_index_for_source_index(source_index) - line_rendered_start;
1300 let text = line.layout.text();
1301 let previous_space = if let Some(idx) = text[0..rendered_index_in_line].rfind(' ') {
1302 idx + ' '.len_utf8()
1303 } else {
1304 0
1305 };
1306 let next_space = if let Some(idx) = text[rendered_index_in_line..].find(' ') {
1307 rendered_index_in_line + idx
1308 } else {
1309 text.len()
1310 };
1311
1312 return line.source_index_for_rendered_index(line_rendered_start + previous_space)
1313 ..line.source_index_for_rendered_index(line_rendered_start + next_space);
1314 }
1315
1316 source_index..source_index
1317 }
1318
1319 fn surrounding_line_range(&self, source_index: usize) -> Range<usize> {
1320 for line in self.lines.iter() {
1321 if source_index > line.source_end {
1322 continue;
1323 }
1324 let line_source_start = line.source_mappings.first().unwrap().source_index;
1325 return line_source_start..line.source_end;
1326 }
1327
1328 source_index..source_index
1329 }
1330
1331 fn text_for_range(&self, range: Range<usize>) -> String {
1332 let mut ret = vec![];
1333
1334 for line in self.lines.iter() {
1335 if range.start > line.source_end {
1336 continue;
1337 }
1338 let line_source_start = line.source_mappings.first().unwrap().source_index;
1339 if range.end < line_source_start {
1340 break;
1341 }
1342
1343 let text = line.layout.text();
1344
1345 let start = if range.start < line_source_start {
1346 0
1347 } else {
1348 line.rendered_index_for_source_index(range.start)
1349 };
1350 let end = if range.end > line.source_end {
1351 line.rendered_index_for_source_index(line.source_end)
1352 } else {
1353 line.rendered_index_for_source_index(range.end)
1354 }
1355 .min(text.len());
1356
1357 ret.push(text[start..end].to_string());
1358 }
1359 ret.join("\n")
1360 }
1361
1362 fn link_for_position(&self, position: Point<Pixels>) -> Option<&RenderedLink> {
1363 let source_index = self.source_index_for_position(position).ok()?;
1364 self.links
1365 .iter()
1366 .find(|link| link.source_range.contains(&source_index))
1367 }
1368}
1369
1370/// Some markdown blocks are indented, and others have e.g. ```rust … ``` around them.
1371/// If this block is fenced with backticks, strip them off (and the language name).
1372/// We use this when copying code blocks to the clipboard.
1373fn without_fences(mut markdown: &str) -> &str {
1374 if let Some(opening_backticks) = markdown.find("```") {
1375 markdown = &markdown[opening_backticks..];
1376
1377 // Trim off the next newline. This also trims off a language name if it's there.
1378 if let Some(newline) = markdown.find('\n') {
1379 markdown = &markdown[newline + 1..];
1380 }
1381 };
1382
1383 if let Some(closing_backticks) = markdown.rfind("```") {
1384 markdown = &markdown[..closing_backticks];
1385 };
1386
1387 markdown
1388}
1389
1390#[cfg(test)]
1391mod tests {
1392 use super::*;
1393
1394 #[test]
1395 fn test_without_fences() {
1396 let input = "```rust\nlet x = 5;\n```";
1397 assert_eq!(without_fences(input), "let x = 5;\n");
1398
1399 let input = " ```\nno language\n``` ";
1400 assert_eq!(without_fences(input), "no language\n");
1401
1402 let input = "plain text";
1403 assert_eq!(without_fences(input), "plain text");
1404
1405 let input = "```python\nprint('hello')\nprint('world')\n```";
1406 assert_eq!(without_fences(input), "print('hello')\nprint('world')\n");
1407 }
1408}