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_5()
1089                                        .absolute()
1090                                        .top_1()
1091                                        .right_1()
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                                    div()
1119                                        .absolute()
1120                                        .top_0()
1121                                        .right_0()
1122                                        .w_5()
1123                                        .visible_on_hover("code_block")
1124                                        .child(codeblock),
1125                                )
1126                            });
1127                        }
1128
1129                        // Pop the parent container.
1130                        builder.pop_div();
1131                    }
1132                    MarkdownTagEnd::HtmlBlock => builder.pop_div(),
1133                    MarkdownTagEnd::List(_) => {
1134                        builder.pop_list();
1135                        builder.pop_div();
1136                    }
1137                    MarkdownTagEnd::Item => {
1138                        builder.pop_div();
1139                        builder.pop_div();
1140                    }
1141                    MarkdownTagEnd::Emphasis => builder.pop_text_style(),
1142                    MarkdownTagEnd::Strong => builder.pop_text_style(),
1143                    MarkdownTagEnd::Strikethrough => builder.pop_text_style(),
1144                    MarkdownTagEnd::Link => {
1145                        if builder.code_block_stack.is_empty() {
1146                            builder.pop_text_style()
1147                        }
1148                    }
1149                    MarkdownTagEnd::Table => {
1150                        builder.pop_div();
1151                        builder.pop_div();
1152                        builder.table_alignments.clear();
1153                    }
1154                    MarkdownTagEnd::TableHead => {
1155                        builder.pop_div();
1156                        builder.pop_text_style();
1157                    }
1158                    MarkdownTagEnd::TableRow => {
1159                        builder.pop_div();
1160                    }
1161                    MarkdownTagEnd::TableCell => {
1162                        builder.pop_div();
1163                    }
1164                    _ => log::debug!("unsupported markdown tag end: {:?}", tag),
1165                },
1166                MarkdownEvent::Text => {
1167                    builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
1168                }
1169                MarkdownEvent::SubstitutedText(text) => {
1170                    builder.push_text(text, range.clone());
1171                }
1172                MarkdownEvent::Code => {
1173                    builder.push_text_style(self.style.inline_code.clone());
1174                    builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
1175                    builder.pop_text_style();
1176                }
1177                MarkdownEvent::Html => {
1178                    let html = &parsed_markdown.source[range.clone()];
1179                    if html.starts_with("<!--") {
1180                        builder.html_comment = true;
1181                    }
1182                    if html.trim_end().ends_with("-->") {
1183                        builder.html_comment = false;
1184                        continue;
1185                    }
1186                    if builder.html_comment {
1187                        continue;
1188                    }
1189                    builder.push_text(html, range.clone());
1190                }
1191                MarkdownEvent::InlineHtml => {
1192                    builder.push_text(&parsed_markdown.source[range.clone()], range.clone());
1193                }
1194                MarkdownEvent::Rule => {
1195                    builder.push_div(
1196                        div()
1197                            .border_b_1()
1198                            .my_2()
1199                            .border_color(self.style.rule_color),
1200                        range,
1201                        markdown_end,
1202                    );
1203                    builder.pop_div()
1204                }
1205                MarkdownEvent::SoftBreak => builder.push_text(" ", range.clone()),
1206                MarkdownEvent::HardBreak => builder.push_text("\n", range.clone()),
1207                _ => log::error!("unsupported markdown event {:?}", event),
1208            }
1209        }
1210        let mut rendered_markdown = builder.build();
1211        let child_layout_id = rendered_markdown.element.request_layout(window, cx);
1212        let layout_id = window.request_layout(gpui::Style::default(), [child_layout_id], cx);
1213        (layout_id, rendered_markdown)
1214    }
1215
1216    fn prepaint(
1217        &mut self,
1218        _id: Option<&GlobalElementId>,
1219        _inspector_id: Option<&gpui::InspectorElementId>,
1220        bounds: Bounds<Pixels>,
1221        rendered_markdown: &mut Self::RequestLayoutState,
1222        window: &mut Window,
1223        cx: &mut App,
1224    ) -> Self::PrepaintState {
1225        let focus_handle = self.markdown.read(cx).focus_handle.clone();
1226        window.set_focus_handle(&focus_handle, cx);
1227        window.set_view_id(self.markdown.entity_id());
1228
1229        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1230        rendered_markdown.element.prepaint(window, cx);
1231        self.autoscroll(&rendered_markdown.text, window, cx);
1232        hitbox
1233    }
1234
1235    fn paint(
1236        &mut self,
1237        _id: Option<&GlobalElementId>,
1238        _inspector_id: Option<&gpui::InspectorElementId>,
1239        bounds: Bounds<Pixels>,
1240        rendered_markdown: &mut Self::RequestLayoutState,
1241        hitbox: &mut Self::PrepaintState,
1242        window: &mut Window,
1243        cx: &mut App,
1244    ) {
1245        let mut context = KeyContext::default();
1246        context.add("Markdown");
1247        window.set_key_context(context);
1248        window.on_action(std::any::TypeId::of::<crate::Copy>(), {
1249            let entity = self.markdown.clone();
1250            let text = rendered_markdown.text.clone();
1251            move |_, phase, window, cx| {
1252                let text = text.clone();
1253                if phase == DispatchPhase::Bubble {
1254                    entity.update(cx, move |this, cx| this.copy(&text, window, cx))
1255                }
1256            }
1257        });
1258        window.on_action(std::any::TypeId::of::<crate::CopyAsMarkdown>(), {
1259            let entity = self.markdown.clone();
1260            move |_, phase, window, cx| {
1261                if phase == DispatchPhase::Bubble {
1262                    entity.update(cx, move |this, cx| this.copy_as_markdown(window, cx))
1263                }
1264            }
1265        });
1266
1267        self.paint_mouse_listeners(hitbox, &rendered_markdown.text, window, cx);
1268        rendered_markdown.element.paint(window, cx);
1269        self.paint_selection(bounds, &rendered_markdown.text, window, cx);
1270    }
1271}
1272
1273fn apply_heading_style(
1274    mut heading: Div,
1275    level: pulldown_cmark::HeadingLevel,
1276    custom_styles: Option<&HeadingLevelStyles>,
1277) -> Div {
1278    heading = match level {
1279        pulldown_cmark::HeadingLevel::H1 => heading.text_3xl(),
1280        pulldown_cmark::HeadingLevel::H2 => heading.text_2xl(),
1281        pulldown_cmark::HeadingLevel::H3 => heading.text_xl(),
1282        pulldown_cmark::HeadingLevel::H4 => heading.text_lg(),
1283        pulldown_cmark::HeadingLevel::H5 => heading.text_base(),
1284        pulldown_cmark::HeadingLevel::H6 => heading.text_sm(),
1285    };
1286
1287    if let Some(styles) = custom_styles {
1288        let style_opt = match level {
1289            pulldown_cmark::HeadingLevel::H1 => &styles.h1,
1290            pulldown_cmark::HeadingLevel::H2 => &styles.h2,
1291            pulldown_cmark::HeadingLevel::H3 => &styles.h3,
1292            pulldown_cmark::HeadingLevel::H4 => &styles.h4,
1293            pulldown_cmark::HeadingLevel::H5 => &styles.h5,
1294            pulldown_cmark::HeadingLevel::H6 => &styles.h6,
1295        };
1296
1297        if let Some(style) = style_opt {
1298            heading.style().text = Some(style.clone());
1299        }
1300    }
1301
1302    heading
1303}
1304
1305fn render_copy_code_block_button(
1306    id: usize,
1307    code: String,
1308    markdown: Entity<Markdown>,
1309    cx: &App,
1310) -> impl IntoElement {
1311    let id = ElementId::named_usize("copy-markdown-code", id);
1312    let was_copied = markdown.read(cx).copied_code_blocks.contains(&id);
1313    IconButton::new(
1314        id.clone(),
1315        if was_copied {
1316            IconName::Check
1317        } else {
1318            IconName::Copy
1319        },
1320    )
1321    .icon_color(Color::Muted)
1322    .icon_size(IconSize::Small)
1323    .style(ButtonStyle::Filled)
1324    .shape(ui::IconButtonShape::Square)
1325    .tooltip(Tooltip::text("Copy Code"))
1326    .on_click({
1327        let markdown = markdown;
1328        move |_event, _window, cx| {
1329            let id = id.clone();
1330            markdown.update(cx, |this, cx| {
1331                this.copied_code_blocks.insert(id.clone());
1332
1333                cx.write_to_clipboard(ClipboardItem::new_string(code.clone()));
1334
1335                cx.spawn(async move |this, cx| {
1336                    cx.background_executor().timer(Duration::from_secs(2)).await;
1337
1338                    cx.update(|cx| {
1339                        this.update(cx, |this, cx| {
1340                            this.copied_code_blocks.remove(&id);
1341                            cx.notify();
1342                        })
1343                    })
1344                    .ok();
1345                })
1346                .detach();
1347            });
1348        }
1349    })
1350}
1351
1352impl IntoElement for MarkdownElement {
1353    type Element = Self;
1354
1355    fn into_element(self) -> Self::Element {
1356        self
1357    }
1358}
1359
1360pub enum AnyDiv {
1361    Div(Div),
1362    Stateful(Stateful<Div>),
1363}
1364
1365impl AnyDiv {
1366    fn into_any_element(self) -> AnyElement {
1367        match self {
1368            Self::Div(div) => div.into_any_element(),
1369            Self::Stateful(div) => div.into_any_element(),
1370        }
1371    }
1372}
1373
1374impl From<Div> for AnyDiv {
1375    fn from(value: Div) -> Self {
1376        Self::Div(value)
1377    }
1378}
1379
1380impl From<Stateful<Div>> for AnyDiv {
1381    fn from(value: Stateful<Div>) -> Self {
1382        Self::Stateful(value)
1383    }
1384}
1385
1386impl Styled for AnyDiv {
1387    fn style(&mut self) -> &mut StyleRefinement {
1388        match self {
1389            Self::Div(div) => div.style(),
1390            Self::Stateful(div) => div.style(),
1391        }
1392    }
1393}
1394
1395impl ParentElement for AnyDiv {
1396    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
1397        match self {
1398            Self::Div(div) => div.extend(elements),
1399            Self::Stateful(div) => div.extend(elements),
1400        }
1401    }
1402}
1403
1404struct MarkdownElementBuilder {
1405    div_stack: Vec<AnyDiv>,
1406    rendered_lines: Vec<RenderedLine>,
1407    pending_line: PendingLine,
1408    rendered_links: Vec<RenderedLink>,
1409    current_source_index: usize,
1410    html_comment: bool,
1411    base_text_style: TextStyle,
1412    text_style_stack: Vec<TextStyleRefinement>,
1413    code_block_stack: Vec<Option<Arc<Language>>>,
1414    list_stack: Vec<ListStackEntry>,
1415    table_alignments: Vec<Alignment>,
1416    syntax_theme: Arc<SyntaxTheme>,
1417}
1418
1419#[derive(Default)]
1420struct PendingLine {
1421    text: String,
1422    runs: Vec<TextRun>,
1423    source_mappings: Vec<SourceMapping>,
1424}
1425
1426struct ListStackEntry {
1427    bullet_index: Option<u64>,
1428}
1429
1430impl MarkdownElementBuilder {
1431    fn new(base_text_style: TextStyle, syntax_theme: Arc<SyntaxTheme>) -> Self {
1432        Self {
1433            div_stack: vec![div().debug_selector(|| "inner".into()).into()],
1434            rendered_lines: Vec::new(),
1435            pending_line: PendingLine::default(),
1436            rendered_links: Vec::new(),
1437            current_source_index: 0,
1438            html_comment: false,
1439            base_text_style,
1440            text_style_stack: Vec::new(),
1441            code_block_stack: Vec::new(),
1442            list_stack: Vec::new(),
1443            table_alignments: Vec::new(),
1444            syntax_theme,
1445        }
1446    }
1447
1448    fn push_text_style(&mut self, style: TextStyleRefinement) {
1449        self.text_style_stack.push(style);
1450    }
1451
1452    fn text_style(&self) -> TextStyle {
1453        let mut style = self.base_text_style.clone();
1454        for refinement in &self.text_style_stack {
1455            style.refine(refinement);
1456        }
1457        style
1458    }
1459
1460    fn pop_text_style(&mut self) {
1461        self.text_style_stack.pop();
1462    }
1463
1464    fn push_div(&mut self, div: impl Into<AnyDiv>, range: &Range<usize>, markdown_end: usize) {
1465        let mut div = div.into();
1466        self.flush_text();
1467
1468        if range.start == 0 {
1469            // Remove the top margin on the first element.
1470            div.style().refine(&StyleRefinement {
1471                margin: gpui::EdgesRefinement {
1472                    top: Some(Length::Definite(px(0.).into())),
1473                    left: None,
1474                    right: None,
1475                    bottom: None,
1476                },
1477                ..Default::default()
1478            });
1479        }
1480
1481        if range.end == markdown_end {
1482            div.style().refine(&StyleRefinement {
1483                margin: gpui::EdgesRefinement {
1484                    top: None,
1485                    left: None,
1486                    right: None,
1487                    bottom: Some(Length::Definite(rems(0.).into())),
1488                },
1489                ..Default::default()
1490            });
1491        }
1492
1493        self.div_stack.push(div);
1494    }
1495
1496    fn modify_current_div(&mut self, f: impl FnOnce(AnyDiv) -> AnyDiv) {
1497        self.flush_text();
1498        if let Some(div) = self.div_stack.pop() {
1499            self.div_stack.push(f(div));
1500        }
1501    }
1502
1503    fn pop_div(&mut self) {
1504        self.flush_text();
1505        let div = self.div_stack.pop().unwrap().into_any_element();
1506        self.div_stack.last_mut().unwrap().extend(iter::once(div));
1507    }
1508
1509    fn push_list(&mut self, bullet_index: Option<u64>) {
1510        self.list_stack.push(ListStackEntry { bullet_index });
1511    }
1512
1513    fn next_bullet_index(&mut self) -> Option<u64> {
1514        self.list_stack.last_mut().and_then(|entry| {
1515            let item_index = entry.bullet_index.as_mut()?;
1516            *item_index += 1;
1517            Some(*item_index - 1)
1518        })
1519    }
1520
1521    fn pop_list(&mut self) {
1522        self.list_stack.pop();
1523    }
1524
1525    fn push_code_block(&mut self, language: Option<Arc<Language>>) {
1526        self.code_block_stack.push(language);
1527    }
1528
1529    fn pop_code_block(&mut self) {
1530        self.code_block_stack.pop();
1531    }
1532
1533    fn push_link(&mut self, destination_url: SharedString, source_range: Range<usize>) {
1534        self.rendered_links.push(RenderedLink {
1535            source_range,
1536            destination_url,
1537        });
1538    }
1539
1540    fn push_text(&mut self, text: &str, source_range: Range<usize>) {
1541        self.pending_line.source_mappings.push(SourceMapping {
1542            rendered_index: self.pending_line.text.len(),
1543            source_index: source_range.start,
1544        });
1545        self.pending_line.text.push_str(text);
1546        self.current_source_index = source_range.end;
1547
1548        if let Some(Some(language)) = self.code_block_stack.last() {
1549            let mut offset = 0;
1550            for (range, highlight_id) in language.highlight_text(&Rope::from(text), 0..text.len()) {
1551                if range.start > offset {
1552                    self.pending_line
1553                        .runs
1554                        .push(self.text_style().to_run(range.start - offset));
1555                }
1556
1557                let mut run_style = self.text_style();
1558                if let Some(highlight) = highlight_id.style(&self.syntax_theme) {
1559                    run_style = run_style.highlight(highlight);
1560                }
1561                self.pending_line.runs.push(run_style.to_run(range.len()));
1562                offset = range.end;
1563            }
1564
1565            if offset < text.len() {
1566                self.pending_line
1567                    .runs
1568                    .push(self.text_style().to_run(text.len() - offset));
1569            }
1570        } else {
1571            self.pending_line
1572                .runs
1573                .push(self.text_style().to_run(text.len()));
1574        }
1575    }
1576
1577    fn trim_trailing_newline(&mut self) {
1578        if self.pending_line.text.ends_with('\n') {
1579            self.pending_line
1580                .text
1581                .truncate(self.pending_line.text.len() - 1);
1582            self.pending_line.runs.last_mut().unwrap().len -= 1;
1583            self.current_source_index -= 1;
1584        }
1585    }
1586
1587    fn flush_text(&mut self) {
1588        let line = mem::take(&mut self.pending_line);
1589        if line.text.is_empty() {
1590            return;
1591        }
1592
1593        let text = StyledText::new(line.text).with_runs(line.runs);
1594        self.rendered_lines.push(RenderedLine {
1595            layout: text.layout().clone(),
1596            source_mappings: line.source_mappings,
1597            source_end: self.current_source_index,
1598        });
1599        self.div_stack.last_mut().unwrap().extend([text.into_any()]);
1600    }
1601
1602    fn build(mut self) -> RenderedMarkdown {
1603        debug_assert_eq!(self.div_stack.len(), 1);
1604        self.flush_text();
1605        RenderedMarkdown {
1606            element: self.div_stack.pop().unwrap().into_any_element(),
1607            text: RenderedText {
1608                lines: self.rendered_lines.into(),
1609                links: self.rendered_links.into(),
1610            },
1611        }
1612    }
1613}
1614
1615struct RenderedLine {
1616    layout: TextLayout,
1617    source_mappings: Vec<SourceMapping>,
1618    source_end: usize,
1619}
1620
1621impl RenderedLine {
1622    fn rendered_index_for_source_index(&self, source_index: usize) -> usize {
1623        if source_index >= self.source_end {
1624            return self.layout.len();
1625        }
1626
1627        let mapping = match self
1628            .source_mappings
1629            .binary_search_by_key(&source_index, |probe| probe.source_index)
1630        {
1631            Ok(ix) => &self.source_mappings[ix],
1632            Err(ix) => &self.source_mappings[ix - 1],
1633        };
1634        mapping.rendered_index + (source_index - mapping.source_index)
1635    }
1636
1637    fn source_index_for_rendered_index(&self, rendered_index: usize) -> usize {
1638        if rendered_index >= self.layout.len() {
1639            return self.source_end;
1640        }
1641
1642        let mapping = match self
1643            .source_mappings
1644            .binary_search_by_key(&rendered_index, |probe| probe.rendered_index)
1645        {
1646            Ok(ix) => &self.source_mappings[ix],
1647            Err(ix) => &self.source_mappings[ix - 1],
1648        };
1649        mapping.source_index + (rendered_index - mapping.rendered_index)
1650    }
1651
1652    fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
1653        let line_rendered_index;
1654        let out_of_bounds;
1655        match self.layout.index_for_position(position) {
1656            Ok(ix) => {
1657                line_rendered_index = ix;
1658                out_of_bounds = false;
1659            }
1660            Err(ix) => {
1661                line_rendered_index = ix;
1662                out_of_bounds = true;
1663            }
1664        };
1665        let source_index = self.source_index_for_rendered_index(line_rendered_index);
1666        if out_of_bounds {
1667            Err(source_index)
1668        } else {
1669            Ok(source_index)
1670        }
1671    }
1672}
1673
1674#[derive(Copy, Clone, Debug, Default)]
1675struct SourceMapping {
1676    rendered_index: usize,
1677    source_index: usize,
1678}
1679
1680pub struct RenderedMarkdown {
1681    element: AnyElement,
1682    text: RenderedText,
1683}
1684
1685#[derive(Clone)]
1686struct RenderedText {
1687    lines: Rc<[RenderedLine]>,
1688    links: Rc<[RenderedLink]>,
1689}
1690
1691#[derive(Debug, Clone, Eq, PartialEq)]
1692struct RenderedLink {
1693    source_range: Range<usize>,
1694    destination_url: SharedString,
1695}
1696
1697impl RenderedText {
1698    fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
1699        let mut lines = self.lines.iter().peekable();
1700
1701        while let Some(line) = lines.next() {
1702            let line_bounds = line.layout.bounds();
1703            if position.y > line_bounds.bottom() {
1704                if let Some(next_line) = lines.peek()
1705                    && position.y < next_line.layout.bounds().top()
1706                {
1707                    return Err(line.source_end);
1708                }
1709
1710                continue;
1711            }
1712
1713            return line.source_index_for_position(position);
1714        }
1715
1716        Err(self.lines.last().map_or(0, |line| line.source_end))
1717    }
1718
1719    fn position_for_source_index(&self, source_index: usize) -> Option<(Point<Pixels>, Pixels)> {
1720        for line in self.lines.iter() {
1721            let line_source_start = line.source_mappings.first().unwrap().source_index;
1722            if source_index < line_source_start {
1723                break;
1724            } else if source_index > line.source_end {
1725                continue;
1726            } else {
1727                let line_height = line.layout.line_height();
1728                let rendered_index_within_line = line.rendered_index_for_source_index(source_index);
1729                let position = line.layout.position_for_index(rendered_index_within_line)?;
1730                return Some((position, line_height));
1731            }
1732        }
1733        None
1734    }
1735
1736    fn surrounding_word_range(&self, source_index: usize) -> Range<usize> {
1737        for line in self.lines.iter() {
1738            if source_index > line.source_end {
1739                continue;
1740            }
1741
1742            let line_rendered_start = line.source_mappings.first().unwrap().rendered_index;
1743            let rendered_index_in_line =
1744                line.rendered_index_for_source_index(source_index) - line_rendered_start;
1745            let text = line.layout.text();
1746            let previous_space = if let Some(idx) = text[0..rendered_index_in_line].rfind(' ') {
1747                idx + ' '.len_utf8()
1748            } else {
1749                0
1750            };
1751            let next_space = if let Some(idx) = text[rendered_index_in_line..].find(' ') {
1752                rendered_index_in_line + idx
1753            } else {
1754                text.len()
1755            };
1756
1757            return line.source_index_for_rendered_index(line_rendered_start + previous_space)
1758                ..line.source_index_for_rendered_index(line_rendered_start + next_space);
1759        }
1760
1761        source_index..source_index
1762    }
1763
1764    fn surrounding_line_range(&self, source_index: usize) -> Range<usize> {
1765        for line in self.lines.iter() {
1766            if source_index > line.source_end {
1767                continue;
1768            }
1769            let line_source_start = line.source_mappings.first().unwrap().source_index;
1770            return line_source_start..line.source_end;
1771        }
1772
1773        source_index..source_index
1774    }
1775
1776    fn text_for_range(&self, range: Range<usize>) -> String {
1777        let mut ret = vec![];
1778
1779        for line in self.lines.iter() {
1780            if range.start > line.source_end {
1781                continue;
1782            }
1783            let line_source_start = line.source_mappings.first().unwrap().source_index;
1784            if range.end < line_source_start {
1785                break;
1786            }
1787
1788            let text = line.layout.text();
1789
1790            let start = if range.start < line_source_start {
1791                0
1792            } else {
1793                line.rendered_index_for_source_index(range.start)
1794            };
1795            let end = if range.end > line.source_end {
1796                line.rendered_index_for_source_index(line.source_end)
1797            } else {
1798                line.rendered_index_for_source_index(range.end)
1799            }
1800            .min(text.len());
1801
1802            ret.push(text[start..end].to_string());
1803        }
1804        ret.join("\n")
1805    }
1806
1807    fn link_for_position(&self, position: Point<Pixels>) -> Option<&RenderedLink> {
1808        let source_index = self.source_index_for_position(position).ok()?;
1809        self.links
1810            .iter()
1811            .find(|link| link.source_range.contains(&source_index))
1812    }
1813}
1814
1815#[cfg(test)]
1816mod tests {
1817    use super::*;
1818    use gpui::{TestAppContext, size};
1819
1820    #[gpui::test]
1821    fn test_mappings(cx: &mut TestAppContext) {
1822        // Formatting.
1823        assert_mappings(
1824            &render_markdown("He*l*lo", cx),
1825            vec![vec![(0, 0), (1, 1), (2, 3), (3, 5), (4, 6), (5, 7)]],
1826        );
1827
1828        // Multiple lines.
1829        assert_mappings(
1830            &render_markdown("Hello\n\nWorld", cx),
1831            vec![
1832                vec![(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)],
1833                vec![(0, 7), (1, 8), (2, 9), (3, 10), (4, 11), (5, 12)],
1834            ],
1835        );
1836
1837        // Multi-byte characters.
1838        assert_mappings(
1839            &render_markdown("αβγ\n\nδεζ", cx),
1840            vec![
1841                vec![(0, 0), (2, 2), (4, 4), (6, 6)],
1842                vec![(0, 8), (2, 10), (4, 12), (6, 14)],
1843            ],
1844        );
1845
1846        // Smart quotes.
1847        assert_mappings(&render_markdown("\"", cx), vec![vec![(0, 0), (3, 1)]]);
1848        assert_mappings(
1849            &render_markdown("\"hey\"", cx),
1850            vec![vec![(0, 0), (3, 1), (4, 2), (5, 3), (6, 4), (9, 5)]],
1851        );
1852
1853        // HTML Comments are ignored
1854        assert_mappings(
1855            &render_markdown(
1856                "<!--\nrdoc-file=string.c\n- str.intern   -> symbol\n- str.to_sym   -> symbol\n-->\nReturns",
1857                cx,
1858            ),
1859            vec![vec![
1860                (0, 78),
1861                (1, 79),
1862                (2, 80),
1863                (3, 81),
1864                (4, 82),
1865                (5, 83),
1866                (6, 84),
1867            ]],
1868        );
1869    }
1870
1871    fn render_markdown(markdown: &str, cx: &mut TestAppContext) -> RenderedText {
1872        struct TestWindow;
1873
1874        impl Render for TestWindow {
1875            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1876                div()
1877            }
1878        }
1879
1880        let (_, cx) = cx.add_window_view(|_, _| TestWindow);
1881        let markdown = cx.new(|cx| Markdown::new(markdown.to_string().into(), None, None, cx));
1882        cx.run_until_parked();
1883        let (rendered, _) = cx.draw(
1884            Default::default(),
1885            size(px(600.0), px(600.0)),
1886            |_window, _cx| MarkdownElement::new(markdown, MarkdownStyle::default()),
1887        );
1888        rendered.text
1889    }
1890
1891    #[test]
1892    fn test_escape() {
1893        assert_eq!(Markdown::escape("hello `world`"), "hello \\`world\\`");
1894        assert_eq!(
1895            Markdown::escape("hello\n    cool world"),
1896            "hello\n\ncool world"
1897        );
1898    }
1899
1900    #[track_caller]
1901    fn assert_mappings(rendered: &RenderedText, expected: Vec<Vec<(usize, usize)>>) {
1902        assert_eq!(rendered.lines.len(), expected.len(), "line count mismatch");
1903        for (line_ix, line_mappings) in expected.into_iter().enumerate() {
1904            let line = &rendered.lines[line_ix];
1905
1906            assert!(
1907                line.source_mappings.windows(2).all(|mappings| {
1908                    mappings[0].source_index < mappings[1].source_index
1909                        && mappings[0].rendered_index < mappings[1].rendered_index
1910                }),
1911                "line {} has duplicate mappings: {:?}",
1912                line_ix,
1913                line.source_mappings
1914            );
1915
1916            for (rendered_ix, source_ix) in line_mappings {
1917                assert_eq!(
1918                    line.source_index_for_rendered_index(rendered_ix),
1919                    source_ix,
1920                    "line {}, rendered_ix {}",
1921                    line_ix,
1922                    rendered_ix
1923                );
1924
1925                assert_eq!(
1926                    line.rendered_index_for_source_index(source_ix),
1927                    rendered_ix,
1928                    "line {}, source_ix {}",
1929                    line_ix,
1930                    source_ix
1931                );
1932            }
1933        }
1934    }
1935}