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