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