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