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