markdown.rs

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