markdown.rs

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