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 container_style: StyleRefinement,
  58    pub code_block: StyleRefinement,
  59    pub code_block_overflow_x_scroll: bool,
  60    pub inline_code: TextStyleRefinement,
  61    pub block_quote: TextStyleRefinement,
  62    pub link: TextStyleRefinement,
  63    pub link_callback: Option<LinkStyleCallback>,
  64    pub rule_color: Hsla,
  65    pub block_quote_border_color: Hsla,
  66    pub syntax: Arc<SyntaxTheme>,
  67    pub selection_background_color: Hsla,
  68    pub heading: StyleRefinement,
  69    pub heading_level_styles: Option<HeadingLevelStyles>,
  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            container_style: Default::default(),
  79            code_block: Default::default(),
  80            code_block_overflow_x_scroll: false,
  81            inline_code: Default::default(),
  82            block_quote: Default::default(),
  83            link: Default::default(),
  84            link_callback: None,
  85            rule_color: Default::default(),
  86            block_quote_border_color: Default::default(),
  87            syntax: Arc::new(SyntaxTheme::default()),
  88            selection_background_color: Default::default(),
  89            heading: Default::default(),
  90            heading_level_styles: None,
  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 Styled for MarkdownElement {
 754    fn style(&mut self) -> &mut StyleRefinement {
 755        &mut self.style.container_style
 756    }
 757}
 758
 759impl Element for MarkdownElement {
 760    type RequestLayoutState = RenderedMarkdown;
 761    type PrepaintState = Hitbox;
 762
 763    fn id(&self) -> Option<ElementId> {
 764        None
 765    }
 766
 767    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 768        None
 769    }
 770
 771    fn request_layout(
 772        &mut self,
 773        _id: Option<&GlobalElementId>,
 774        _inspector_id: Option<&gpui::InspectorElementId>,
 775        window: &mut Window,
 776        cx: &mut App,
 777    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
 778        let mut builder = MarkdownElementBuilder::new(
 779            &self.style.container_style,
 780            self.style.base_text_style.clone(),
 781            self.style.syntax.clone(),
 782        );
 783        let (parsed_markdown, images) = {
 784            let markdown = self.markdown.read(cx);
 785            (
 786                markdown.parsed_markdown.clone(),
 787                markdown.images_by_source_offset.clone(),
 788            )
 789        };
 790        let markdown_end = if let Some(last) = parsed_markdown.events.last() {
 791            last.0.end
 792        } else {
 793            0
 794        };
 795        let mut code_block_ids = HashSet::default();
 796
 797        let mut current_img_block_range: Option<Range<usize>> = None;
 798        for (range, event) in parsed_markdown.events.iter() {
 799            // Skip alt text for images that rendered
 800            if let Some(current_img_block_range) = &current_img_block_range
 801                && current_img_block_range.end > range.end
 802            {
 803                continue;
 804            }
 805
 806            match event {
 807                MarkdownEvent::Start(tag) => {
 808                    match tag {
 809                        MarkdownTag::Image { .. } => {
 810                            if let Some(image) = images.get(&range.start) {
 811                                current_img_block_range = Some(range.clone());
 812                                builder.modify_current_div(|el| {
 813                                    el.items_center()
 814                                        .flex()
 815                                        .flex_row()
 816                                        .child(img(image.clone()))
 817                                });
 818                            }
 819                        }
 820                        MarkdownTag::Paragraph => {
 821                            builder.push_div(
 822                                div().when(!self.style.height_is_multiple_of_line_height, |el| {
 823                                    el.mb_2().line_height(rems(1.3))
 824                                }),
 825                                range,
 826                                markdown_end,
 827                            );
 828                        }
 829                        MarkdownTag::Heading { level, .. } => {
 830                            let mut heading = div().mb_2();
 831
 832                            heading = apply_heading_style(
 833                                heading,
 834                                *level,
 835                                self.style.heading_level_styles.as_ref(),
 836                            );
 837
 838                            heading.style().refine(&self.style.heading);
 839
 840                            let text_style =
 841                                self.style.heading.text_style().clone().unwrap_or_default();
 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                                    if let Some(code_block_text_style) = &self.style.code_block.text
 936                                    {
 937                                        builder.push_text_style(code_block_text_style.to_owned());
 938                                    }
 939                                    builder.push_code_block(language);
 940                                    builder.push_div(code_block, range, markdown_end);
 941                                }
 942                                (CodeBlockRenderer::Custom { .. }, _) => {}
 943                            }
 944                        }
 945                        MarkdownTag::HtmlBlock => builder.push_div(div(), range, markdown_end),
 946                        MarkdownTag::List(bullet_index) => {
 947                            builder.push_list(*bullet_index);
 948                            builder.push_div(div().pl_4(), range, markdown_end);
 949                        }
 950                        MarkdownTag::Item => {
 951                            let bullet = if let Some(bullet_index) = builder.next_bullet_index() {
 952                                format!("{}.", bullet_index)
 953                            } else {
 954                                "".to_string()
 955                            };
 956                            builder.push_div(
 957                                div()
 958                                    .when(!self.style.height_is_multiple_of_line_height, |el| {
 959                                        el.mb_1().gap_1().line_height(rems(1.3))
 960                                    })
 961                                    .h_flex()
 962                                    .items_start()
 963                                    .child(bullet),
 964                                range,
 965                                markdown_end,
 966                            );
 967                            // Without `w_0`, text doesn't wrap to the width of the container.
 968                            builder.push_div(div().flex_1().w_0(), range, markdown_end);
 969                        }
 970                        MarkdownTag::Emphasis => builder.push_text_style(TextStyleRefinement {
 971                            font_style: Some(FontStyle::Italic),
 972                            ..Default::default()
 973                        }),
 974                        MarkdownTag::Strong => builder.push_text_style(TextStyleRefinement {
 975                            font_weight: Some(FontWeight::BOLD),
 976                            ..Default::default()
 977                        }),
 978                        MarkdownTag::Strikethrough => {
 979                            builder.push_text_style(TextStyleRefinement {
 980                                strikethrough: Some(StrikethroughStyle {
 981                                    thickness: px(1.),
 982                                    color: None,
 983                                }),
 984                                ..Default::default()
 985                            })
 986                        }
 987                        MarkdownTag::Link { dest_url, .. } => {
 988                            if builder.code_block_stack.is_empty() {
 989                                builder.push_link(dest_url.clone(), range.clone());
 990                                let style = self
 991                                    .style
 992                                    .link_callback
 993                                    .as_ref()
 994                                    .and_then(|callback| callback(dest_url, cx))
 995                                    .unwrap_or_else(|| self.style.link.clone());
 996                                builder.push_text_style(style)
 997                            }
 998                        }
 999                        MarkdownTag::MetadataBlock(_) => {}
1000                        MarkdownTag::Table(alignments) => {
1001                            builder.table_alignments = alignments.clone();
1002
1003                            builder.push_div(
1004                                div()
1005                                    .id(("table", range.start))
1006                                    .min_w_0()
1007                                    .size_full()
1008                                    .mb_2()
1009                                    .border_1()
1010                                    .border_color(cx.theme().colors().border)
1011                                    .rounded_sm()
1012                                    .overflow_hidden(),
1013                                range,
1014                                markdown_end,
1015                            );
1016                        }
1017                        MarkdownTag::TableHead => {
1018                            let column_count = builder.table_alignments.len();
1019
1020                            builder.push_div(
1021                                div()
1022                                    .grid()
1023                                    .grid_cols(column_count as u16)
1024                                    .bg(cx.theme().colors().title_bar_background),
1025                                range,
1026                                markdown_end,
1027                            );
1028                            builder.push_text_style(TextStyleRefinement {
1029                                font_weight: Some(FontWeight::SEMIBOLD),
1030                                ..Default::default()
1031                            });
1032                        }
1033                        MarkdownTag::TableRow => {
1034                            let column_count = builder.table_alignments.len();
1035
1036                            builder.push_div(
1037                                div().grid().grid_cols(column_count as u16),
1038                                range,
1039                                markdown_end,
1040                            );
1041                        }
1042                        MarkdownTag::TableCell => {
1043                            builder.push_div(
1044                                div()
1045                                    .min_w_0()
1046                                    .border(px(0.5))
1047                                    .border_color(cx.theme().colors().border)
1048                                    .px_1()
1049                                    .py_0p5(),
1050                                range,
1051                                markdown_end,
1052                            );
1053                        }
1054                        _ => log::debug!("unsupported markdown tag {:?}", tag),
1055                    }
1056                }
1057                MarkdownEvent::End(tag) => match tag {
1058                    MarkdownTagEnd::Image => {
1059                        current_img_block_range.take();
1060                    }
1061                    MarkdownTagEnd::Paragraph => {
1062                        builder.pop_div();
1063                    }
1064                    MarkdownTagEnd::Heading(_) => {
1065                        builder.pop_div();
1066                        builder.pop_text_style()
1067                    }
1068                    MarkdownTagEnd::BlockQuote(_kind) => {
1069                        builder.pop_text_style();
1070                        builder.pop_div()
1071                    }
1072                    MarkdownTagEnd::CodeBlock => {
1073                        builder.trim_trailing_newline();
1074
1075                        builder.pop_div();
1076                        builder.pop_code_block();
1077                        if self.style.code_block.text.is_some() {
1078                            builder.pop_text_style();
1079                        }
1080
1081                        if let CodeBlockRenderer::Default {
1082                            copy_button: true, ..
1083                        } = &self.code_block_renderer
1084                        {
1085                            builder.modify_current_div(|el| {
1086                                let content_range = parser::extract_code_block_content_range(
1087                                    &parsed_markdown.source()[range.clone()],
1088                                );
1089                                let content_range = content_range.start + range.start
1090                                    ..content_range.end + range.start;
1091
1092                                let code = parsed_markdown.source()[content_range].to_string();
1093                                let codeblock = render_copy_code_block_button(
1094                                    range.end,
1095                                    code,
1096                                    self.markdown.clone(),
1097                                    cx,
1098                                );
1099                                el.child(
1100                                    h_flex()
1101                                        .w_4()
1102                                        .absolute()
1103                                        .top_1p5()
1104                                        .right_1p5()
1105                                        .justify_end()
1106                                        .child(codeblock),
1107                                )
1108                            });
1109                        }
1110
1111                        if let CodeBlockRenderer::Default {
1112                            copy_button_on_hover: true,
1113                            ..
1114                        } = &self.code_block_renderer
1115                        {
1116                            builder.modify_current_div(|el| {
1117                                let content_range = parser::extract_code_block_content_range(
1118                                    &parsed_markdown.source()[range.clone()],
1119                                );
1120                                let content_range = content_range.start + range.start
1121                                    ..content_range.end + range.start;
1122
1123                                let code = parsed_markdown.source()[content_range].to_string();
1124                                let codeblock = render_copy_code_block_button(
1125                                    range.end,
1126                                    code,
1127                                    self.markdown.clone(),
1128                                    cx,
1129                                );
1130                                el.child(
1131                                    h_flex()
1132                                        .w_4()
1133                                        .absolute()
1134                                        .top_0()
1135                                        .right_0()
1136                                        .justify_end()
1137                                        .visible_on_hover("code_block")
1138                                        .child(codeblock),
1139                                )
1140                            });
1141                        }
1142
1143                        // Pop the parent container.
1144                        builder.pop_div();
1145                    }
1146                    MarkdownTagEnd::HtmlBlock => builder.pop_div(),
1147                    MarkdownTagEnd::List(_) => {
1148                        builder.pop_list();
1149                        builder.pop_div();
1150                    }
1151                    MarkdownTagEnd::Item => {
1152                        builder.pop_div();
1153                        builder.pop_div();
1154                    }
1155                    MarkdownTagEnd::Emphasis => builder.pop_text_style(),
1156                    MarkdownTagEnd::Strong => builder.pop_text_style(),
1157                    MarkdownTagEnd::Strikethrough => builder.pop_text_style(),
1158                    MarkdownTagEnd::Link => {
1159                        if builder.code_block_stack.is_empty() {
1160                            builder.pop_text_style()
1161                        }
1162                    }
1163                    MarkdownTagEnd::Table => {
1164                        builder.pop_div();
1165                        builder.table_alignments.clear();
1166                    }
1167                    MarkdownTagEnd::TableHead => {
1168                        builder.pop_div();
1169                        builder.pop_text_style();
1170                    }
1171                    MarkdownTagEnd::TableRow => {
1172                        builder.pop_div();
1173                    }
1174                    MarkdownTagEnd::TableCell => {
1175                        builder.pop_div();
1176                    }
1177                    _ => log::debug!("unsupported markdown tag end: {:?}", tag),
1178                },
1179                MarkdownEvent::Text => {
1180                    builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
1181                }
1182                MarkdownEvent::SubstitutedText(text) => {
1183                    builder.push_text(text, range.clone());
1184                }
1185                MarkdownEvent::Code => {
1186                    builder.push_text_style(self.style.inline_code.clone());
1187                    builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
1188                    builder.pop_text_style();
1189                }
1190                MarkdownEvent::Html => {
1191                    let html = &parsed_markdown.source[range.clone()];
1192                    if html.starts_with("<!--") {
1193                        builder.html_comment = true;
1194                    }
1195                    if html.trim_end().ends_with("-->") {
1196                        builder.html_comment = false;
1197                        continue;
1198                    }
1199                    if builder.html_comment {
1200                        continue;
1201                    }
1202                    builder.push_text(html, range.clone());
1203                }
1204                MarkdownEvent::InlineHtml => {
1205                    builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
1206                }
1207                MarkdownEvent::Rule => {
1208                    builder.push_div(
1209                        div()
1210                            .border_b_1()
1211                            .my_2()
1212                            .border_color(self.style.rule_color),
1213                        range,
1214                        markdown_end,
1215                    );
1216                    builder.pop_div()
1217                }
1218                MarkdownEvent::SoftBreak => builder.push_text(" ", range.clone()),
1219                MarkdownEvent::HardBreak => builder.push_text("\n", range.clone()),
1220                _ => log::debug!("unsupported markdown event {:?}", event),
1221            }
1222        }
1223        if self.style.code_block_overflow_x_scroll {
1224            let code_block_ids = code_block_ids;
1225            self.markdown.update(cx, move |markdown, _| {
1226                markdown.retain_code_block_scroll_handles(&code_block_ids);
1227            });
1228        } else {
1229            self.markdown
1230                .update(cx, |markdown, _| markdown.clear_code_block_scroll_handles());
1231        }
1232        let mut rendered_markdown = builder.build();
1233        let child_layout_id = rendered_markdown.element.request_layout(window, cx);
1234        let layout_id = window.request_layout(gpui::Style::default(), [child_layout_id], cx);
1235        (layout_id, rendered_markdown)
1236    }
1237
1238    fn prepaint(
1239        &mut self,
1240        _id: Option<&GlobalElementId>,
1241        _inspector_id: Option<&gpui::InspectorElementId>,
1242        bounds: Bounds<Pixels>,
1243        rendered_markdown: &mut Self::RequestLayoutState,
1244        window: &mut Window,
1245        cx: &mut App,
1246    ) -> Self::PrepaintState {
1247        let focus_handle = self.markdown.read(cx).focus_handle.clone();
1248        window.set_focus_handle(&focus_handle, cx);
1249        window.set_view_id(self.markdown.entity_id());
1250
1251        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1252        rendered_markdown.element.prepaint(window, cx);
1253        self.autoscroll(&rendered_markdown.text, window, cx);
1254        hitbox
1255    }
1256
1257    fn paint(
1258        &mut self,
1259        _id: Option<&GlobalElementId>,
1260        _inspector_id: Option<&gpui::InspectorElementId>,
1261        bounds: Bounds<Pixels>,
1262        rendered_markdown: &mut Self::RequestLayoutState,
1263        hitbox: &mut Self::PrepaintState,
1264        window: &mut Window,
1265        cx: &mut App,
1266    ) {
1267        let mut context = KeyContext::default();
1268        context.add("Markdown");
1269        window.set_key_context(context);
1270        window.on_action(std::any::TypeId::of::<crate::Copy>(), {
1271            let entity = self.markdown.clone();
1272            let text = rendered_markdown.text.clone();
1273            move |_, phase, window, cx| {
1274                let text = text.clone();
1275                if phase == DispatchPhase::Bubble {
1276                    entity.update(cx, move |this, cx| this.copy(&text, window, cx))
1277                }
1278            }
1279        });
1280        window.on_action(std::any::TypeId::of::<crate::CopyAsMarkdown>(), {
1281            let entity = self.markdown.clone();
1282            move |_, phase, window, cx| {
1283                if phase == DispatchPhase::Bubble {
1284                    entity.update(cx, move |this, cx| this.copy_as_markdown(window, cx))
1285                }
1286            }
1287        });
1288
1289        self.paint_mouse_listeners(hitbox, &rendered_markdown.text, window, cx);
1290        rendered_markdown.element.paint(window, cx);
1291        self.paint_selection(bounds, &rendered_markdown.text, window, cx);
1292    }
1293}
1294
1295fn apply_heading_style(
1296    mut heading: Div,
1297    level: pulldown_cmark::HeadingLevel,
1298    custom_styles: Option<&HeadingLevelStyles>,
1299) -> Div {
1300    heading = match level {
1301        pulldown_cmark::HeadingLevel::H1 => heading.text_3xl(),
1302        pulldown_cmark::HeadingLevel::H2 => heading.text_2xl(),
1303        pulldown_cmark::HeadingLevel::H3 => heading.text_xl(),
1304        pulldown_cmark::HeadingLevel::H4 => heading.text_lg(),
1305        pulldown_cmark::HeadingLevel::H5 => heading.text_base(),
1306        pulldown_cmark::HeadingLevel::H6 => heading.text_sm(),
1307    };
1308
1309    if let Some(styles) = custom_styles {
1310        let style_opt = match level {
1311            pulldown_cmark::HeadingLevel::H1 => &styles.h1,
1312            pulldown_cmark::HeadingLevel::H2 => &styles.h2,
1313            pulldown_cmark::HeadingLevel::H3 => &styles.h3,
1314            pulldown_cmark::HeadingLevel::H4 => &styles.h4,
1315            pulldown_cmark::HeadingLevel::H5 => &styles.h5,
1316            pulldown_cmark::HeadingLevel::H6 => &styles.h6,
1317        };
1318
1319        if let Some(style) = style_opt {
1320            heading.style().text = Some(style.clone());
1321        }
1322    }
1323
1324    heading
1325}
1326
1327fn render_copy_code_block_button(
1328    id: usize,
1329    code: String,
1330    markdown: Entity<Markdown>,
1331    cx: &App,
1332) -> impl IntoElement {
1333    let id = ElementId::named_usize("copy-markdown-code", id);
1334    let was_copied = markdown.read(cx).copied_code_blocks.contains(&id);
1335    IconButton::new(
1336        id.clone(),
1337        if was_copied {
1338            IconName::Check
1339        } else {
1340            IconName::Copy
1341        },
1342    )
1343    .icon_color(Color::Muted)
1344    .icon_size(IconSize::Small)
1345    .style(ButtonStyle::Filled)
1346    .shape(ui::IconButtonShape::Square)
1347    .tooltip(Tooltip::text("Copy"))
1348    .on_click({
1349        let markdown = markdown;
1350        move |_event, _window, cx| {
1351            let id = id.clone();
1352            markdown.update(cx, |this, cx| {
1353                this.copied_code_blocks.insert(id.clone());
1354
1355                cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));
1356
1357                cx.spawn(async move |this, cx| {
1358                    cx.background_executor().timer(Duration::from_secs(2)).await;
1359
1360                    cx.update(|cx| {
1361                        this.update(cx, |this, cx| {
1362                            this.copied_code_blocks.remove(&id);
1363                            cx.notify();
1364                        })
1365                    })
1366                    .ok();
1367                })
1368                .detach();
1369            });
1370        }
1371    })
1372}
1373
1374impl IntoElement for MarkdownElement {
1375    type Element = Self;
1376
1377    fn into_element(self) -> Self::Element {
1378        self
1379    }
1380}
1381
1382pub enum AnyDiv {
1383    Div(Div),
1384    Stateful(Stateful<Div>),
1385}
1386
1387impl AnyDiv {
1388    fn into_any_element(self) -> AnyElement {
1389        match self {
1390            Self::Div(div) => div.into_any_element(),
1391            Self::Stateful(div) => div.into_any_element(),
1392        }
1393    }
1394}
1395
1396impl From<Div> for AnyDiv {
1397    fn from(value: Div) -> Self {
1398        Self::Div(value)
1399    }
1400}
1401
1402impl From<Stateful<Div>> for AnyDiv {
1403    fn from(value: Stateful<Div>) -> Self {
1404        Self::Stateful(value)
1405    }
1406}
1407
1408impl Styled for AnyDiv {
1409    fn style(&mut self) -> &mut StyleRefinement {
1410        match self {
1411            Self::Div(div) => div.style(),
1412            Self::Stateful(div) => div.style(),
1413        }
1414    }
1415}
1416
1417impl ParentElement for AnyDiv {
1418    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1419        match self {
1420            Self::Div(div) => div.extend(elements),
1421            Self::Stateful(div) => div.extend(elements),
1422        }
1423    }
1424}
1425
1426struct MarkdownElementBuilder {
1427    div_stack: Vec<AnyDiv>,
1428    rendered_lines: Vec<RenderedLine>,
1429    pending_line: PendingLine,
1430    rendered_links: Vec<RenderedLink>,
1431    current_source_index: usize,
1432    html_comment: bool,
1433    base_text_style: TextStyle,
1434    text_style_stack: Vec<TextStyleRefinement>,
1435    code_block_stack: Vec<Option<Arc<Language>>>,
1436    list_stack: Vec<ListStackEntry>,
1437    table_alignments: Vec<Alignment>,
1438    syntax_theme: Arc<SyntaxTheme>,
1439}
1440
1441#[derive(Default)]
1442struct PendingLine {
1443    text: String,
1444    runs: Vec<TextRun>,
1445    source_mappings: Vec<SourceMapping>,
1446}
1447
1448struct ListStackEntry {
1449    bullet_index: Option<u64>,
1450}
1451
1452impl MarkdownElementBuilder {
1453    fn new(
1454        container_style: &StyleRefinement,
1455        base_text_style: TextStyle,
1456        syntax_theme: Arc<SyntaxTheme>,
1457    ) -> Self {
1458        Self {
1459            div_stack: vec![{
1460                let mut base_div = div();
1461                base_div.style().refine(container_style);
1462                base_div.debug_selector(|| "inner".into()).into()
1463            }],
1464            rendered_lines: Vec::new(),
1465            pending_line: PendingLine::default(),
1466            rendered_links: Vec::new(),
1467            current_source_index: 0,
1468            html_comment: false,
1469            base_text_style,
1470            text_style_stack: Vec::new(),
1471            code_block_stack: Vec::new(),
1472            list_stack: Vec::new(),
1473            table_alignments: Vec::new(),
1474            syntax_theme,
1475        }
1476    }
1477
1478    fn push_text_style(&mut self, style: TextStyleRefinement) {
1479        self.text_style_stack.push(style);
1480    }
1481
1482    fn text_style(&self) -> TextStyle {
1483        let mut style = self.base_text_style.clone();
1484        for refinement in &self.text_style_stack {
1485            style.refine(refinement);
1486        }
1487        style
1488    }
1489
1490    fn pop_text_style(&mut self) {
1491        self.text_style_stack.pop();
1492    }
1493
1494    fn push_div(&mut self, div: impl Into<AnyDiv>, range: &Range<usize>, markdown_end: usize) {
1495        let mut div = div.into();
1496        self.flush_text();
1497
1498        if range.start == 0 {
1499            // Remove the top margin on the first element.
1500            div.style().refine(&StyleRefinement {
1501                margin: gpui::EdgesRefinement {
1502                    top: Some(Length::Definite(px(0.).into())),
1503                    left: None,
1504                    right: None,
1505                    bottom: None,
1506                },
1507                ..Default::default()
1508            });
1509        }
1510
1511        if range.end == markdown_end {
1512            div.style().refine(&StyleRefinement {
1513                margin: gpui::EdgesRefinement {
1514                    top: None,
1515                    left: None,
1516                    right: None,
1517                    bottom: Some(Length::Definite(rems(0.).into())),
1518                },
1519                ..Default::default()
1520            });
1521        }
1522
1523        self.div_stack.push(div);
1524    }
1525
1526    fn modify_current_div(&mut self, f: impl FnOnce(AnyDiv) -> AnyDiv) {
1527        self.flush_text();
1528        if let Some(div) = self.div_stack.pop() {
1529            self.div_stack.push(f(div));
1530        }
1531    }
1532
1533    fn pop_div(&mut self) {
1534        self.flush_text();
1535        let div = self.div_stack.pop().unwrap().into_any_element();
1536        self.div_stack.last_mut().unwrap().extend(iter::once(div));
1537    }
1538
1539    fn push_list(&mut self, bullet_index: Option<u64>) {
1540        self.list_stack.push(ListStackEntry { bullet_index });
1541    }
1542
1543    fn next_bullet_index(&mut self) -> Option<u64> {
1544        self.list_stack.last_mut().and_then(|entry| {
1545            let item_index = entry.bullet_index.as_mut()?;
1546            *item_index += 1;
1547            Some(*item_index - 1)
1548        })
1549    }
1550
1551    fn pop_list(&mut self) {
1552        self.list_stack.pop();
1553    }
1554
1555    fn push_code_block(&mut self, language: Option<Arc<Language>>) {
1556        self.code_block_stack.push(language);
1557    }
1558
1559    fn pop_code_block(&mut self) {
1560        self.code_block_stack.pop();
1561    }
1562
1563    fn push_link(&mut self, destination_url: SharedString, source_range: Range<usize>) {
1564        self.rendered_links.push(RenderedLink {
1565            source_range,
1566            destination_url,
1567        });
1568    }
1569
1570    fn push_text(&mut self, text: &str, source_range: Range<usize>) {
1571        self.pending_line.source_mappings.push(SourceMapping {
1572            rendered_index: self.pending_line.text.len(),
1573            source_index: source_range.start,
1574        });
1575        self.pending_line.text.push_str(text);
1576        self.current_source_index = source_range.end;
1577
1578        if let Some(Some(language)) = self.code_block_stack.last() {
1579            let mut offset = 0;
1580            for (range, highlight_id) in language.highlight_text(&Rope::from(text), 0..text.len()) {
1581                if range.start > offset {
1582                    self.pending_line
1583                        .runs
1584                        .push(self.text_style().to_run(range.start - offset));
1585                }
1586
1587                let mut run_style = self.text_style();
1588                if let Some(highlight) = highlight_id.style(&self.syntax_theme) {
1589                    run_style = run_style.highlight(highlight);
1590                }
1591                self.pending_line.runs.push(run_style.to_run(range.len()));
1592                offset = range.end;
1593            }
1594
1595            if offset < text.len() {
1596                self.pending_line
1597                    .runs
1598                    .push(self.text_style().to_run(text.len() - offset));
1599            }
1600        } else {
1601            self.pending_line
1602                .runs
1603                .push(self.text_style().to_run(text.len()));
1604        }
1605    }
1606
1607    fn trim_trailing_newline(&mut self) {
1608        if self.pending_line.text.ends_with('\n') {
1609            self.pending_line
1610                .text
1611                .truncate(self.pending_line.text.len() - 1);
1612            self.pending_line.runs.last_mut().unwrap().len -= 1;
1613            self.current_source_index -= 1;
1614        }
1615    }
1616
1617    fn flush_text(&mut self) {
1618        let line = mem::take(&mut self.pending_line);
1619        if line.text.is_empty() {
1620            return;
1621        }
1622
1623        let text = StyledText::new(line.text).with_runs(line.runs);
1624        self.rendered_lines.push(RenderedLine {
1625            layout: text.layout().clone(),
1626            source_mappings: line.source_mappings,
1627            source_end: self.current_source_index,
1628        });
1629        self.div_stack.last_mut().unwrap().extend([text.into_any()]);
1630    }
1631
1632    fn build(mut self) -> RenderedMarkdown {
1633        debug_assert_eq!(self.div_stack.len(), 1);
1634        self.flush_text();
1635        RenderedMarkdown {
1636            element: self.div_stack.pop().unwrap().into_any_element(),
1637            text: RenderedText {
1638                lines: self.rendered_lines.into(),
1639                links: self.rendered_links.into(),
1640            },
1641        }
1642    }
1643}
1644
1645struct RenderedLine {
1646    layout: TextLayout,
1647    source_mappings: Vec<SourceMapping>,
1648    source_end: usize,
1649}
1650
1651impl RenderedLine {
1652    fn rendered_index_for_source_index(&self, source_index: usize) -> usize {
1653        if source_index >= self.source_end {
1654            return self.layout.len();
1655        }
1656
1657        let mapping = match self
1658            .source_mappings
1659            .binary_search_by_key(&source_index, |probe| probe.source_index)
1660        {
1661            Ok(ix) => &self.source_mappings[ix],
1662            Err(ix) => &self.source_mappings[ix - 1],
1663        };
1664        mapping.rendered_index + (source_index - mapping.source_index)
1665    }
1666
1667    fn source_index_for_rendered_index(&self, rendered_index: usize) -> usize {
1668        if rendered_index >= self.layout.len() {
1669            return self.source_end;
1670        }
1671
1672        let mapping = match self
1673            .source_mappings
1674            .binary_search_by_key(&rendered_index, |probe| probe.rendered_index)
1675        {
1676            Ok(ix) => &self.source_mappings[ix],
1677            Err(ix) => &self.source_mappings[ix - 1],
1678        };
1679        mapping.source_index + (rendered_index - mapping.rendered_index)
1680    }
1681
1682    fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
1683        let line_rendered_index;
1684        let out_of_bounds;
1685        match self.layout.index_for_position(position) {
1686            Ok(ix) => {
1687                line_rendered_index = ix;
1688                out_of_bounds = false;
1689            }
1690            Err(ix) => {
1691                line_rendered_index = ix;
1692                out_of_bounds = true;
1693            }
1694        };
1695        let source_index = self.source_index_for_rendered_index(line_rendered_index);
1696        if out_of_bounds {
1697            Err(source_index)
1698        } else {
1699            Ok(source_index)
1700        }
1701    }
1702}
1703
1704#[derive(Copy, Clone, Debug, Default)]
1705struct SourceMapping {
1706    rendered_index: usize,
1707    source_index: usize,
1708}
1709
1710pub struct RenderedMarkdown {
1711    element: AnyElement,
1712    text: RenderedText,
1713}
1714
1715#[derive(Clone)]
1716struct RenderedText {
1717    lines: Rc<[RenderedLine]>,
1718    links: Rc<[RenderedLink]>,
1719}
1720
1721#[derive(Debug, Clone, Eq, PartialEq)]
1722struct RenderedLink {
1723    source_range: Range<usize>,
1724    destination_url: SharedString,
1725}
1726
1727impl RenderedText {
1728    fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
1729        let mut lines = self.lines.iter().peekable();
1730
1731        while let Some(line) = lines.next() {
1732            let line_bounds = line.layout.bounds();
1733            if position.y > line_bounds.bottom() {
1734                if let Some(next_line) = lines.peek()
1735                    && position.y < next_line.layout.bounds().top()
1736                {
1737                    return Err(line.source_end);
1738                }
1739
1740                continue;
1741            }
1742
1743            return line.source_index_for_position(position);
1744        }
1745
1746        Err(self.lines.last().map_or(0, |line| line.source_end))
1747    }
1748
1749    fn position_for_source_index(&self, source_index: usize) -> Option<(Point<Pixels>, Pixels)> {
1750        for line in self.lines.iter() {
1751            let line_source_start = line.source_mappings.first().unwrap().source_index;
1752            if source_index < line_source_start {
1753                break;
1754            } else if source_index > line.source_end {
1755                continue;
1756            } else {
1757                let line_height = line.layout.line_height();
1758                let rendered_index_within_line = line.rendered_index_for_source_index(source_index);
1759                let position = line.layout.position_for_index(rendered_index_within_line)?;
1760                return Some((position, line_height));
1761            }
1762        }
1763        None
1764    }
1765
1766    fn surrounding_word_range(&self, source_index: usize) -> Range<usize> {
1767        for line in self.lines.iter() {
1768            if source_index > line.source_end {
1769                continue;
1770            }
1771
1772            let line_rendered_start = line.source_mappings.first().unwrap().rendered_index;
1773            let rendered_index_in_line =
1774                line.rendered_index_for_source_index(source_index) - line_rendered_start;
1775            let text = line.layout.text();
1776            let previous_space = if let Some(idx) = text[0..rendered_index_in_line].rfind(' ') {
1777                idx + ' '.len_utf8()
1778            } else {
1779                0
1780            };
1781            let next_space = if let Some(idx) = text[rendered_index_in_line..].find(' ') {
1782                rendered_index_in_line + idx
1783            } else {
1784                text.len()
1785            };
1786
1787            return line.source_index_for_rendered_index(line_rendered_start + previous_space)
1788                ..line.source_index_for_rendered_index(line_rendered_start + next_space);
1789        }
1790
1791        source_index..source_index
1792    }
1793
1794    fn surrounding_line_range(&self, source_index: usize) -> Range<usize> {
1795        for line in self.lines.iter() {
1796            if source_index > line.source_end {
1797                continue;
1798            }
1799            let line_source_start = line.source_mappings.first().unwrap().source_index;
1800            return line_source_start..line.source_end;
1801        }
1802
1803        source_index..source_index
1804    }
1805
1806    fn text_for_range(&self, range: Range<usize>) -> String {
1807        let mut ret = vec![];
1808
1809        for line in self.lines.iter() {
1810            if range.start > line.source_end {
1811                continue;
1812            }
1813            let line_source_start = line.source_mappings.first().unwrap().source_index;
1814            if range.end < line_source_start {
1815                break;
1816            }
1817
1818            let text = line.layout.text();
1819
1820            let start = if range.start < line_source_start {
1821                0
1822            } else {
1823                line.rendered_index_for_source_index(range.start)
1824            };
1825            let end = if range.end > line.source_end {
1826                line.rendered_index_for_source_index(line.source_end)
1827            } else {
1828                line.rendered_index_for_source_index(range.end)
1829            }
1830            .min(text.len());
1831
1832            ret.push(text[start..end].to_string());
1833        }
1834        ret.join("\n")
1835    }
1836
1837    fn link_for_position(&self, position: Point<Pixels>) -> Option<&RenderedLink> {
1838        let source_index = self.source_index_for_position(position).ok()?;
1839        self.links
1840            .iter()
1841            .find(|link| link.source_range.contains(&source_index))
1842    }
1843}
1844
1845#[cfg(test)]
1846mod tests {
1847    use super::*;
1848    use gpui::{TestAppContext, size};
1849
1850    #[gpui::test]
1851    fn test_mappings(cx: &mut TestAppContext) {
1852        // Formatting.
1853        assert_mappings(
1854            &render_markdown("He*l*lo", cx),
1855            vec![vec![(0, 0), (1, 1), (2, 3), (3, 5), (4, 6), (5, 7)]],
1856        );
1857
1858        // Multiple lines.
1859        assert_mappings(
1860            &render_markdown("Hello\n\nWorld", cx),
1861            vec![
1862                vec![(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)],
1863                vec![(0, 7), (1, 8), (2, 9), (3, 10), (4, 11), (5, 12)],
1864            ],
1865        );
1866
1867        // Multi-byte characters.
1868        assert_mappings(
1869            &render_markdown("αβγ\n\nδεζ", cx),
1870            vec![
1871                vec![(0, 0), (2, 2), (4, 4), (6, 6)],
1872                vec![(0, 8), (2, 10), (4, 12), (6, 14)],
1873            ],
1874        );
1875
1876        // Smart quotes.
1877        assert_mappings(&render_markdown("\"", cx), vec![vec![(0, 0), (3, 1)]]);
1878        assert_mappings(
1879            &render_markdown("\"hey\"", cx),
1880            vec![vec![(0, 0), (3, 1), (4, 2), (5, 3), (6, 4), (9, 5)]],
1881        );
1882
1883        // HTML Comments are ignored
1884        assert_mappings(
1885            &render_markdown(
1886                "<!--\nrdoc-file=string.c\n- str.intern   -> symbol\n- str.to_sym   -> symbol\n-->\nReturns",
1887                cx,
1888            ),
1889            vec![vec![
1890                (0, 78),
1891                (1, 79),
1892                (2, 80),
1893                (3, 81),
1894                (4, 82),
1895                (5, 83),
1896                (6, 84),
1897            ]],
1898        );
1899    }
1900
1901    fn render_markdown(markdown: &str, cx: &mut TestAppContext) -> RenderedText {
1902        struct TestWindow;
1903
1904        impl Render for TestWindow {
1905            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1906                div()
1907            }
1908        }
1909
1910        let (_, cx) = cx.add_window_view(|_, _| TestWindow);
1911        let markdown = cx.new(|cx| Markdown::new(markdown.to_string().into(), None, None, cx));
1912        cx.run_until_parked();
1913        let (rendered, _) = cx.draw(
1914            Default::default(),
1915            size(px(600.0), px(600.0)),
1916            |_window, _cx| MarkdownElement::new(markdown, MarkdownStyle::default()),
1917        );
1918        rendered.text
1919    }
1920
1921    #[test]
1922    fn test_escape() {
1923        assert_eq!(Markdown::escape("hello `world`"), "hello \\`world\\`");
1924        assert_eq!(
1925            Markdown::escape("hello\n    cool world"),
1926            "hello\n\ncool world"
1927        );
1928    }
1929
1930    #[track_caller]
1931    fn assert_mappings(rendered: &RenderedText, expected: Vec<Vec<(usize, usize)>>) {
1932        assert_eq!(rendered.lines.len(), expected.len(), "line count mismatch");
1933        for (line_ix, line_mappings) in expected.into_iter().enumerate() {
1934            let line = &rendered.lines[line_ix];
1935
1936            assert!(
1937                line.source_mappings.windows(2).all(|mappings| {
1938                    mappings[0].source_index < mappings[1].source_index
1939                        && mappings[0].rendered_index < mappings[1].rendered_index
1940                }),
1941                "line {} has duplicate mappings: {:?}",
1942                line_ix,
1943                line.source_mappings
1944            );
1945
1946            for (rendered_ix, source_ix) in line_mappings {
1947                assert_eq!(
1948                    line.source_index_for_rendered_index(rendered_ix),
1949                    source_ix,
1950                    "line {}, rendered_ix {}",
1951                    line_ix,
1952                    rendered_ix
1953                );
1954
1955                assert_eq!(
1956                    line.rendered_index_for_source_index(source_ix),
1957                    rendered_ix,
1958                    "line {}, source_ix {}",
1959                    line_ix,
1960                    source_ix
1961                );
1962            }
1963        }
1964    }
1965}