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