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