markdown.rs

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