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