markdown.rs

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