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