markdown.rs

   1pub mod parser;
   2
   3use std::collections::{HashMap, HashSet};
   4use std::iter;
   5use std::mem;
   6use std::ops::Range;
   7use std::rc::Rc;
   8use std::sync::Arc;
   9
  10use gpui::{
  11    actions, point, quad, AnyElement, App, Bounds, ClipboardItem, CursorStyle, DispatchPhase,
  12    Edges, Entity, FocusHandle, Focusable, FontStyle, FontWeight, GlobalElementId, Hitbox, Hsla,
  13    KeyContext, Length, MouseDownEvent, MouseEvent, MouseMoveEvent, MouseUpEvent, Point, Render,
  14    Stateful, StrikethroughStyle, StyleRefinement, StyledText, Task, TextLayout, TextRun,
  15    TextStyle, TextStyleRefinement,
  16};
  17use language::{Language, LanguageRegistry, Rope};
  18use parser::{parse_links_only, parse_markdown, MarkdownEvent, MarkdownTag, MarkdownTagEnd};
  19use pulldown_cmark::Alignment;
  20use theme::SyntaxTheme;
  21use ui::{prelude::*, Tooltip};
  22use util::{ResultExt, TryFutureExt};
  23
  24use crate::parser::CodeBlockKind;
  25
  26#[derive(Clone)]
  27pub struct MarkdownStyle {
  28    pub base_text_style: TextStyle,
  29    pub code_block: StyleRefinement,
  30    pub code_block_overflow_x_scroll: bool,
  31    pub inline_code: TextStyleRefinement,
  32    pub block_quote: TextStyleRefinement,
  33    pub link: TextStyleRefinement,
  34    pub rule_color: Hsla,
  35    pub block_quote_border_color: Hsla,
  36    pub syntax: Arc<SyntaxTheme>,
  37    pub selection_background_color: Hsla,
  38    pub heading: StyleRefinement,
  39    pub table_overflow_x_scroll: bool,
  40}
  41
  42impl Default for MarkdownStyle {
  43    fn default() -> Self {
  44        Self {
  45            base_text_style: Default::default(),
  46            code_block: Default::default(),
  47            code_block_overflow_x_scroll: false,
  48            inline_code: Default::default(),
  49            block_quote: Default::default(),
  50            link: Default::default(),
  51            rule_color: Default::default(),
  52            block_quote_border_color: Default::default(),
  53            syntax: Arc::new(SyntaxTheme::default()),
  54            selection_background_color: Default::default(),
  55            heading: Default::default(),
  56            table_overflow_x_scroll: false,
  57        }
  58    }
  59}
  60
  61pub struct Markdown {
  62    source: SharedString,
  63    selection: Selection,
  64    pressed_link: Option<RenderedLink>,
  65    autoscroll_request: Option<usize>,
  66    style: MarkdownStyle,
  67    parsed_markdown: ParsedMarkdown,
  68    should_reparse: bool,
  69    pending_parse: Option<Task<Option<()>>>,
  70    focus_handle: FocusHandle,
  71    language_registry: Option<Arc<LanguageRegistry>>,
  72    fallback_code_block_language: Option<String>,
  73    open_url: Option<Box<dyn Fn(SharedString, &mut Window, &mut App)>>,
  74    options: Options,
  75    copied_code_blocks: HashSet<ElementId>,
  76}
  77
  78#[derive(Debug)]
  79struct Options {
  80    parse_links_only: bool,
  81    copy_code_block_buttons: bool,
  82}
  83
  84actions!(markdown, [Copy]);
  85
  86impl Markdown {
  87    pub fn new(
  88        source: SharedString,
  89        style: MarkdownStyle,
  90        language_registry: Option<Arc<LanguageRegistry>>,
  91        fallback_code_block_language: Option<String>,
  92        cx: &mut Context<Self>,
  93    ) -> Self {
  94        let focus_handle = cx.focus_handle();
  95        let mut this = Self {
  96            source,
  97            selection: Selection::default(),
  98            pressed_link: None,
  99            autoscroll_request: None,
 100            style,
 101            should_reparse: false,
 102            parsed_markdown: ParsedMarkdown::default(),
 103            pending_parse: None,
 104            focus_handle,
 105            language_registry,
 106            fallback_code_block_language,
 107            options: Options {
 108                parse_links_only: false,
 109                copy_code_block_buttons: true,
 110            },
 111            open_url: None,
 112            copied_code_blocks: HashSet::new(),
 113        };
 114        this.parse(cx);
 115        this
 116    }
 117
 118    pub fn open_url(
 119        self,
 120        open_url: impl Fn(SharedString, &mut Window, &mut App) + 'static,
 121    ) -> Self {
 122        Self {
 123            open_url: Some(Box::new(open_url)),
 124            ..self
 125        }
 126    }
 127
 128    pub fn new_text(source: SharedString, style: MarkdownStyle, cx: &mut Context<Self>) -> Self {
 129        let focus_handle = cx.focus_handle();
 130        let mut this = Self {
 131            source,
 132            selection: Selection::default(),
 133            pressed_link: None,
 134            autoscroll_request: None,
 135            style,
 136            should_reparse: false,
 137            parsed_markdown: ParsedMarkdown::default(),
 138            pending_parse: None,
 139            focus_handle,
 140            language_registry: None,
 141            fallback_code_block_language: None,
 142            options: Options {
 143                parse_links_only: true,
 144                copy_code_block_buttons: true,
 145            },
 146            open_url: None,
 147            copied_code_blocks: HashSet::new(),
 148        };
 149        this.parse(cx);
 150        this
 151    }
 152
 153    pub fn source(&self) -> &str {
 154        &self.source
 155    }
 156
 157    pub fn append(&mut self, text: &str, cx: &mut Context<Self>) {
 158        self.source = SharedString::new(self.source.to_string() + text);
 159        self.parse(cx);
 160    }
 161
 162    pub fn reset(&mut self, source: SharedString, cx: &mut Context<Self>) {
 163        if source == self.source() {
 164            return;
 165        }
 166        self.source = source;
 167        self.selection = Selection::default();
 168        self.autoscroll_request = None;
 169        self.pending_parse = None;
 170        self.should_reparse = false;
 171        self.parsed_markdown = ParsedMarkdown::default();
 172        self.parse(cx);
 173    }
 174
 175    pub fn parsed_markdown(&self) -> &ParsedMarkdown {
 176        &self.parsed_markdown
 177    }
 178
 179    fn copy(&self, text: &RenderedText, _: &mut Window, cx: &mut Context<Self>) {
 180        if self.selection.end <= self.selection.start {
 181            return;
 182        }
 183        let text = text.text_for_range(self.selection.start..self.selection.end);
 184        cx.write_to_clipboard(ClipboardItem::new_string(text));
 185    }
 186
 187    fn parse(&mut self, cx: &mut Context<Self>) {
 188        if self.source.is_empty() {
 189            return;
 190        }
 191
 192        if self.pending_parse.is_some() {
 193            self.should_reparse = true;
 194            return;
 195        }
 196
 197        let source = self.source.clone();
 198        let parse_text_only = self.options.parse_links_only;
 199        let language_registry = self.language_registry.clone();
 200        let fallback = self.fallback_code_block_language.clone();
 201        let parsed = cx.background_spawn(async move {
 202            if parse_text_only {
 203                return anyhow::Ok(ParsedMarkdown {
 204                    events: Arc::from(parse_links_only(source.as_ref())),
 205                    source,
 206                    languages: HashMap::default(),
 207                });
 208            }
 209            let (events, language_names) = parse_markdown(&source);
 210            let mut languages = HashMap::with_capacity(language_names.len());
 211            for name in language_names {
 212                if let Some(registry) = language_registry.as_ref() {
 213                    let language = if !name.is_empty() {
 214                        registry.language_for_name(&name)
 215                    } else if let Some(fallback) = &fallback {
 216                        registry.language_for_name(fallback)
 217                    } else {
 218                        continue;
 219                    };
 220                    if let Ok(language) = language.await {
 221                        languages.insert(name, language);
 222                    }
 223                }
 224            }
 225            anyhow::Ok(ParsedMarkdown {
 226                source,
 227                events: Arc::from(events),
 228                languages,
 229            })
 230        });
 231
 232        self.should_reparse = false;
 233        self.pending_parse = Some(cx.spawn(|this, mut cx| {
 234            async move {
 235                let parsed = parsed.await?;
 236                this.update(&mut cx, |this, cx| {
 237                    this.parsed_markdown = parsed;
 238                    this.pending_parse.take();
 239                    if this.should_reparse {
 240                        this.parse(cx);
 241                    }
 242                    cx.notify();
 243                })
 244                .ok();
 245                anyhow::Ok(())
 246            }
 247            .log_err()
 248        }));
 249    }
 250
 251    pub fn copy_code_block_buttons(mut self, should_copy: bool) -> Self {
 252        self.options.copy_code_block_buttons = should_copy;
 253        self
 254    }
 255}
 256
 257impl Render for Markdown {
 258    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 259        MarkdownElement::new(cx.entity().clone(), self.style.clone())
 260    }
 261}
 262
 263impl Focusable for Markdown {
 264    fn focus_handle(&self, _cx: &App) -> FocusHandle {
 265        self.focus_handle.clone()
 266    }
 267}
 268
 269#[derive(Copy, Clone, Default, Debug)]
 270struct Selection {
 271    start: usize,
 272    end: usize,
 273    reversed: bool,
 274    pending: bool,
 275}
 276
 277impl Selection {
 278    fn set_head(&mut self, head: usize) {
 279        if head < self.tail() {
 280            if !self.reversed {
 281                self.end = self.start;
 282                self.reversed = true;
 283            }
 284            self.start = head;
 285        } else {
 286            if self.reversed {
 287                self.start = self.end;
 288                self.reversed = false;
 289            }
 290            self.end = head;
 291        }
 292    }
 293
 294    fn tail(&self) -> usize {
 295        if self.reversed {
 296            self.end
 297        } else {
 298            self.start
 299        }
 300    }
 301}
 302
 303#[derive(Default)]
 304pub struct ParsedMarkdown {
 305    source: SharedString,
 306    events: Arc<[(Range<usize>, MarkdownEvent)]>,
 307    languages: HashMap<SharedString, Arc<Language>>,
 308}
 309
 310impl ParsedMarkdown {
 311    pub fn source(&self) -> &SharedString {
 312        &self.source
 313    }
 314
 315    pub fn events(&self) -> &Arc<[(Range<usize>, MarkdownEvent)]> {
 316        &self.events
 317    }
 318}
 319
 320pub struct MarkdownElement {
 321    markdown: Entity<Markdown>,
 322    style: MarkdownStyle,
 323}
 324
 325impl MarkdownElement {
 326    fn new(markdown: Entity<Markdown>, style: MarkdownStyle) -> Self {
 327        Self { markdown, style }
 328    }
 329
 330    fn paint_selection(
 331        &self,
 332        bounds: Bounds<Pixels>,
 333        rendered_text: &RenderedText,
 334        window: &mut Window,
 335        cx: &mut App,
 336    ) {
 337        let selection = self.markdown.read(cx).selection;
 338        let selection_start = rendered_text.position_for_source_index(selection.start);
 339        let selection_end = rendered_text.position_for_source_index(selection.end);
 340
 341        if let Some(((start_position, start_line_height), (end_position, end_line_height))) =
 342            selection_start.zip(selection_end)
 343        {
 344            if start_position.y == end_position.y {
 345                window.paint_quad(quad(
 346                    Bounds::from_corners(
 347                        start_position,
 348                        point(end_position.x, end_position.y + end_line_height),
 349                    ),
 350                    Pixels::ZERO,
 351                    self.style.selection_background_color,
 352                    Edges::default(),
 353                    Hsla::transparent_black(),
 354                ));
 355            } else {
 356                window.paint_quad(quad(
 357                    Bounds::from_corners(
 358                        start_position,
 359                        point(bounds.right(), start_position.y + start_line_height),
 360                    ),
 361                    Pixels::ZERO,
 362                    self.style.selection_background_color,
 363                    Edges::default(),
 364                    Hsla::transparent_black(),
 365                ));
 366
 367                if end_position.y > start_position.y + start_line_height {
 368                    window.paint_quad(quad(
 369                        Bounds::from_corners(
 370                            point(bounds.left(), start_position.y + start_line_height),
 371                            point(bounds.right(), end_position.y),
 372                        ),
 373                        Pixels::ZERO,
 374                        self.style.selection_background_color,
 375                        Edges::default(),
 376                        Hsla::transparent_black(),
 377                    ));
 378                }
 379
 380                window.paint_quad(quad(
 381                    Bounds::from_corners(
 382                        point(bounds.left(), end_position.y),
 383                        point(end_position.x, end_position.y + end_line_height),
 384                    ),
 385                    Pixels::ZERO,
 386                    self.style.selection_background_color,
 387                    Edges::default(),
 388                    Hsla::transparent_black(),
 389                ));
 390            }
 391        }
 392    }
 393
 394    fn paint_mouse_listeners(
 395        &self,
 396        hitbox: &Hitbox,
 397        rendered_text: &RenderedText,
 398        window: &mut Window,
 399        cx: &mut App,
 400    ) {
 401        let is_hovering_link = hitbox.is_hovered(window)
 402            && !self.markdown.read(cx).selection.pending
 403            && rendered_text
 404                .link_for_position(window.mouse_position())
 405                .is_some();
 406
 407        if is_hovering_link {
 408            window.set_cursor_style(CursorStyle::PointingHand, hitbox);
 409        } else {
 410            window.set_cursor_style(CursorStyle::IBeam, hitbox);
 411        }
 412
 413        self.on_mouse_event(window, cx, {
 414            let rendered_text = rendered_text.clone();
 415            let hitbox = hitbox.clone();
 416            move |markdown, event: &MouseDownEvent, phase, window, cx| {
 417                if hitbox.is_hovered(window) {
 418                    if phase.bubble() {
 419                        if let Some(link) = rendered_text.link_for_position(event.position) {
 420                            markdown.pressed_link = Some(link.clone());
 421                        } else {
 422                            let source_index =
 423                                match rendered_text.source_index_for_position(event.position) {
 424                                    Ok(ix) | Err(ix) => ix,
 425                                };
 426                            let range = if event.click_count == 2 {
 427                                rendered_text.surrounding_word_range(source_index)
 428                            } else if event.click_count == 3 {
 429                                rendered_text.surrounding_line_range(source_index)
 430                            } else {
 431                                source_index..source_index
 432                            };
 433                            markdown.selection = Selection {
 434                                start: range.start,
 435                                end: range.end,
 436                                reversed: false,
 437                                pending: true,
 438                            };
 439                            window.focus(&markdown.focus_handle);
 440                            window.prevent_default();
 441                        }
 442
 443                        cx.notify();
 444                    }
 445                } else if phase.capture() {
 446                    markdown.selection = Selection::default();
 447                    markdown.pressed_link = None;
 448                    cx.notify();
 449                }
 450            }
 451        });
 452        self.on_mouse_event(window, cx, {
 453            let rendered_text = rendered_text.clone();
 454            let hitbox = hitbox.clone();
 455            let was_hovering_link = is_hovering_link;
 456            move |markdown, event: &MouseMoveEvent, phase, window, cx| {
 457                if phase.capture() {
 458                    return;
 459                }
 460
 461                if markdown.selection.pending {
 462                    let source_index = match rendered_text.source_index_for_position(event.position)
 463                    {
 464                        Ok(ix) | Err(ix) => ix,
 465                    };
 466                    markdown.selection.set_head(source_index);
 467                    markdown.autoscroll_request = Some(source_index);
 468                    cx.notify();
 469                } else {
 470                    let is_hovering_link = hitbox.is_hovered(window)
 471                        && rendered_text.link_for_position(event.position).is_some();
 472                    if is_hovering_link != was_hovering_link {
 473                        cx.notify();
 474                    }
 475                }
 476            }
 477        });
 478        self.on_mouse_event(window, cx, {
 479            let rendered_text = rendered_text.clone();
 480            move |markdown, event: &MouseUpEvent, phase, window, cx| {
 481                if phase.bubble() {
 482                    if let Some(pressed_link) = markdown.pressed_link.take() {
 483                        if Some(&pressed_link) == rendered_text.link_for_position(event.position) {
 484                            if let Some(open_url) = markdown.open_url.as_mut() {
 485                                open_url(pressed_link.destination_url, window, cx);
 486                            } else {
 487                                cx.open_url(&pressed_link.destination_url);
 488                            }
 489                        }
 490                    }
 491                } else if markdown.selection.pending {
 492                    markdown.selection.pending = false;
 493                    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 494                    {
 495                        let text = rendered_text
 496                            .text_for_range(markdown.selection.start..markdown.selection.end);
 497                        cx.write_to_primary(ClipboardItem::new_string(text))
 498                    }
 499                    cx.notify();
 500                }
 501            }
 502        });
 503    }
 504
 505    fn autoscroll(
 506        &self,
 507        rendered_text: &RenderedText,
 508        window: &mut Window,
 509        cx: &mut App,
 510    ) -> Option<()> {
 511        let autoscroll_index = self
 512            .markdown
 513            .update(cx, |markdown, _| markdown.autoscroll_request.take())?;
 514        let (position, line_height) = rendered_text.position_for_source_index(autoscroll_index)?;
 515
 516        let text_style = self.style.base_text_style.clone();
 517        let font_id = window.text_system().resolve_font(&text_style.font());
 518        let font_size = text_style.font_size.to_pixels(window.rem_size());
 519        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
 520        window.request_autoscroll(Bounds::from_corners(
 521            point(position.x - 3. * em_width, position.y - 3. * line_height),
 522            point(position.x + 3. * em_width, position.y + 3. * line_height),
 523        ));
 524        Some(())
 525    }
 526
 527    fn on_mouse_event<T: MouseEvent>(
 528        &self,
 529        window: &mut Window,
 530        _cx: &mut App,
 531        mut f: impl 'static
 532            + FnMut(&mut Markdown, &T, DispatchPhase, &mut Window, &mut Context<Markdown>),
 533    ) {
 534        window.on_mouse_event({
 535            let markdown = self.markdown.downgrade();
 536            move |event, phase, window, cx| {
 537                markdown
 538                    .update(cx, |markdown, cx| f(markdown, event, phase, window, cx))
 539                    .log_err();
 540            }
 541        });
 542    }
 543}
 544
 545impl Element for MarkdownElement {
 546    type RequestLayoutState = RenderedMarkdown;
 547    type PrepaintState = Hitbox;
 548
 549    fn id(&self) -> Option<ElementId> {
 550        None
 551    }
 552
 553    fn request_layout(
 554        &mut self,
 555        _id: Option<&GlobalElementId>,
 556        window: &mut Window,
 557        cx: &mut App,
 558    ) -> (gpui::LayoutId, Self::RequestLayoutState) {
 559        let mut builder = MarkdownElementBuilder::new(
 560            self.style.base_text_style.clone(),
 561            self.style.syntax.clone(),
 562        );
 563        let parsed_markdown = &self.markdown.read(cx).parsed_markdown;
 564        let markdown_end = if let Some(last) = parsed_markdown.events.last() {
 565            last.0.end
 566        } else {
 567            0
 568        };
 569        for (range, event) in parsed_markdown.events.iter() {
 570            match event {
 571                MarkdownEvent::Start(tag) => {
 572                    match tag {
 573                        MarkdownTag::Paragraph => {
 574                            builder.push_div(
 575                                div().mb_2().line_height(rems(1.3)),
 576                                range,
 577                                markdown_end,
 578                            );
 579                        }
 580                        MarkdownTag::Heading { level, .. } => {
 581                            let mut heading = div().mb_2();
 582                            heading = match level {
 583                                pulldown_cmark::HeadingLevel::H1 => heading.text_3xl(),
 584                                pulldown_cmark::HeadingLevel::H2 => heading.text_2xl(),
 585                                pulldown_cmark::HeadingLevel::H3 => heading.text_xl(),
 586                                pulldown_cmark::HeadingLevel::H4 => heading.text_lg(),
 587                                _ => heading,
 588                            };
 589                            heading.style().refine(&self.style.heading);
 590                            builder.push_text_style(
 591                                self.style.heading.text_style().clone().unwrap_or_default(),
 592                            );
 593                            builder.push_div(heading, range, markdown_end);
 594                        }
 595                        MarkdownTag::BlockQuote => {
 596                            builder.push_text_style(self.style.block_quote.clone());
 597                            builder.push_div(
 598                                div()
 599                                    .pl_4()
 600                                    .mb_2()
 601                                    .border_l_4()
 602                                    .border_color(self.style.block_quote_border_color),
 603                                range,
 604                                markdown_end,
 605                            );
 606                        }
 607                        MarkdownTag::CodeBlock(kind) => {
 608                            let language = if let CodeBlockKind::Fenced(language) = kind {
 609                                parsed_markdown.languages.get(language).cloned()
 610                            } else {
 611                                None
 612                            };
 613
 614                            let mut code_block = div()
 615                                .id(("code-block", range.start))
 616                                .flex()
 617                                .rounded_lg()
 618                                .when(self.style.code_block_overflow_x_scroll, |mut code_block| {
 619                                    code_block.style().restrict_scroll_to_axis = Some(true);
 620                                    code_block.overflow_x_scroll()
 621                                });
 622                            code_block.style().refine(&self.style.code_block);
 623                            if let Some(code_block_text_style) = &self.style.code_block.text {
 624                                builder.push_text_style(code_block_text_style.to_owned());
 625                            }
 626                            builder.push_code_block(language);
 627                            builder.push_div(code_block, range, markdown_end);
 628                        }
 629                        MarkdownTag::HtmlBlock => builder.push_div(div(), range, markdown_end),
 630                        MarkdownTag::List(bullet_index) => {
 631                            builder.push_list(*bullet_index);
 632                            builder.push_div(div().pl_4(), range, markdown_end);
 633                        }
 634                        MarkdownTag::Item => {
 635                            let bullet = if let Some(bullet_index) = builder.next_bullet_index() {
 636                                format!("{}.", bullet_index)
 637                            } else {
 638                                "".to_string()
 639                            };
 640                            builder.push_div(
 641                                div()
 642                                    .mb_1()
 643                                    .h_flex()
 644                                    .items_start()
 645                                    .gap_1()
 646                                    .line_height(rems(1.3))
 647                                    .child(bullet),
 648                                range,
 649                                markdown_end,
 650                            );
 651                            // Without `w_0`, text doesn't wrap to the width of the container.
 652                            builder.push_div(div().flex_1().w_0(), range, markdown_end);
 653                        }
 654                        MarkdownTag::Emphasis => builder.push_text_style(TextStyleRefinement {
 655                            font_style: Some(FontStyle::Italic),
 656                            ..Default::default()
 657                        }),
 658                        MarkdownTag::Strong => builder.push_text_style(TextStyleRefinement {
 659                            font_weight: Some(FontWeight::BOLD),
 660                            ..Default::default()
 661                        }),
 662                        MarkdownTag::Strikethrough => {
 663                            builder.push_text_style(TextStyleRefinement {
 664                                strikethrough: Some(StrikethroughStyle {
 665                                    thickness: px(1.),
 666                                    color: None,
 667                                }),
 668                                ..Default::default()
 669                            })
 670                        }
 671                        MarkdownTag::Link { dest_url, .. } => {
 672                            if builder.code_block_stack.is_empty() {
 673                                builder.push_link(dest_url.clone(), range.clone());
 674                                builder.push_text_style(self.style.link.clone())
 675                            }
 676                        }
 677                        MarkdownTag::MetadataBlock(_) => {}
 678                        MarkdownTag::Table(alignments) => {
 679                            builder.table_alignments = alignments.clone();
 680                            builder.push_div(
 681                                div()
 682                                    .id(("table", range.start))
 683                                    .flex()
 684                                    .border_1()
 685                                    .border_color(cx.theme().colors().border)
 686                                    .rounded_md()
 687                                    .when(self.style.table_overflow_x_scroll, |mut table| {
 688                                        table.style().restrict_scroll_to_axis = Some(true);
 689                                        table.overflow_x_scroll()
 690                                    }),
 691                                range,
 692                                markdown_end,
 693                            );
 694                            // This inner `v_flex` is so the table rows will stack vertically without disrupting the `overflow_x_scroll`.
 695                            builder.push_div(div().v_flex().flex_grow(), range, markdown_end);
 696                        }
 697                        MarkdownTag::TableHead => {
 698                            builder.push_div(
 699                                div()
 700                                    .flex()
 701                                    .justify_between()
 702                                    .border_b_1()
 703                                    .border_color(cx.theme().colors().border),
 704                                range,
 705                                markdown_end,
 706                            );
 707                            builder.push_text_style(TextStyleRefinement {
 708                                font_weight: Some(FontWeight::BOLD),
 709                                ..Default::default()
 710                            });
 711                        }
 712                        MarkdownTag::TableRow => {
 713                            builder.push_div(
 714                                div().h_flex().justify_between().px_1().py_0p5(),
 715                                range,
 716                                markdown_end,
 717                            );
 718                        }
 719                        MarkdownTag::TableCell => {
 720                            let column_count = builder.table_alignments.len();
 721
 722                            builder.push_div(
 723                                div()
 724                                    .flex()
 725                                    .px_1()
 726                                    .w(relative(1. / column_count as f32))
 727                                    .truncate(),
 728                                range,
 729                                markdown_end,
 730                            );
 731                        }
 732                        _ => log::error!("unsupported markdown tag {:?}", tag),
 733                    }
 734                }
 735                MarkdownEvent::End(tag) => match tag {
 736                    MarkdownTagEnd::Paragraph => {
 737                        builder.pop_div();
 738                    }
 739                    MarkdownTagEnd::Heading(_) => {
 740                        builder.pop_div();
 741                        builder.pop_text_style()
 742                    }
 743                    MarkdownTagEnd::BlockQuote(_kind) => {
 744                        builder.pop_text_style();
 745                        builder.pop_div()
 746                    }
 747                    MarkdownTagEnd::CodeBlock => {
 748                        builder.trim_trailing_newline();
 749
 750                        if self.markdown.read(cx).options.copy_code_block_buttons {
 751                            builder.flush_text();
 752                            builder.modify_current_div(|el| {
 753                                let id =
 754                                    ElementId::NamedInteger("copy-markdown-code".into(), range.end);
 755                                let was_copied =
 756                                    self.markdown.read(cx).copied_code_blocks.contains(&id);
 757                                let copy_button = div().absolute().top_1().right_1().w_5().child(
 758                                    IconButton::new(
 759                                        id.clone(),
 760                                        if was_copied {
 761                                            IconName::Check
 762                                        } else {
 763                                            IconName::Copy
 764                                        },
 765                                    )
 766                                    .icon_color(Color::Muted)
 767                                    .shape(ui::IconButtonShape::Square)
 768                                    .tooltip(Tooltip::text("Copy Code"))
 769                                    .on_click({
 770                                        let id = id.clone();
 771                                        let markdown = self.markdown.clone();
 772                                        let code = without_fences(
 773                                            parsed_markdown.source()[range.clone()].trim(),
 774                                        )
 775                                        .to_string();
 776                                        move |_event, _window, cx| {
 777                                            markdown.update(cx, |this, cx| {
 778                                                this.copied_code_blocks.insert(id.clone());
 779
 780                                                cx.write_to_clipboard(ClipboardItem::new_string(
 781                                                    code.clone(),
 782                                                ));
 783                                            });
 784                                        }
 785                                    }),
 786                                );
 787
 788                                el.child(copy_button)
 789                            });
 790                        }
 791
 792                        builder.pop_div();
 793                        builder.pop_code_block();
 794                        if self.style.code_block.text.is_some() {
 795                            builder.pop_text_style();
 796                        }
 797                    }
 798                    MarkdownTagEnd::HtmlBlock => builder.pop_div(),
 799                    MarkdownTagEnd::List(_) => {
 800                        builder.pop_list();
 801                        builder.pop_div();
 802                    }
 803                    MarkdownTagEnd::Item => {
 804                        builder.pop_div();
 805                        builder.pop_div();
 806                    }
 807                    MarkdownTagEnd::Emphasis => builder.pop_text_style(),
 808                    MarkdownTagEnd::Strong => builder.pop_text_style(),
 809                    MarkdownTagEnd::Strikethrough => builder.pop_text_style(),
 810                    MarkdownTagEnd::Link => {
 811                        if builder.code_block_stack.is_empty() {
 812                            builder.pop_text_style()
 813                        }
 814                    }
 815                    MarkdownTagEnd::Table => {
 816                        builder.pop_div();
 817                        builder.pop_div();
 818                        builder.table_alignments.clear();
 819                    }
 820                    MarkdownTagEnd::TableHead => {
 821                        builder.pop_div();
 822                        builder.pop_text_style();
 823                    }
 824                    MarkdownTagEnd::TableRow => {
 825                        builder.pop_div();
 826                    }
 827                    MarkdownTagEnd::TableCell => {
 828                        builder.pop_div();
 829                    }
 830                    _ => log::error!("unsupported markdown tag end: {:?}", tag),
 831                },
 832                MarkdownEvent::Text(parsed) => {
 833                    builder.push_text(parsed, range.start);
 834                }
 835                MarkdownEvent::Code => {
 836                    builder.push_text_style(self.style.inline_code.clone());
 837                    builder.push_text(&parsed_markdown.source[range.clone()], range.start);
 838                    builder.pop_text_style();
 839                }
 840                MarkdownEvent::Html => {
 841                    builder.push_text(&parsed_markdown.source[range.clone()], range.start);
 842                }
 843                MarkdownEvent::InlineHtml => {
 844                    builder.push_text(&parsed_markdown.source[range.clone()], range.start);
 845                }
 846                MarkdownEvent::Rule => {
 847                    builder.push_div(
 848                        div()
 849                            .border_b_1()
 850                            .my_2()
 851                            .border_color(self.style.rule_color),
 852                        range,
 853                        markdown_end,
 854                    );
 855                    builder.pop_div()
 856                }
 857                MarkdownEvent::SoftBreak => builder.push_text(" ", range.start),
 858                MarkdownEvent::HardBreak => builder.push_text("\n", range.start),
 859                _ => log::error!("unsupported markdown event {:?}", event),
 860            }
 861        }
 862        let mut rendered_markdown = builder.build();
 863        let child_layout_id = rendered_markdown.element.request_layout(window, cx);
 864        let layout_id = window.request_layout(gpui::Style::default(), [child_layout_id], cx);
 865        (layout_id, rendered_markdown)
 866    }
 867
 868    fn prepaint(
 869        &mut self,
 870        _id: Option<&GlobalElementId>,
 871        bounds: Bounds<Pixels>,
 872        rendered_markdown: &mut Self::RequestLayoutState,
 873        window: &mut Window,
 874        cx: &mut App,
 875    ) -> Self::PrepaintState {
 876        let focus_handle = self.markdown.read(cx).focus_handle.clone();
 877        window.set_focus_handle(&focus_handle, cx);
 878
 879        let hitbox = window.insert_hitbox(bounds, false);
 880        rendered_markdown.element.prepaint(window, cx);
 881        self.autoscroll(&rendered_markdown.text, window, cx);
 882        hitbox
 883    }
 884
 885    fn paint(
 886        &mut self,
 887        _id: Option<&GlobalElementId>,
 888        bounds: Bounds<Pixels>,
 889        rendered_markdown: &mut Self::RequestLayoutState,
 890        hitbox: &mut Self::PrepaintState,
 891        window: &mut Window,
 892        cx: &mut App,
 893    ) {
 894        let mut context = KeyContext::default();
 895        context.add("Markdown");
 896        window.set_key_context(context);
 897        let entity = self.markdown.clone();
 898        window.on_action(std::any::TypeId::of::<crate::Copy>(), {
 899            let text = rendered_markdown.text.clone();
 900            move |_, phase, window, cx| {
 901                let text = text.clone();
 902                if phase == DispatchPhase::Bubble {
 903                    entity.update(cx, move |this, cx| this.copy(&text, window, cx))
 904                }
 905            }
 906        });
 907
 908        self.paint_mouse_listeners(hitbox, &rendered_markdown.text, window, cx);
 909        rendered_markdown.element.paint(window, cx);
 910        self.paint_selection(bounds, &rendered_markdown.text, window, cx);
 911    }
 912}
 913
 914impl IntoElement for MarkdownElement {
 915    type Element = Self;
 916
 917    fn into_element(self) -> Self::Element {
 918        self
 919    }
 920}
 921
 922enum AnyDiv {
 923    Div(Div),
 924    Stateful(Stateful<Div>),
 925}
 926
 927impl AnyDiv {
 928    fn into_any_element(self) -> AnyElement {
 929        match self {
 930            Self::Div(div) => div.into_any_element(),
 931            Self::Stateful(div) => div.into_any_element(),
 932        }
 933    }
 934}
 935
 936impl From<Div> for AnyDiv {
 937    fn from(value: Div) -> Self {
 938        Self::Div(value)
 939    }
 940}
 941
 942impl From<Stateful<Div>> for AnyDiv {
 943    fn from(value: Stateful<Div>) -> Self {
 944        Self::Stateful(value)
 945    }
 946}
 947
 948impl Styled for AnyDiv {
 949    fn style(&mut self) -> &mut StyleRefinement {
 950        match self {
 951            Self::Div(div) => div.style(),
 952            Self::Stateful(div) => div.style(),
 953        }
 954    }
 955}
 956
 957impl ParentElement for AnyDiv {
 958    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
 959        match self {
 960            Self::Div(div) => div.extend(elements),
 961            Self::Stateful(div) => div.extend(elements),
 962        }
 963    }
 964}
 965
 966struct MarkdownElementBuilder {
 967    div_stack: Vec<AnyDiv>,
 968    rendered_lines: Vec<RenderedLine>,
 969    pending_line: PendingLine,
 970    rendered_links: Vec<RenderedLink>,
 971    current_source_index: usize,
 972    base_text_style: TextStyle,
 973    text_style_stack: Vec<TextStyleRefinement>,
 974    code_block_stack: Vec<Option<Arc<Language>>>,
 975    list_stack: Vec<ListStackEntry>,
 976    table_alignments: Vec<Alignment>,
 977    syntax_theme: Arc<SyntaxTheme>,
 978}
 979
 980#[derive(Default)]
 981struct PendingLine {
 982    text: String,
 983    runs: Vec<TextRun>,
 984    source_mappings: Vec<SourceMapping>,
 985}
 986
 987struct ListStackEntry {
 988    bullet_index: Option<u64>,
 989}
 990
 991impl MarkdownElementBuilder {
 992    fn new(base_text_style: TextStyle, syntax_theme: Arc<SyntaxTheme>) -> Self {
 993        Self {
 994            div_stack: vec![div().debug_selector(|| "inner".into()).into()],
 995            rendered_lines: Vec::new(),
 996            pending_line: PendingLine::default(),
 997            rendered_links: Vec::new(),
 998            current_source_index: 0,
 999            base_text_style,
1000            text_style_stack: Vec::new(),
1001            code_block_stack: Vec::new(),
1002            list_stack: Vec::new(),
1003            table_alignments: Vec::new(),
1004            syntax_theme,
1005        }
1006    }
1007
1008    fn push_text_style(&mut self, style: TextStyleRefinement) {
1009        self.text_style_stack.push(style);
1010    }
1011
1012    fn text_style(&self) -> TextStyle {
1013        let mut style = self.base_text_style.clone();
1014        for refinement in &self.text_style_stack {
1015            style.refine(refinement);
1016        }
1017        style
1018    }
1019
1020    fn pop_text_style(&mut self) {
1021        self.text_style_stack.pop();
1022    }
1023
1024    fn push_div(&mut self, div: impl Into<AnyDiv>, range: &Range<usize>, markdown_end: usize) {
1025        let mut div = div.into();
1026        self.flush_text();
1027
1028        if range.start == 0 {
1029            // Remove the top margin on the first element.
1030            div.style().refine(&StyleRefinement {
1031                margin: gpui::EdgesRefinement {
1032                    top: Some(Length::Definite(px(0.).into())),
1033                    left: None,
1034                    right: None,
1035                    bottom: None,
1036                },
1037                ..Default::default()
1038            });
1039        }
1040
1041        if range.end == markdown_end {
1042            div.style().refine(&StyleRefinement {
1043                margin: gpui::EdgesRefinement {
1044                    top: None,
1045                    left: None,
1046                    right: None,
1047                    bottom: Some(Length::Definite(rems(0.).into())),
1048                },
1049                ..Default::default()
1050            });
1051        }
1052
1053        self.div_stack.push(div);
1054    }
1055
1056    fn modify_current_div(&mut self, f: impl FnOnce(AnyDiv) -> AnyDiv) {
1057        self.flush_text();
1058        if let Some(div) = self.div_stack.pop() {
1059            self.div_stack.push(f(div));
1060        }
1061    }
1062
1063    fn pop_div(&mut self) {
1064        self.flush_text();
1065        let div = self.div_stack.pop().unwrap().into_any_element();
1066        self.div_stack.last_mut().unwrap().extend(iter::once(div));
1067    }
1068
1069    fn push_list(&mut self, bullet_index: Option<u64>) {
1070        self.list_stack.push(ListStackEntry { bullet_index });
1071    }
1072
1073    fn next_bullet_index(&mut self) -> Option<u64> {
1074        self.list_stack.last_mut().and_then(|entry| {
1075            let item_index = entry.bullet_index.as_mut()?;
1076            *item_index += 1;
1077            Some(*item_index - 1)
1078        })
1079    }
1080
1081    fn pop_list(&mut self) {
1082        self.list_stack.pop();
1083    }
1084
1085    fn push_code_block(&mut self, language: Option<Arc<Language>>) {
1086        self.code_block_stack.push(language);
1087    }
1088
1089    fn pop_code_block(&mut self) {
1090        self.code_block_stack.pop();
1091    }
1092
1093    fn push_link(&mut self, destination_url: SharedString, source_range: Range<usize>) {
1094        self.rendered_links.push(RenderedLink {
1095            source_range,
1096            destination_url,
1097        });
1098    }
1099
1100    fn push_text(&mut self, text: &str, source_index: usize) {
1101        self.pending_line.source_mappings.push(SourceMapping {
1102            rendered_index: self.pending_line.text.len(),
1103            source_index,
1104        });
1105        self.pending_line.text.push_str(text);
1106        self.current_source_index = source_index + text.len();
1107
1108        if let Some(Some(language)) = self.code_block_stack.last() {
1109            let mut offset = 0;
1110            for (range, highlight_id) in language.highlight_text(&Rope::from(text), 0..text.len()) {
1111                if range.start > offset {
1112                    self.pending_line
1113                        .runs
1114                        .push(self.text_style().to_run(range.start - offset));
1115                }
1116
1117                let mut run_style = self.text_style();
1118                if let Some(highlight) = highlight_id.style(&self.syntax_theme) {
1119                    run_style = run_style.highlight(highlight);
1120                }
1121                self.pending_line.runs.push(run_style.to_run(range.len()));
1122                offset = range.end;
1123            }
1124
1125            if offset < text.len() {
1126                self.pending_line
1127                    .runs
1128                    .push(self.text_style().to_run(text.len() - offset));
1129            }
1130        } else {
1131            self.pending_line
1132                .runs
1133                .push(self.text_style().to_run(text.len()));
1134        }
1135    }
1136
1137    fn trim_trailing_newline(&mut self) {
1138        if self.pending_line.text.ends_with('\n') {
1139            self.pending_line
1140                .text
1141                .truncate(self.pending_line.text.len() - 1);
1142            self.pending_line.runs.last_mut().unwrap().len -= 1;
1143            self.current_source_index -= 1;
1144        }
1145    }
1146
1147    fn flush_text(&mut self) {
1148        let line = mem::take(&mut self.pending_line);
1149        if line.text.is_empty() {
1150            return;
1151        }
1152
1153        let text = StyledText::new(line.text).with_runs(line.runs);
1154        self.rendered_lines.push(RenderedLine {
1155            layout: text.layout().clone(),
1156            source_mappings: line.source_mappings,
1157            source_end: self.current_source_index,
1158        });
1159        self.div_stack.last_mut().unwrap().extend([text.into_any()]);
1160    }
1161
1162    fn build(mut self) -> RenderedMarkdown {
1163        debug_assert_eq!(self.div_stack.len(), 1);
1164        self.flush_text();
1165        RenderedMarkdown {
1166            element: self.div_stack.pop().unwrap().into_any_element(),
1167            text: RenderedText {
1168                lines: self.rendered_lines.into(),
1169                links: self.rendered_links.into(),
1170            },
1171        }
1172    }
1173}
1174
1175struct RenderedLine {
1176    layout: TextLayout,
1177    source_mappings: Vec<SourceMapping>,
1178    source_end: usize,
1179}
1180
1181impl RenderedLine {
1182    fn rendered_index_for_source_index(&self, source_index: usize) -> usize {
1183        let mapping = match self
1184            .source_mappings
1185            .binary_search_by_key(&source_index, |probe| probe.source_index)
1186        {
1187            Ok(ix) => &self.source_mappings[ix],
1188            Err(ix) => &self.source_mappings[ix - 1],
1189        };
1190        mapping.rendered_index + (source_index - mapping.source_index)
1191    }
1192
1193    fn source_index_for_rendered_index(&self, rendered_index: usize) -> usize {
1194        let mapping = match self
1195            .source_mappings
1196            .binary_search_by_key(&rendered_index, |probe| probe.rendered_index)
1197        {
1198            Ok(ix) => &self.source_mappings[ix],
1199            Err(ix) => &self.source_mappings[ix - 1],
1200        };
1201        mapping.source_index + (rendered_index - mapping.rendered_index)
1202    }
1203
1204    fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
1205        let line_rendered_index;
1206        let out_of_bounds;
1207        match self.layout.index_for_position(position) {
1208            Ok(ix) => {
1209                line_rendered_index = ix;
1210                out_of_bounds = false;
1211            }
1212            Err(ix) => {
1213                line_rendered_index = ix;
1214                out_of_bounds = true;
1215            }
1216        };
1217        let source_index = self.source_index_for_rendered_index(line_rendered_index);
1218        if out_of_bounds {
1219            Err(source_index)
1220        } else {
1221            Ok(source_index)
1222        }
1223    }
1224}
1225
1226#[derive(Copy, Clone, Debug, Default)]
1227struct SourceMapping {
1228    rendered_index: usize,
1229    source_index: usize,
1230}
1231
1232pub struct RenderedMarkdown {
1233    element: AnyElement,
1234    text: RenderedText,
1235}
1236
1237#[derive(Clone)]
1238struct RenderedText {
1239    lines: Rc<[RenderedLine]>,
1240    links: Rc<[RenderedLink]>,
1241}
1242
1243#[derive(Clone, Eq, PartialEq)]
1244struct RenderedLink {
1245    source_range: Range<usize>,
1246    destination_url: SharedString,
1247}
1248
1249impl RenderedText {
1250    fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
1251        let mut lines = self.lines.iter().peekable();
1252
1253        while let Some(line) = lines.next() {
1254            let line_bounds = line.layout.bounds();
1255            if position.y > line_bounds.bottom() {
1256                if let Some(next_line) = lines.peek() {
1257                    if position.y < next_line.layout.bounds().top() {
1258                        return Err(line.source_end);
1259                    }
1260                }
1261
1262                continue;
1263            }
1264
1265            return line.source_index_for_position(position);
1266        }
1267
1268        Err(self.lines.last().map_or(0, |line| line.source_end))
1269    }
1270
1271    fn position_for_source_index(&self, source_index: usize) -> Option<(Point<Pixels>, Pixels)> {
1272        for line in self.lines.iter() {
1273            let line_source_start = line.source_mappings.first().unwrap().source_index;
1274            if source_index < line_source_start {
1275                break;
1276            } else if source_index > line.source_end {
1277                continue;
1278            } else {
1279                let line_height = line.layout.line_height();
1280                let rendered_index_within_line = line.rendered_index_for_source_index(source_index);
1281                let position = line.layout.position_for_index(rendered_index_within_line)?;
1282                return Some((position, line_height));
1283            }
1284        }
1285        None
1286    }
1287
1288    fn surrounding_word_range(&self, source_index: usize) -> Range<usize> {
1289        for line in self.lines.iter() {
1290            if source_index > line.source_end {
1291                continue;
1292            }
1293
1294            let line_rendered_start = line.source_mappings.first().unwrap().rendered_index;
1295            let rendered_index_in_line =
1296                line.rendered_index_for_source_index(source_index) - line_rendered_start;
1297            let text = line.layout.text();
1298            let previous_space = if let Some(idx) = text[0..rendered_index_in_line].rfind(' ') {
1299                idx + ' '.len_utf8()
1300            } else {
1301                0
1302            };
1303            let next_space = if let Some(idx) = text[rendered_index_in_line..].find(' ') {
1304                rendered_index_in_line + idx
1305            } else {
1306                text.len()
1307            };
1308
1309            return line.source_index_for_rendered_index(line_rendered_start + previous_space)
1310                ..line.source_index_for_rendered_index(line_rendered_start + next_space);
1311        }
1312
1313        source_index..source_index
1314    }
1315
1316    fn surrounding_line_range(&self, source_index: usize) -> Range<usize> {
1317        for line in self.lines.iter() {
1318            if source_index > line.source_end {
1319                continue;
1320            }
1321            let line_source_start = line.source_mappings.first().unwrap().source_index;
1322            return line_source_start..line.source_end;
1323        }
1324
1325        source_index..source_index
1326    }
1327
1328    fn text_for_range(&self, range: Range<usize>) -> String {
1329        let mut ret = vec![];
1330
1331        for line in self.lines.iter() {
1332            if range.start > line.source_end {
1333                continue;
1334            }
1335            let line_source_start = line.source_mappings.first().unwrap().source_index;
1336            if range.end < line_source_start {
1337                break;
1338            }
1339
1340            let text = line.layout.text();
1341
1342            let start = if range.start < line_source_start {
1343                0
1344            } else {
1345                line.rendered_index_for_source_index(range.start)
1346            };
1347            let end = if range.end > line.source_end {
1348                line.rendered_index_for_source_index(line.source_end)
1349            } else {
1350                line.rendered_index_for_source_index(range.end)
1351            }
1352            .min(text.len());
1353
1354            ret.push(text[start..end].to_string());
1355        }
1356        ret.join("\n")
1357    }
1358
1359    fn link_for_position(&self, position: Point<Pixels>) -> Option<&RenderedLink> {
1360        let source_index = self.source_index_for_position(position).ok()?;
1361        self.links
1362            .iter()
1363            .find(|link| link.source_range.contains(&source_index))
1364    }
1365}
1366
1367/// Some markdown blocks are indented, and others have e.g. ```rust … ``` around them.
1368/// If this block is fenced with backticks, strip them off (and the language name).
1369/// We use this when copying code blocks to the clipboard.
1370fn without_fences(mut markdown: &str) -> &str {
1371    if let Some(opening_backticks) = markdown.find("```") {
1372        markdown = &markdown[opening_backticks..];
1373
1374        // Trim off the next newline. This also trims off a language name if it's there.
1375        if let Some(newline) = markdown.find('\n') {
1376            markdown = &markdown[newline + 1..];
1377        }
1378    };
1379
1380    if let Some(closing_backticks) = markdown.rfind("```") {
1381        markdown = &markdown[..closing_backticks];
1382    };
1383
1384    markdown
1385}
1386
1387#[cfg(test)]
1388mod tests {
1389    use super::*;
1390
1391    #[test]
1392    fn test_without_fences() {
1393        let input = "```rust\nlet x = 5;\n```";
1394        assert_eq!(without_fences(input), "let x = 5;\n");
1395
1396        let input = "   ```\nno language\n```   ";
1397        assert_eq!(without_fences(input), "no language\n");
1398
1399        let input = "plain text";
1400        assert_eq!(without_fences(input), "plain text");
1401
1402        let input = "```python\nprint('hello')\nprint('world')\n```";
1403        assert_eq!(without_fences(input), "print('hello')\nprint('world')\n");
1404    }
1405}