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