markdown.rs

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