markdown.rs

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