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