markdown.rs

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