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