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