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