Skip to main content

gpui_base/text/
node.rs

1use std::{
2    borrow::Cow,
3    collections::HashMap,
4    ops::Range,
5    sync::{Arc, Mutex, OnceLock},
6};
7
8use gpui::{
9    AnyElement, App, Axis, Bounds, DefiniteLength, Div, Element, ElementId, FontStyle, FontWeight,
10    GlobalElementId, HighlightStyle, Hsla, Image, ImageFormat, ImageSource, InspectorElementId,
11    InteractiveElement as _, IntoElement, IsZero as _, LayoutId, ObjectFit, Overflow,
12    ParentElement, Pixels, Point, Refineable as _, Rems, ScrollHandle, SharedString, SharedUri,
13    StatefulInteractiveElement, StyleRefinement, Styled, StyledImage as _, TextStyleRefinement,
14    WhiteSpace, Window, div, img, prelude::FluentBuilder as _, px, relative, rems,
15};
16use markdown::mdast;
17
18use crate::{
19    GlobalState, ScrollableMask, Scrollbar, StyledExt, h_flex,
20    scrollable_mask::horizontal_scroll_area,
21    text::{
22        CodeBlockActionsFn, CodeBlockHighlighterFn, Link, LinkClickHandlerFn, LinkFn,
23        MarkdownExtensions, MarkdownNode, TableActionsFn, TaskToggleEvent, TaskToggleHandlerFn,
24        document::{NodeRenderOptions, PrevBlock, flow_position},
25        inline::{
26            Inline, InlineHighlight, InlineState, code_insets, combine_highlights, fade_highlights,
27            foreground_highlights, point_in_text_selection, text_runs, text_size_ranges,
28        },
29        inline_flow::{InlineFlow, InlineFlowItem, slice_ranges},
30        range_highlight::{RangeHighlightFrame, RevealAt, RevealRequest},
31        stream_fade::{StreamFadeFrame, TextLeafKey},
32        text_view::handle_link_click,
33    },
34    theme::ActiveTheme as _,
35};
36
37use super::{
38    SelectionFormat, TextViewStyle,
39    utils::{data_url_image, list_item_prefix, ordered_list_ordinal},
40};
41
42const CHECK_SVG_LIGHT: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none"><path d="m3.25 8.25 3 3 6.5-7" stroke="white" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>"#;
43const CHECK_SVG_DARK: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none"><path d="m3.25 8.25 3 3 6.5-7" stroke="black" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>"#;
44
45/// The block-level nodes.
46///
47/// This is the document tree TextView renders. Together with
48/// [`editor_host`](super::editor_host) it is also the hand-over type for
49/// external editors: they build the tree, render it with
50/// [`BlockNode::render`] and read geometry back per leaf.
51#[derive(Debug, Clone, PartialEq)]
52#[non_exhaustive]
53pub enum BlockNode {
54    /// Something like a Div container in HTML.
55    Root {
56        children: Vec<BlockNode>,
57        span: Option<Span>,
58    },
59    Paragraph(Paragraph),
60    Heading {
61        level: u8,
62        children: Paragraph,
63        span: Option<Span>,
64    },
65    Blockquote {
66        children: Vec<BlockNode>,
67        span: Option<Span>,
68    },
69    /// A blockquote opening with the marker of a
70    /// [block surface](super::MarkdownExtensions::block_surface), drawn inside
71    /// the container registered for `name`.
72    ///
73    /// Its text, selection, highlights and reveals are its children's, which
74    /// leave out the marker line.
75    Surface {
76        /// The name it is registered under, in ASCII lowercase.
77        name: SharedString,
78        children: Vec<BlockNode>,
79        /// The source of the whole blockquote, marker included.
80        span: Option<Span>,
81    },
82    List {
83        /// Only contains ListItem, others will be ignored
84        children: Vec<BlockNode>,
85        ordered: bool,
86        /// The first ordinal for an ordered list. HTML lists leave this unset.
87        start: Option<u32>,
88        span: Option<Span>,
89    },
90    ListItem {
91        children: Vec<BlockNode>,
92        spread: bool,
93        /// Whether the list item is checked, if None, it's not a checkbox
94        checked: Option<bool>,
95        /// The source of a Markdown task item's `[ ]` / `[x]` marker.
96        task_marker: Option<Span>,
97        span: Option<Span>,
98    },
99    CodeBlock(CodeBlock),
100    /// A custom Markdown node produced by [`MarkdownExtensions`].
101    Custom {
102        node: MarkdownNode,
103        state: BlockState,
104    },
105    Table(Table),
106    Break {
107        html: bool,
108        span: Option<Span>,
109    },
110    HorizontalRule {
111        span: Option<Span>,
112    },
113    /// Use for to_markdown get raw definition
114    Definition {
115        identifier: SharedString,
116        url: SharedString,
117        title: Option<SharedString>,
118        span: Option<Span>,
119    },
120    Unknown,
121}
122
123/// Retained block interaction state, shared with its rendered element.
124///
125/// Opaque: build one with `BlockState::default()` for a
126/// [`BlockNode::Custom`].
127#[derive(Debug, Clone, Default)]
128pub struct BlockState {
129    // None is unobserved, allowing virtualized copy to include enclosed blocks.
130    selection: Arc<Mutex<Option<BlockSelection>>>,
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134enum BlockSelection {
135    Empty,
136    Full,
137}
138
139impl BlockState {
140    fn selection(&self) -> Option<BlockSelection> {
141        self.selection.lock().ok().and_then(|selection| *selection)
142    }
143
144    fn set_selection(&self, value: Option<BlockSelection>) {
145        if let Ok(mut selection) = self.selection.lock() {
146            *selection = value;
147        }
148    }
149
150    fn is_selected(&self) -> bool {
151        self.selection() == Some(BlockSelection::Full)
152    }
153
154    fn has_selection_observation(&self) -> bool {
155        self.selection().is_some()
156    }
157
158    fn clear_selection(&self) {
159        self.set_selection(None);
160    }
161}
162
163impl PartialEq for BlockState {
164    fn eq(&self, _: &Self) -> bool {
165        // Runtime selection does not change parsed document identity.
166        true
167    }
168}
169
170pub(super) struct CustomBlockSelectionProjection {
171    state: BlockState,
172    bounds: Bounds<Pixels>,
173}
174
175impl CustomBlockSelectionProjection {
176    pub(super) fn project(&self, start: Point<Pixels>, end: Point<Pixels>) {
177        self.state
178            .set_selection(custom_block_selection(self.bounds, start, end));
179    }
180
181    pub(super) fn deselect(&self) {
182        self.state.set_selection(None);
183    }
184}
185
186fn custom_block_selection(
187    bounds: Bounds<Pixels>,
188    start: Point<Pixels>,
189    end: Point<Pixels>,
190) -> Option<BlockSelection> {
191    if bounds.size.width <= Pixels::ZERO
192        || bounds.size.height <= Pixels::ZERO
193        || bounds.bottom() <= start.y.min(end.y)
194        || bounds.top() > start.y.max(end.y)
195    {
196        return None;
197    }
198    Some(if custom_block_is_selected(bounds, start, end) {
199        BlockSelection::Full
200    } else {
201        BlockSelection::Empty
202    })
203}
204
205/// A table cell, laid out as its content. Text painted inside it knows its
206/// cell, so a drag that starts in the cell selects only in that cell.
207struct TableCellElement(AnyElement);
208
209#[cfg(not(feature = "gpui-fast"))]
210impl IntoElement for TableCellElement {
211    type Element = Self;
212
213    fn into_element(self) -> Self {
214        self
215    }
216}
217
218impl Element for TableCellElement {
219    type RequestLayoutState = ();
220    type PrepaintState = ();
221
222    fn id(&self) -> Option<ElementId> {
223        None
224    }
225
226    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
227        None
228    }
229
230    fn request_layout(
231        &mut self,
232        _: Option<&GlobalElementId>,
233        _: Option<&InspectorElementId>,
234        window: &mut Window,
235        cx: &mut App,
236    ) -> (LayoutId, ()) {
237        (self.0.request_layout(window, cx), ())
238    }
239
240    fn prepaint(
241        &mut self,
242        _: Option<&GlobalElementId>,
243        _: Option<&InspectorElementId>,
244        bounds: Bounds<Pixels>,
245        _: &mut (),
246        window: &mut Window,
247        cx: &mut App,
248    ) {
249        // Prepaint runs for the whole window before any text paints, so the
250        // cell that holds the anchor is known to all text, in every view.
251        if let Some(view) = GlobalState::global(cx).text_view_state() {
252            view.read(cx)
253                .selection_adapter
254                .record_table_cell(bounds, cx);
255        }
256        GlobalState::global(cx).push_table_cell(bounds);
257        self.0.prepaint(window, cx);
258        GlobalState::global(cx).pop_table_cell();
259    }
260
261    fn paint(
262        &mut self,
263        _: Option<&GlobalElementId>,
264        _: Option<&InspectorElementId>,
265        bounds: Bounds<Pixels>,
266        _: &mut (),
267        _: &mut (),
268        window: &mut Window,
269        cx: &mut App,
270    ) {
271        GlobalState::global(cx).push_table_cell(bounds);
272        self.0.paint(window, cx);
273        GlobalState::global(cx).pop_table_cell();
274    }
275}
276
277/// Observe the plugin's own bounds without changing its layout or listeners.
278struct CustomBlockElement {
279    content: AnyElement,
280    state: BlockState,
281    /// A pending reveal of this block, when it is inside a block surface and
282    /// so has no row of its own to scroll to.
283    reveal: Option<RevealAt>,
284}
285
286#[cfg(not(feature = "gpui-fast"))]
287impl IntoElement for CustomBlockElement {
288    type Element = Self;
289
290    fn into_element(self) -> Self {
291        self
292    }
293}
294
295impl Element for CustomBlockElement {
296    type RequestLayoutState = ();
297    type PrepaintState = ();
298
299    fn id(&self) -> Option<ElementId> {
300        None
301    }
302
303    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
304        None
305    }
306
307    fn request_layout(
308        &mut self,
309        _: Option<&GlobalElementId>,
310        _: Option<&InspectorElementId>,
311        window: &mut Window,
312        cx: &mut App,
313    ) -> (LayoutId, ()) {
314        (self.content.request_layout(window, cx), ())
315    }
316
317    fn prepaint(
318        &mut self,
319        _: Option<&GlobalElementId>,
320        _: Option<&InspectorElementId>,
321        bounds: Bounds<Pixels>,
322        _: &mut (),
323        window: &mut Window,
324        cx: &mut App,
325    ) {
326        self.content.prepaint(window, cx);
327        if let Some(reveal) = &self.reveal {
328            // A list scrolls to its edge, which layout may miss by a fraction of
329            // a pixel.
330            let slack = px(0.5);
331            let view = window.content_mask().bounds;
332            let inside =
333                bounds.top() >= view.top() - slack && bounds.bottom() <= view.bottom() + slack;
334            // A block taller than the view has no place to scroll to where it
335            // fits, and asking from each edge in turn would never settle.
336            let fills =
337                bounds.top() <= view.top() + slack && bounds.bottom() >= view.bottom() - slack;
338            let visible = inside || fills;
339            if !visible {
340                window.request_autoscroll(bounds);
341            }
342            reveal.report(bounds, visible);
343        }
344    }
345
346    fn paint(
347        &mut self,
348        _: Option<&GlobalElementId>,
349        _: Option<&InspectorElementId>,
350        bounds: Bounds<Pixels>,
351        _: &mut (),
352        _: &mut (),
353        window: &mut Window,
354        cx: &mut App,
355    ) {
356        let view = GlobalState::global(cx).text_view_state();
357        let selection = view.as_ref().and_then(|view| {
358            let state = view.read(cx);
359            if !state.is_selectable() {
360                return None;
361            }
362            if state.is_all_selected() {
363                return Some(BlockSelection::Full);
364            }
365            if state.preserve_inline_selection {
366                return self.state.selection();
367            }
368            let (start, end) = state.painted_selection_points(cx)?;
369            custom_block_selection(bounds, start, end)
370        });
371        self.state.set_selection(selection);
372        if let Some(view) = &view {
373            if view.read(cx).is_selectable() {
374                view.read(cx).selection_adapter.register_copy_projection(
375                    super::selection_adapter::CopyProjection::CustomBlock(
376                        CustomBlockSelectionProjection {
377                            state: self.state.clone(),
378                            bounds,
379                        },
380                    ),
381                    cx,
382                );
383            }
384            let visible = bounds.intersect(&window.content_mask().bounds);
385            if view.read(cx).is_selectable()
386                && visible.size.width > Pixels::ZERO
387                && visible.size.height > Pixels::ZERO
388            {
389                view.read(cx)
390                    .selection_adapter
391                    .register_inline(vec![visible]);
392            }
393        }
394        self.content.paint(window, cx);
395        if selection == Some(BlockSelection::Full) {
396            let color = view.as_ref().unwrap().read(cx).text_view_style.selection();
397            window.paint_quad(gpui::fill(bounds, color));
398        }
399    }
400}
401
402/// A block is atomic: the selection takes it whole once it crosses the block's
403/// edge, and never from a gesture that stays inside it. A press and release
404/// within one block is a click on its content — often an interactive card —
405/// and the pointer commonly travels a few pixels during a quick click, so
406/// counting that travel as a drag would paint the whole block as selected.
407fn custom_block_is_selected(
408    bounds: Bounds<Pixels>,
409    start: Point<Pixels>,
410    end: Point<Pixels>,
411) -> bool {
412    let (start_inside, end_inside) = (bounds.contains(&start), bounds.contains(&end));
413    start != end
414        && !(start_inside && end_inside)
415        && (start_inside
416            || end_inside
417            || point_in_text_selection(
418                bounds.origin,
419                bounds.size.width,
420                start,
421                end,
422                bounds.size.height,
423            ))
424}
425
426/// How many styles a selection takes in, which decides whether
427/// [`SelectionFormat::SourceAcrossStyles`] copies the rendered text or the
428/// source.
429#[derive(Clone, Copy, Debug, PartialEq, Eq)]
430pub(super) enum SelectionStyles {
431    None,
432    One,
433    Mixed,
434}
435
436impl SelectionStyles {
437    /// Combine two separately selected parts. They are two styles even when
438    /// their marks match, because they sit in different blocks or cells.
439    fn merge(&mut self, other: Self) {
440        *self = match (*self, other) {
441            (Self::None, other) | (other, Self::None) => other,
442            _ => Self::Mixed,
443        };
444    }
445}
446
447#[derive(Clone, Copy)]
448enum BlockTextKind {
449    All,
450    Selected,
451    /// Like `Selected`, but reconstructs Markdown source for the selection
452    /// instead of the rendered plain text.
453    SelectedSource,
454}
455
456impl BlockNode {
457    pub(super) fn is_list_item(&self) -> bool {
458        matches!(self, Self::ListItem { .. })
459    }
460
461    /// Whether this block shows nothing: a link definition, a comment, a `<br>`.
462    fn draws_nothing(&self) -> bool {
463        match self {
464            Self::Definition { .. } | Self::Break { .. } | Self::Unknown => true,
465            Self::Root { children, .. } => children.iter().all(Self::draws_nothing),
466            Self::Paragraph(paragraph) => paragraph.children().iter().all(|inline| {
467                inline.as_image().is_none()
468                    && inline.as_custom().is_none()
469                    && inline.text().trim().is_empty()
470            }),
471            _ => false,
472        }
473    }
474
475    /// Combine all children, omitting the empt parent nodes.
476    pub(super) fn compact(self) -> BlockNode {
477        match self {
478            Self::Root { mut children, .. } if children.len() == 1 => children.remove(0).compact(),
479            _ => self,
480        }
481    }
482
483    /// Get the span of the node.
484    pub fn span(&self) -> Option<Span> {
485        match self {
486            BlockNode::Root { span, .. } => *span,
487            BlockNode::Paragraph(paragraph) => paragraph.span,
488            BlockNode::Heading { span, .. } => *span,
489            BlockNode::Blockquote { span, .. } => *span,
490            BlockNode::Surface { span, .. } => *span,
491            BlockNode::List { span, .. } => *span,
492            BlockNode::ListItem { span, .. } => *span,
493            BlockNode::CodeBlock(code_block) => code_block.span,
494            BlockNode::Custom { node, .. } => node.span,
495            BlockNode::Table(table) => table.span,
496            BlockNode::Break { span, .. } => *span,
497            BlockNode::HorizontalRule { span, .. } => *span,
498            BlockNode::Definition { span, .. } => *span,
499            BlockNode::Unknown { .. } => None,
500        }
501    }
502
503    pub(super) fn text(&self) -> String {
504        self.text_by_kind(BlockTextKind::All)
505    }
506
507    /// The selected text within this block, in `format`.
508    ///
509    /// [`SelectionFormat::Source`] reconstructs the Markdown source of the
510    /// selection instead of the rendered text.
511    pub(super) fn selected_text(&self, format: SelectionFormat) -> String {
512        self.text_by_kind(match format {
513            SelectionFormat::Plain => BlockTextKind::Selected,
514            SelectionFormat::Source | SelectionFormat::SourceAcrossStyles => {
515                BlockTextKind::SelectedSource
516            }
517        })
518    }
519
520    /// How many styles the selection within this block takes in.
521    pub(super) fn selection_styles(&self) -> SelectionStyles {
522        let mut styles = SelectionStyles::None;
523        match self {
524            BlockNode::Root { children, .. }
525            | BlockNode::Blockquote { children, .. }
526            | BlockNode::Surface { children, .. }
527            | BlockNode::List { children, .. }
528            | BlockNode::ListItem { children, .. } => {
529                for child in children {
530                    styles.merge(child.selection_styles());
531                }
532            }
533            BlockNode::Paragraph(paragraph) => styles = paragraph.selection_styles(),
534            BlockNode::Heading { children, .. } => styles = children.selection_styles(),
535            BlockNode::Table(table) => {
536                for row in &table.children {
537                    for cell in &row.children {
538                        styles.merge(cell.children.selection_styles());
539                    }
540                }
541            }
542            BlockNode::CodeBlock(code_block) => {
543                if code_block.has_selection() {
544                    styles = SelectionStyles::One;
545                }
546            }
547            // A plugin's text stands in for content its source spells out.
548            BlockNode::Custom { state, .. } => {
549                if state.is_selected() {
550                    styles = SelectionStyles::Mixed;
551                }
552            }
553            BlockNode::Definition { .. }
554            | BlockNode::Break { .. }
555            | BlockNode::HorizontalRule { .. }
556            | BlockNode::Unknown => {}
557        }
558        styles
559    }
560
561    pub(super) fn selected_source_range(&self) -> SourceRangeSelection {
562        let mut selected = SourceRangeSelection::Unselected;
563        match self {
564            BlockNode::Root { children, .. }
565            | BlockNode::Blockquote { children, .. }
566            | BlockNode::Surface { children, .. }
567            | BlockNode::List { children, .. }
568            | BlockNode::ListItem { children, .. } => {
569                for child in children {
570                    selected.merge(child.selected_source_range());
571                }
572            }
573            BlockNode::Paragraph(paragraph) => selected = paragraph.selected_source_range(),
574            BlockNode::Heading { children, .. } => selected = children.selected_source_range(),
575            BlockNode::Table(table) => {
576                for row in &table.children {
577                    for cell in &row.children {
578                        selected.merge(cell.children.selected_source_range());
579                    }
580                }
581            }
582            BlockNode::CodeBlock(code_block) => selected = code_block.selected_source_range(),
583            BlockNode::Custom { node, state } => {
584                if state.is_selected() {
585                    selected = node
586                        .source_range()
587                        .map_or(SourceRangeSelection::Unmapped, SourceRangeSelection::Mapped);
588                }
589            }
590            BlockNode::Definition { .. }
591            | BlockNode::Break { .. }
592            | BlockNode::HorizontalRule { .. }
593            | BlockNode::Unknown => {}
594        }
595        selected
596    }
597
598    fn text_by_kind(&self, kind: BlockTextKind) -> String {
599        let mut text = String::new();
600        match self {
601            BlockNode::Root { children, .. } => {
602                let block_text = Self::children_text(children, kind);
603                if !block_text.is_empty() {
604                    text.push_str(&block_text);
605                    text.push('\n');
606                }
607            }
608            BlockNode::Paragraph(paragraph) => {
609                let block_text = match kind {
610                    BlockTextKind::All => paragraph.text(),
611                    BlockTextKind::Selected => paragraph.selected_text(),
612                    BlockTextKind::SelectedSource => paragraph.selected_source(),
613                };
614                if !block_text.is_empty() {
615                    text.push_str(&block_text);
616                    text.push('\n');
617                }
618            }
619            BlockNode::Heading {
620                level, children, ..
621            } => {
622                let block_text = match kind {
623                    BlockTextKind::All => children.text(),
624                    BlockTextKind::Selected => children.selected_text(),
625                    BlockTextKind::SelectedSource => children.selected_source(),
626                };
627                if !block_text.is_empty() {
628                    // In source mode, prefix the heading marker so a selected
629                    // heading round-trips as Markdown (e.g. `## Title`).
630                    if matches!(kind, BlockTextKind::SelectedSource) {
631                        text.push_str(&"#".repeat(*level as usize));
632                        text.push(' ');
633                    }
634                    text.push_str(&block_text);
635                    text.push('\n');
636                }
637            }
638            BlockNode::List {
639                children,
640                ordered,
641                start,
642                ..
643            } => {
644                if matches!(kind, BlockTextKind::SelectedSource) {
645                    // Reconstruct the list source, indenting nested lists and
646                    // restoring list markers and task-list checkboxes.
647                    text.push_str(&list_selected_source(children, *ordered, *start, ""));
648                } else {
649                    text.push_str(&Self::children_text(children, kind));
650                }
651            }
652            BlockNode::ListItem { children, .. } => {
653                text.push_str(&Self::children_text(children, kind));
654            }
655            BlockNode::Blockquote { children, .. } => {
656                let block_text = Self::children_text(children, kind);
657
658                if !block_text.is_empty() {
659                    if matches!(kind, BlockTextKind::SelectedSource) {
660                        text.push_str(&quoted_source(None, &block_text));
661                    } else {
662                        text.push_str(&block_text);
663                    }
664                    text.push('\n');
665                }
666            }
667            BlockNode::Surface { name, children, .. } => {
668                let block_text = Self::children_text(children, kind);
669                if matches!(kind, BlockTextKind::SelectedSource) {
670                    // Quoted under its marker, as a blockquote's selection is
671                    // quoted, so that it round-trips as the same surface.
672                    if !block_text.is_empty() {
673                        text.push_str(&quoted_source(Some(name), &block_text));
674                        text.push('\n');
675                    }
676                } else {
677                    text.push_str(&block_text);
678                }
679            }
680            BlockNode::Table(table) => {
681                if matches!(kind, BlockTextKind::SelectedSource) {
682                    let block_text = table_selected_source(table);
683                    if !block_text.is_empty() {
684                        text.push_str(&block_text);
685                        text.push('\n');
686                    }
687                } else {
688                    let mut block_text = String::new();
689                    for row in table.children.iter() {
690                        let mut row_texts = vec![];
691                        for cell in row.children.iter() {
692                            match kind {
693                                BlockTextKind::All => row_texts.push(cell.children.text()),
694                                // Source is handled above; only Selected reaches
695                                // here. A cell with nothing selected adds nothing,
696                                // so a selection in one cell copies only its text.
697                                _ => {
698                                    let selected = cell.children.selected_text();
699                                    if !selected.is_empty() {
700                                        row_texts.push(selected);
701                                    }
702                                }
703                            }
704                        }
705                        if !row_texts.is_empty() {
706                            block_text.push_str(&row_texts.join(" "));
707                            block_text.push('\n');
708                        }
709                    }
710
711                    if !block_text.is_empty() {
712                        text.push_str(&block_text);
713                        text.push('\n');
714                    }
715                }
716            }
717            BlockNode::CodeBlock(code_block) => {
718                let block_text = match kind {
719                    BlockTextKind::All => code_block.text(),
720                    BlockTextKind::Selected => code_block.selected_text(),
721                    BlockTextKind::SelectedSource => code_block.selected_source(),
722                };
723                if !block_text.is_empty() {
724                    text.push_str(&block_text);
725                    text.push('\n');
726                }
727            }
728            BlockNode::Custom { node, state } => {
729                if matches!(kind, BlockTextKind::All) || state.is_selected() {
730                    let content = match kind {
731                        BlockTextKind::SelectedSource => Cow::Owned(node.to_markdown()),
732                        _ => Cow::Borrowed(node.as_text()),
733                    };
734                    if !content.is_empty() {
735                        text.push_str(&content);
736                        text.push('\n');
737                    }
738                }
739            }
740            BlockNode::Definition { .. }
741            | BlockNode::Break { .. }
742            | BlockNode::HorizontalRule { .. }
743            | BlockNode::Unknown { .. } => {}
744        }
745
746        text
747    }
748
749    fn children_text(children: &[BlockNode], kind: BlockTextKind) -> String {
750        let mut text = String::new();
751        for child in children.iter() {
752            text.push_str(&child.text_by_kind(kind));
753        }
754
755        text
756    }
757
758    /// Synchronously clear the selection stored in every inline state.
759    ///
760    /// Mirrors the [`selected_text`](Self::selected_text) traversal so the
761    /// selection can be cleared without relying on a repaint.
762    /// Whether this block carries a selection, even an empty one.
763    ///
764    /// A block only learns its selection when it is painted, so this doubles as
765    /// "this block was on screen while the selection was made". An empty
766    /// selection is the caret left by the press that started the drag, which is
767    /// why it counts (see [`ParsedDocument::selected_text`]).
768    pub(super) fn has_selection(&self) -> bool {
769        match self {
770            BlockNode::Root { children, .. }
771            | BlockNode::Blockquote { children, .. }
772            | BlockNode::Surface { children, .. }
773            | BlockNode::List { children, .. }
774            | BlockNode::ListItem { children, .. } => {
775                children.iter().any(|child| child.has_selection())
776            }
777            BlockNode::Paragraph(paragraph) => paragraph.has_selection(),
778            BlockNode::Heading { children, .. } => children.has_selection(),
779            BlockNode::Table(table) => table.children.iter().any(|row| {
780                row.children
781                    .iter()
782                    .any(|cell| cell.children.has_selection())
783            }),
784            BlockNode::CodeBlock(code_block) => code_block.has_selection(),
785            BlockNode::Custom { state, .. } => {
786                // An observed empty endpoint must suppress virtualized copy fallback.
787                state.has_selection_observation()
788            }
789            BlockNode::Definition { .. }
790            | BlockNode::Break { .. }
791            | BlockNode::HorizontalRule { .. }
792            | BlockNode::Unknown { .. } => false,
793        }
794    }
795
796    pub(super) fn clear_selection(&self) {
797        match self {
798            BlockNode::Root { children, .. }
799            | BlockNode::Blockquote { children, .. }
800            | BlockNode::Surface { children, .. }
801            | BlockNode::List { children, .. }
802            | BlockNode::ListItem { children, .. } => {
803                for child in children.iter() {
804                    child.clear_selection();
805                }
806            }
807            BlockNode::Paragraph(paragraph) => paragraph.clear_selection(),
808            BlockNode::Heading { children, .. } => children.clear_selection(),
809            BlockNode::Table(table) => {
810                for row in table.children.iter() {
811                    for cell in row.children.iter() {
812                        cell.children.clear_selection();
813                    }
814                }
815            }
816            BlockNode::CodeBlock(code_block) => code_block.clear_selection(),
817            BlockNode::Custom { state, .. } => {
818                state.clear_selection();
819            }
820            BlockNode::Definition { .. }
821            | BlockNode::Break { .. }
822            | BlockNode::HorizontalRule { .. }
823            | BlockNode::Unknown { .. } => {}
824        }
825    }
826}
827
828#[allow(unused)]
829#[derive(Debug, Default, Clone, PartialEq)]
830pub struct LinkMark {
831    pub url: SharedString,
832    /// Optional identifier for footnotes.
833    pub identifier: Option<SharedString>,
834    pub title: Option<SharedString>,
835}
836
837#[derive(Debug, Default, Clone, PartialEq)]
838pub struct TextMark {
839    pub bold: bool,
840    pub italic: bool,
841    pub strikethrough: bool,
842    pub underline: bool,
843    pub code: bool,
844    /// Highlight (`<mark>`) the text with this background color.
845    ///
846    /// `None` means the text is not highlighted.
847    pub highlight: Option<Hsla>,
848    pub link: Option<LinkMark>,
849}
850
851impl TextMark {
852    pub fn bold(mut self) -> Self {
853        self.bold = true;
854        self
855    }
856
857    pub fn italic(mut self) -> Self {
858        self.italic = true;
859        self
860    }
861
862    pub fn strikethrough(mut self) -> Self {
863        self.strikethrough = true;
864        self
865    }
866
867    pub fn underline(mut self) -> Self {
868        self.underline = true;
869        self
870    }
871
872    pub fn code(mut self) -> Self {
873        self.code = true;
874        self
875    }
876
877    /// Mark the text as highlighted (`<mark>`) with the given background color.
878    pub fn highlight(mut self, color: Hsla) -> Self {
879        self.highlight = Some(color);
880        self
881    }
882
883    pub fn link(mut self, link: impl Into<LinkMark>) -> Self {
884        self.link = Some(link.into());
885        self
886    }
887
888    pub fn merge(&mut self, other: TextMark) {
889        self.bold |= other.bold;
890        self.italic |= other.italic;
891        self.strikethrough |= other.strikethrough;
892        self.underline |= other.underline;
893        self.code |= other.code;
894        if other.highlight.is_some() {
895            self.highlight = other.highlight;
896        }
897        if let Some(link) = other.link {
898            self.link = Some(link);
899        }
900    }
901}
902
903/// The bytes
904#[derive(Debug, Default, Copy, Clone, PartialEq)]
905pub struct Span {
906    pub start: usize,
907    pub end: usize,
908}
909
910#[allow(unused)]
911#[derive(Default, Clone)]
912pub struct ImageNode {
913    pub url: SharedUri,
914    pub link: Option<LinkMark>,
915    pub title: Option<SharedString>,
916    pub alt: Option<SharedString>,
917    pub width: Option<DefiniteLength>,
918    pub height: Option<DefiniteLength>,
919    pub(crate) span: Option<Span>,
920    /// The image a `data:` URL carries, decoded on first render and kept for
921    /// the node's lifetime so it is not decoded again every frame.
922    pub(super) embedded: OnceLock<Option<Arc<Image>>>,
923}
924
925impl ImageNode {
926    pub fn title(&self) -> String {
927        self.title
928            .clone()
929            .unwrap_or_else(|| self.alt.clone().unwrap_or_default())
930            .to_string()
931    }
932
933    /// The [`ImageSource`] to render, without granting implicit filesystem
934    /// access.
935    ///
936    /// A `data:` URL carries its image inline, so it is decoded here rather
937    /// than handed to GPUI's resource loader, which only fetches over HTTP.
938    /// Every other document-provided value remains URI-backed, including
939    /// `file://` and scheme-less strings.
940    pub(super) fn source(&self) -> ImageSource {
941        match self.embedded.get_or_init(|| data_url_image(&self.url)) {
942            Some(image) => ImageSource::Image(image.clone()),
943            None => self.url.clone().into(),
944        }
945    }
946}
947
948impl std::fmt::Debug for ImageNode {
949    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
950        f.debug_struct("ImageNode")
951            .field("url", &self.url)
952            .field("link", &self.link)
953            .field("title", &self.title)
954            .field("alt", &self.alt)
955            .field("width", &self.width)
956            .field("height", &self.height)
957            .field("span", &self.span)
958            .finish()
959    }
960}
961
962impl PartialEq for ImageNode {
963    fn eq(&self, other: &Self) -> bool {
964        self.url == other.url
965            && self.link == other.link
966            && self.title == other.title
967            && self.alt == other.alt
968            && self.width == other.width
969            && self.height == other.height
970            && self.span == other.span
971    }
972}
973
974#[derive(Debug, Clone, PartialEq)]
975pub(crate) struct SourceSegment {
976    pub(crate) rendered: Range<usize>,
977    pub(crate) source: Range<usize>,
978    /// Whether each rendered character came from a source character of the
979    /// same length, so that part of the segment maps to part of its source.
980    /// A decoded entity or an escape maps only as a whole, even an entity
981    /// whose characters take as many bytes as its source, like `&acE;`.
982    pub(crate) linear: bool,
983}
984
985pub(crate) enum SourceRangeSelection {
986    Unselected,
987    Mapped(Range<usize>),
988    Unmapped,
989}
990
991impl SourceRangeSelection {
992    pub(crate) fn merge(&mut self, other: Self) {
993        match (&mut *self, other) {
994            (_, Self::Unselected) => {}
995            (_, Self::Unmapped) => *self = Self::Unmapped,
996            (Self::Unselected, mapped @ Self::Mapped(_)) => *self = mapped,
997            (Self::Mapped(selected), Self::Mapped(range)) => {
998                selected.start = selected.start.min(range.start);
999                selected.end = selected.end.max(range.end);
1000            }
1001            (Self::Unmapped, Self::Mapped(_)) => {}
1002        }
1003    }
1004
1005    pub(crate) fn into_range(self) -> Option<Range<usize>> {
1006        match self {
1007            Self::Mapped(range) => Some(range),
1008            Self::Unselected | Self::Unmapped => None,
1009        }
1010    }
1011}
1012
1013fn source_range_for_segments(
1014    segments: &[SourceSegment],
1015    selection: Range<usize>,
1016) -> Option<Range<usize>> {
1017    fn mapped_source_start(segment: &SourceSegment, rendered_start: usize) -> usize {
1018        if segment.linear {
1019            segment.source.start + rendered_start.saturating_sub(segment.rendered.start)
1020        } else {
1021            segment.source.start
1022        }
1023    }
1024
1025    fn mapped_source_end(segment: &SourceSegment, rendered_end: usize) -> usize {
1026        if segment.linear {
1027            segment.source.start
1028                + rendered_end
1029                    .min(segment.rendered.end)
1030                    .saturating_sub(segment.rendered.start)
1031        } else {
1032            segment.source.end
1033        }
1034    }
1035
1036    if selection.start >= selection.end {
1037        return None;
1038    }
1039
1040    let mut overlapping = segments.iter().filter(|segment| {
1041        segment.rendered.start < selection.end && segment.rendered.end > selection.start
1042    });
1043    let first = overlapping.next()?;
1044    if first.rendered.start > selection.start {
1045        return None;
1046    }
1047    let mut rendered_end = first.rendered.end;
1048    let source_start = mapped_source_start(first, selection.start);
1049    let mut source_end = mapped_source_end(first, selection.end);
1050    for segment in overlapping {
1051        if segment.rendered.start > rendered_end {
1052            return None;
1053        }
1054        rendered_end = rendered_end.max(segment.rendered.end);
1055        source_end = mapped_source_end(segment, selection.end);
1056    }
1057    (rendered_end >= selection.end).then_some(source_start..source_end)
1058}
1059
1060/// One run of inline content in a [`Paragraph`]: marked text, an image or a
1061/// custom inline node.
1062#[derive(Default, Clone, Debug)]
1063pub struct InlineNode {
1064    /// The text content.
1065    pub(crate) text: SharedString,
1066    pub(crate) image: Option<ImageNode>,
1067    pub(crate) custom: Option<MarkdownNode>,
1068    custom_selection: Arc<Mutex<bool>>,
1069    /// The text styles, each tuple contains the range of the text and the style.
1070    pub(crate) marks: Vec<(Range<usize>, TextMark)>,
1071    /// Rendered UTF-8 byte spans paired with their exact Markdown source spans.
1072    pub(crate) source_segments: Vec<SourceSegment>,
1073
1074    pub(super) state: Arc<Mutex<InlineState>>,
1075}
1076
1077impl PartialEq for InlineNode {
1078    fn eq(&self, other: &Self) -> bool {
1079        self.text == other.text
1080            && self.image == other.image
1081            && self.custom == other.custom
1082            && self.marks == other.marks
1083            && self.source_segments == other.source_segments
1084    }
1085}
1086
1087fn set_leaf_key(state: &mut Arc<Mutex<InlineState>>, key: u64) {
1088    let text = state
1089        .lock()
1090        .map(|state| state.text.clone())
1091        .unwrap_or_default();
1092    // Rekeying creates a new rendered identity. Do not mutate the state of
1093    // another AST clone (or carry its transient selection into this instance).
1094    *state = Arc::new(Mutex::new(InlineState {
1095        text,
1096        editor_key: Some(key),
1097        selection_rows: None,
1098        cleanup_senders: Vec::new(),
1099        ..Default::default()
1100    }));
1101}
1102
1103/// Wrap `text` with the Markdown syntax implied by `mark`.
1104///
1105/// This mirrors the per-mark formatting in [`Paragraph::to_markdown`] but
1106/// operates on an already-sliced run, so it can reconstruct the Markdown
1107/// source for a *partial* text selection. Applied inside-out (innermost markup
1108/// first) so nested emphasis like `**_x_**` round-trips.
1109pub(crate) fn wrap_with_mark(text: &str, mark: &TextMark) -> String {
1110    if text.is_empty() {
1111        return String::new();
1112    }
1113
1114    let mut out = text.to_string();
1115    if mark.code {
1116        out = format!("`{}`", out);
1117    }
1118    if mark.italic {
1119        out = format!("*{}*", out);
1120    }
1121    if mark.bold {
1122        out = format!("**{}**", out);
1123    }
1124    if mark.strikethrough {
1125        out = format!("~~{}~~", out);
1126    }
1127    if mark.underline {
1128        // Markdown has no underline syntax, and `__` reads as bold to most
1129        // parsers, so fall back to the inline HTML `<u>` parses from.
1130        out = format!("<u>{}</u>", out);
1131    }
1132    if mark.highlight.is_some() {
1133        out = format!("=={}==", out);
1134    }
1135    if let Some(link) = &mark.link {
1136        out = match &link.title {
1137            Some(title) => format!("[{}]({} \"{}\")", out, link.url, title),
1138            None => format!("[{}]({})", out, link.url),
1139        };
1140    }
1141    out
1142}
1143
1144/// Keep syntax and marks separate until all selected runs and atomic objects
1145/// have been collected. Wrapping every run independently creates adjacent `*`
1146/// delimiters that can turn italic formulas into bold ones when pasted.
1147#[derive(Default)]
1148struct MarkdownSource {
1149    pieces: Vec<(String, Vec<TextMark>)>,
1150    /// Whether an inline object or image was emitted, whose rendered text
1151    /// stands in for source that spells out more.
1152    has_objects: bool,
1153}
1154
1155impl MarkdownSource {
1156    fn push_str(&mut self, source: &str) {
1157        self.push_marked(source, &TextMark::default());
1158    }
1159
1160    fn push_marked(&mut self, source: &str, mark: &TextMark) {
1161        if source.is_empty() {
1162            return;
1163        }
1164        // Outer-to-inner order for equally extensive marks. When a mark spans
1165        // more neighboring pieces, serialize it outside the shorter marks.
1166        let mut layers = Vec::new();
1167        if let Some(link) = &mark.link {
1168            layers.push(TextMark {
1169                link: Some(link.clone()),
1170                ..Default::default()
1171            });
1172        }
1173        if let Some(highlight) = mark.highlight {
1174            layers.push(TextMark {
1175                highlight: Some(highlight),
1176                ..Default::default()
1177            });
1178        }
1179        if mark.underline {
1180            layers.push(TextMark::default().underline());
1181        }
1182        if mark.strikethrough {
1183            layers.push(TextMark::default().strikethrough());
1184        }
1185        if mark.bold {
1186            layers.push(TextMark::default().bold());
1187        }
1188        if mark.italic {
1189            layers.push(TextMark::default().italic());
1190        }
1191        if mark.code {
1192            layers.push(TextMark::default().code());
1193        }
1194        self.pieces.push((source.to_string(), layers));
1195    }
1196
1197    fn push_text(
1198        &mut self,
1199        text: &str,
1200        marks: &[(Range<usize>, TextMark)],
1201        selection: Range<usize>,
1202    ) {
1203        let start = selection.start.min(text.len());
1204        let end = selection.end.min(text.len());
1205        if start >= end {
1206            return;
1207        }
1208        let mut cursor = start;
1209        for (range, mark) in marks {
1210            let lo = range.start.max(start);
1211            let hi = range.end.min(end);
1212            if lo >= hi {
1213                continue;
1214            }
1215            if cursor < lo {
1216                self.push_str(&text[cursor..lo]);
1217            }
1218            self.push_marked(&text[lo..hi], mark);
1219            cursor = hi;
1220        }
1221        if cursor < end {
1222            self.push_str(&text[cursor..end]);
1223        }
1224    }
1225
1226    fn push_images(&mut self, images: &[String]) {
1227        if images.is_empty() {
1228            return;
1229        }
1230        self.has_objects = true;
1231        self.push_str(&images.join(""));
1232    }
1233
1234    fn push_object(&mut self, node: &InlineNode) {
1235        self.has_objects = true;
1236        let mut mark = TextMark::default();
1237        for (_, layer) in &node.marks {
1238            mark.merge(layer.clone());
1239        }
1240        self.push_marked(&node.custom.as_ref().unwrap().to_markdown(), &mark);
1241    }
1242
1243    fn is_empty(&self) -> bool {
1244        self.pieces.is_empty()
1245    }
1246
1247    fn styles(&self) -> SelectionStyles {
1248        if self.is_empty() {
1249            SelectionStyles::None
1250        } else if !self.has_objects && self.pieces.windows(2).all(|pair| pair[0].1 == pair[1].1) {
1251            SelectionStyles::One
1252        } else {
1253            SelectionStyles::Mixed
1254        }
1255    }
1256
1257    fn finish(mut self) -> String {
1258        fn write(pieces: &mut [(String, Vec<TextMark>)]) -> String {
1259            let mut out = String::new();
1260            let mut offset = 0;
1261            while offset < pieces.len() {
1262                let Some((mark, count)) = pieces[offset]
1263                    .1
1264                    .iter()
1265                    .map(|mark| {
1266                        let count = pieces[offset..]
1267                            .iter()
1268                            .take_while(|(_, layers)| layers.contains(mark))
1269                            .count();
1270                        (mark.clone(), count)
1271                    })
1272                    .reduce(|best, candidate| {
1273                        if candidate.1 > best.1 {
1274                            candidate
1275                        } else {
1276                            best
1277                        }
1278                    })
1279                else {
1280                    out.push_str(&pieces[offset].0);
1281                    offset += 1;
1282                    continue;
1283                };
1284                let group = &mut pieces[offset..offset + count];
1285                for (_, layers) in group.iter_mut() {
1286                    layers.retain(|layer| layer != &mark);
1287                }
1288                let content = write(group);
1289                out.push_str(&wrap_with_mark(&content, &mark));
1290                offset += count;
1291            }
1292            out
1293        }
1294        write(&mut self.pieces)
1295    }
1296}
1297
1298/// How a selection covers one rendered run, so the caller can tell whether it
1299/// continues into an adjacent inline image.
1300#[derive(Default)]
1301struct RunSelection {
1302    emitted: bool,
1303    at_start: bool,
1304    at_end: bool,
1305}
1306
1307/// Emit the selected part of one rendered run, preceded by the images the
1308/// selection has run into. `run` holds the run's children with their offset
1309/// into the run's concatenated text.
1310fn emit_run(
1311    state: &Arc<Mutex<InlineState>>,
1312    run: &[(usize, &InlineNode)],
1313    pending_images: &mut Vec<String>,
1314    out: &mut MarkdownSource,
1315) -> RunSelection {
1316    let mut selected = RunSelection::default();
1317    let Ok(state) = state.lock() else {
1318        return selected;
1319    };
1320    let Some(selection) = &state.selection else {
1321        return selected;
1322    };
1323    if selection.start >= selection.end {
1324        return selected;
1325    }
1326
1327    selected.at_start = selection.start == 0;
1328    selected.at_end = selection.end >= state.text.len();
1329
1330    for (start, child) in run {
1331        let end = start + child.text.len();
1332        let lo = selection.start.max(*start);
1333        let hi = selection.end.min(end);
1334        if lo >= hi {
1335            continue;
1336        }
1337
1338        if !selected.emitted {
1339            if selected.at_start {
1340                out.push_images(pending_images);
1341            }
1342            pending_images.clear();
1343        }
1344        selected.emitted = true;
1345
1346        out.push_text(&child.text, &child.marks, (lo - start)..(hi - start));
1347    }
1348
1349    selected
1350}
1351
1352/// The Markdown source for an inline image, e.g. `![alt](url "title")`.
1353fn image_markdown(image: &ImageNode) -> String {
1354    let alt = image.alt.clone().unwrap_or_default();
1355    let title = image
1356        .title
1357        .clone()
1358        .map_or(String::new(), |title| format!(" \"{}\"", title));
1359    format!("![{}]({}{})", alt, image.url, title)
1360}
1361
1362/// Reconstruct the Markdown source for the `selection` sub-range of a text run
1363/// carrying `marks`.
1364///
1365/// `selection` is a byte range into `text`. For each mark that overlaps the
1366/// selection, the overlapping slice is wrapped in the mark's Markdown syntax
1367/// (see [`wrap_with_mark`]); slices not covered by any mark are emitted
1368/// verbatim. This lets a rendered-offset selection be copied back as Markdown
1369/// source (e.g. selecting inside a `**bold**` run yields `**bold**`).
1370#[cfg(test)]
1371pub(crate) fn reconstruct_markdown(
1372    text: &str,
1373    marks: &[(Range<usize>, TextMark)],
1374    selection: Range<usize>,
1375) -> String {
1376    let mut source = MarkdownSource::default();
1377    source.push_text(text, marks, selection);
1378    source.finish()
1379}
1380
1381/// Reconstruct the Markdown source of the selected cells of `table`.
1382///
1383/// Cells emit their own selected source; rows are piped (`| a | b |`) and the
1384/// delimiter/alignment row is inserted after the first row, so a selected
1385/// table round-trips as a Markdown table. A selection in one cell (a drag that
1386/// started in a cell stays in it) is that cell's source alone. Returns an empty
1387/// string when no cell is selected.
1388fn table_selected_source(table: &Table) -> String {
1389    let cell_source = |cell: &TableCell| cell.children.selected_source().replace('\n', " ");
1390
1391    let mut selected = table
1392        .children
1393        .iter()
1394        .flat_map(|row| row.children.iter())
1395        .map(cell_source)
1396        .filter(|source| !source.trim().is_empty());
1397    match (selected.next(), selected.next()) {
1398        (None, _) => return String::new(),
1399        (Some(only), None) => return only.trim().to_string(),
1400        _ => {}
1401    }
1402
1403    let mut lines: Vec<String> = Vec::new();
1404    for (row_ix, row) in table.children.iter().enumerate() {
1405        let cells: Vec<String> = row
1406            .children
1407            .iter()
1408            .map(|cell| cell_source(cell).trim().to_string())
1409            .collect();
1410        lines.push(format!("| {} |", cells.join(" | ")));
1411
1412        // The Markdown delimiter row carries the column alignments and must
1413        // follow the header row.
1414        if row_ix == 0 {
1415            let aligns: Vec<String> = (0..row.children.len())
1416                .map(|ix| {
1417                    match table.column_align(ix) {
1418                        ColumnumnAlign::None | ColumnumnAlign::Left => ":--",
1419                        ColumnumnAlign::Center => ":-:",
1420                        ColumnumnAlign::Right => "--:",
1421                    }
1422                    .to_string()
1423                })
1424                .collect();
1425            lines.push(format!("| {} |", aligns.join(" | ")));
1426        }
1427    }
1428
1429    lines.join("\n")
1430}
1431
1432/// `text` as the source of a blockquote, each line prefixed with `> ` so it
1433/// round-trips as Markdown, under a block surface's `[!marker]` line when it has
1434/// one.
1435fn quoted_source(marker: Option<&SharedString>, text: &str) -> String {
1436    marker
1437        .map(|name| format!("[!{name}]"))
1438        .into_iter()
1439        .chain(text.trim_end_matches('\n').lines().map(str::to_string))
1440        .map(|line| {
1441            if line.is_empty() {
1442                ">".to_string()
1443            } else {
1444                format!("> {line}")
1445            }
1446        })
1447        .collect::<Vec<_>>()
1448        .join("\n")
1449}
1450
1451/// Reconstruct the Markdown source of the selected items of a list.
1452///
1453/// Restores the list marker (`- ` / `N. `) and task-list checkbox (`[x] ` /
1454/// `[ ] `) of each item, and recurses into nested lists with a deeper `indent`
1455/// so nesting is preserved. `indent` is the leading whitespace for this level;
1456/// nested levels are indented by the width of the parent marker so continuation
1457/// and sub-list lines align under the item text. Items with no selected content
1458/// are skipped but still consume an ordered number, so the remaining items keep
1459/// their original numbering.
1460fn list_selected_source(
1461    children: &[BlockNode],
1462    ordered: bool,
1463    start: Option<u32>,
1464    indent: &str,
1465) -> String {
1466    let mut out = String::new();
1467    let mut item_ix = 0usize;
1468
1469    for child in children {
1470        let BlockNode::ListItem {
1471            children: item_children,
1472            checked,
1473            ..
1474        } = child
1475        else {
1476            continue;
1477        };
1478
1479        let marker = if ordered {
1480            format!("{}. ", ordered_list_ordinal(start, item_ix))
1481        } else {
1482            "- ".to_string()
1483        };
1484        let checkbox = match checked {
1485            Some(true) => "[x] ",
1486            Some(false) => "[ ] ",
1487            None => "",
1488        };
1489        let child_indent = format!("{}{}", indent, " ".repeat(marker.len()));
1490
1491        // Split the item into its own content and any nested lists, so the
1492        // nested lists can be indented under the content.
1493        let mut content = String::new();
1494        let mut nested = String::new();
1495        for sub in item_children {
1496            if let BlockNode::List {
1497                children: sub_children,
1498                ordered: sub_ordered,
1499                start: sub_start,
1500                ..
1501            } = sub
1502            {
1503                nested.push_str(&list_selected_source(
1504                    sub_children,
1505                    *sub_ordered,
1506                    *sub_start,
1507                    &child_indent,
1508                ));
1509            } else {
1510                content.push_str(&sub.text_by_kind(BlockTextKind::SelectedSource));
1511            }
1512        }
1513        let content = content.trim_end_matches('\n');
1514
1515        if content.is_empty() && nested.is_empty() {
1516            item_ix += 1;
1517            continue;
1518        }
1519
1520        if content.is_empty() {
1521            // An item whose only selected content is a nested list.
1522            out.push_str(indent);
1523            out.push_str(&marker);
1524            out.push_str(checkbox.trim_end());
1525            out.push('\n');
1526        } else {
1527            // The first line carries the marker and checkbox; continuation
1528            // lines are indented to align under the item text.
1529            let mut lines = content.lines();
1530            if let Some(first) = lines.next() {
1531                out.push_str(indent);
1532                out.push_str(&marker);
1533                out.push_str(checkbox);
1534                out.push_str(first);
1535                out.push('\n');
1536            }
1537            for line in lines {
1538                out.push_str(&child_indent);
1539                out.push_str(line);
1540                out.push('\n');
1541            }
1542        }
1543        out.push_str(&nested);
1544        item_ix += 1;
1545    }
1546
1547    out
1548}
1549
1550impl InlineNode {
1551    /// A run of text with no marks.
1552    pub fn new(text: impl Into<SharedString>) -> Self {
1553        Self {
1554            text: text.into(),
1555            image: None,
1556            custom: None,
1557            custom_selection: Arc::default(),
1558            marks: vec![],
1559            source_segments: vec![],
1560            state: Arc::new(Mutex::new(InlineState::default())),
1561        }
1562    }
1563
1564    /// A custom inline node, an atomic object in the flow.
1565    pub fn custom(node: MarkdownNode) -> Self {
1566        let mut this = Self::new(node.as_text().to_string());
1567        this.custom = Some(node);
1568        this
1569    }
1570
1571    /// An inline image, an atomic object in the flow.
1572    pub fn image(image: ImageNode) -> Self {
1573        let mut this = Self::new("");
1574        this.image = Some(image);
1575        this
1576    }
1577
1578    /// Sets the marks, each a byte range of the text and its style.
1579    pub fn marks(mut self, marks: Vec<(Range<usize>, TextMark)>) -> Self {
1580        self.marks = marks;
1581        self
1582    }
1583
1584    /// The text of the run (the fallback text of a custom node, empty for an image).
1585    pub fn text(&self) -> &str {
1586        &self.text
1587    }
1588
1589    /// The image, when this run is an image.
1590    pub fn as_image(&self) -> Option<&ImageNode> {
1591        self.image.as_ref()
1592    }
1593
1594    /// The custom node, when this run is one.
1595    pub fn as_custom(&self) -> Option<&MarkdownNode> {
1596        self.custom.as_ref()
1597    }
1598
1599    /// The marks, each a byte range of the text and its style.
1600    pub fn mark_runs(&self) -> &[(Range<usize>, TextMark)] {
1601        &self.marks
1602    }
1603
1604    pub(crate) fn source_segments(mut self, source_segments: Vec<SourceSegment>) -> Self {
1605        self.source_segments = source_segments;
1606        self
1607    }
1608
1609    fn selected_source_range(&self, selection: Range<usize>) -> Option<Range<usize>> {
1610        source_range_for_segments(&self.source_segments, selection)
1611    }
1612}
1613
1614/// The paragraph element, contains multiple text nodes.
1615///
1616/// Unlike other Element, this is cloneable, because it is used in the Node AST.
1617/// We are keep the selection state inside this AST Nodes.
1618#[derive(Debug, Clone, Default)]
1619pub struct Paragraph {
1620    pub(super) span: Option<Span>,
1621    pub(super) children: Vec<InlineNode>,
1622    /// The link references in this paragraph, used for reference links.
1623    ///
1624    /// The key is the identifier, the value is the url.
1625    pub(super) link_refs: HashMap<SharedString, SharedString>,
1626
1627    pub(crate) state: Arc<Mutex<InlineState>>,
1628    /// What the plain (text-only) render path derives from `children`, kept
1629    /// between frames; see [`ParagraphRender`].
1630    pub(super) render_cache: ParagraphRenderCache,
1631}
1632
1633/// Derived state, invisible to `Debug` and equality.
1634///
1635/// A clone carries what was cached so far: the cached value is a pure
1636/// function of the children and the style it is keyed on, a clone has the
1637/// same children, and every mutation of the children replaces the cache
1638/// (`invalidate_render_cache`). Streaming reparses deep-clone the document on
1639/// every append, and an empty clone made every paragraph rebuild.
1640#[derive(Default)]
1641pub(super) struct ParagraphRenderCache(Mutex<Option<Arc<ParagraphRender>>>);
1642
1643impl Clone for ParagraphRenderCache {
1644    fn clone(&self) -> Self {
1645        let cached = self.0.lock().ok().and_then(|cache| cache.clone());
1646        Self(Mutex::new(cached))
1647    }
1648}
1649
1650impl std::fmt::Debug for ParagraphRenderCache {
1651    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1652        f.write_str("ParagraphRenderCache")
1653    }
1654}
1655
1656/// The text, highlights and links a text-only paragraph renders with.
1657///
1658/// They are a pure function of the paragraph's children and the style they
1659/// are rendered under, yet every frame rebuilt them: the paragraph's text was
1660/// re-concatenated and copied into a fresh `SharedString`, and its marks
1661/// merged into highlights through `combine_highlights` once per child. On a
1662/// scroll that was ~8% of the frame for nothing. Streamed fades change every
1663/// frame and are layered on afterwards; reference links are resolved
1664/// afterwards too, since a definition can arrive later in the document.
1665struct ParagraphRender {
1666    style: Arc<TextViewStyle>,
1667    mono_font: SharedString,
1668    background: Hsla,
1669    text: SharedString,
1670    highlights: Vec<(Range<usize>, InlineHighlight)>,
1671    /// Links as written, before reference resolution.
1672    links: Vec<(Range<usize>, LinkMark)>,
1673    /// What the view's link hook made of each link as written, `None` for a
1674    /// link drawn as plain text. The highlights depend on it, so the cache
1675    /// holds only while the hook still answers the same.
1676    replaced: Vec<Option<LinkMark>>,
1677}
1678
1679impl ParagraphRender {
1680    /// The links drawn as links, resolved and replaced.
1681    fn drawn_links(&self) -> Vec<(Range<usize>, LinkMark)> {
1682        self.links
1683            .iter()
1684            .zip(&self.replaced)
1685            .filter_map(|((range, _), link)| Some((range.clone(), link.clone()?)))
1686            .collect()
1687    }
1688}
1689
1690impl PartialEq for Paragraph {
1691    fn eq(&self, other: &Self) -> bool {
1692        self.span == other.span
1693            && self.children == other.children
1694            && self.link_refs == other.link_refs
1695    }
1696}
1697
1698impl Paragraph {
1699    pub(crate) fn new(text: String) -> Self {
1700        Self {
1701            span: None,
1702            children: vec![InlineNode::new(&text)],
1703            link_refs: HashMap::new(),
1704            state: Arc::new(Mutex::new(InlineState::default())),
1705            render_cache: ParagraphRenderCache::default(),
1706        }
1707    }
1708
1709    /// The text, highlights and (unresolved) links of a text-only paragraph,
1710    /// from the cache when the style has not changed since they were built.
1711    fn plain_render(
1712        &self,
1713        node_cx: &NodeContext,
1714        cx: &App,
1715    ) -> (
1716        SharedString,
1717        Vec<(Range<usize>, InlineHighlight)>,
1718        Vec<(Range<usize>, LinkMark)>,
1719    ) {
1720        let mono_font = cx.theme().tokens.typography.mono;
1721        let background = cx.theme().tokens.colors.background;
1722        if let Ok(cache) = self.render_cache.0.lock()
1723            && let Some(cached) = cache.as_ref()
1724            && (Arc::ptr_eq(&cached.style, &node_cx.style) || *cached.style == *node_cx.style)
1725            && cached.mono_font == mono_font
1726            && cached.background == background
1727            && cached
1728                .links
1729                .iter()
1730                .zip(&cached.replaced)
1731                .all(|((_, link), replaced)| node_cx.link(link, cx) == *replaced)
1732        {
1733            return (
1734                cached.text.clone(),
1735                foreground_highlights(
1736                    cached.highlights.clone(),
1737                    &cached.text,
1738                    0,
1739                    node_cx.foregrounds(self.leaf_key()),
1740                ),
1741                cached.drawn_links(),
1742            );
1743        }
1744
1745        let mut text = String::new();
1746        let mut highlights: Vec<(Range<usize>, InlineHighlight)> = vec![];
1747        let mut links: Vec<(Range<usize>, LinkMark)> = vec![];
1748        let mut replaced = vec![];
1749        let mut offset = 0;
1750        for inline_node in &self.children {
1751            let text_len = inline_node.text.len();
1752            text.push_str(&inline_node.text);
1753            let mut node_highlights = vec![];
1754            for (range, style) in &inline_node.marks {
1755                let inner_range = (offset + range.start)..(offset + range.end);
1756                let mut highlight = mark_highlight(style, node_cx, cx);
1757                if let Some(link_mark) = style.link.clone() {
1758                    let link = node_cx.link(&link_mark, cx);
1759                    if link.is_some() {
1760                        highlight.style.color = Some(node_cx.style.link());
1761                        highlight.style.underline = Some(link_underline(&node_cx.style));
1762                    }
1763                    links.push((inner_range.clone(), link_mark));
1764                    replaced.push(link);
1765                }
1766                node_highlights.push((inner_range, highlight));
1767            }
1768            append_node_highlights(&mut highlights, node_highlights);
1769            offset += text_len;
1770        }
1771        let text = SharedString::from(text);
1772        let render = Arc::new(ParagraphRender {
1773            style: node_cx.style.clone(),
1774            mono_font,
1775            background,
1776            text: text.clone(),
1777            highlights: highlights.clone(),
1778            links,
1779            replaced,
1780        });
1781        let links = render.drawn_links();
1782        if let Ok(mut cache) = self.render_cache.0.lock() {
1783            *cache = Some(render);
1784        }
1785        let highlights =
1786            foreground_highlights(highlights, &text, 0, node_cx.foregrounds(self.leaf_key()));
1787        (text, highlights, links)
1788    }
1789
1790    pub(super) fn selected_text(&self) -> String {
1791        let mut text = String::new();
1792
1793        for c in self.children.iter() {
1794            let Ok(state) = c.state.lock() else {
1795                continue;
1796            };
1797            if let Some(selection) = &state.selection {
1798                text.push_str(&state.text[selection.start..selection.end]);
1799            }
1800            if let Some(custom) = &c.custom
1801                && c.custom_selection.lock().is_ok_and(|selected| *selected)
1802            {
1803                text.push_str(custom.as_text());
1804            }
1805        }
1806
1807        if let Ok(state) = self.state.lock()
1808            && let Some(selection) = &state.selection
1809        {
1810            text.push_str(&state.text[selection.start..selection.end]);
1811        }
1812
1813        text
1814    }
1815
1816    /// Map the current rendered selection to its exact Markdown source range.
1817    pub(super) fn selected_source_range(&self) -> SourceRangeSelection {
1818        let mut selected = SourceRangeSelection::Unselected;
1819        let mut run: Vec<(usize, &InlineNode)> = Vec::new();
1820        let mut offset = 0;
1821        let mut pending_images: Vec<Option<Span>> = Vec::new();
1822        let mut enters_image = true;
1823
1824        let include_run = |state: &Arc<Mutex<InlineState>>,
1825                           run: &[(usize, &InlineNode)]|
1826         -> (SourceRangeSelection, RunSelection) {
1827            let Ok(state) = state.lock() else {
1828                return (SourceRangeSelection::Unmapped, RunSelection::default());
1829            };
1830            let Some(selection) = state.selection else {
1831                return (SourceRangeSelection::Unselected, RunSelection::default());
1832            };
1833            if selection.start >= selection.end {
1834                return (SourceRangeSelection::Unselected, RunSelection::default());
1835            }
1836
1837            let mut run_selection = RunSelection {
1838                at_start: selection.start == 0,
1839                at_end: selection.end >= state.text.len(),
1840                ..Default::default()
1841            };
1842            let mut mapped = SourceRangeSelection::Unselected;
1843            let mut rendered_end = selection.start;
1844            for (start, child) in run {
1845                let end = start + child.text.len();
1846                let lo = selection.start.max(*start);
1847                let hi = selection.end.min(end);
1848                if lo >= hi {
1849                    continue;
1850                }
1851                run_selection.emitted = true;
1852                if lo > rendered_end {
1853                    return (SourceRangeSelection::Unmapped, run_selection);
1854                }
1855                let Some(range) = child.selected_source_range((lo - start)..(hi - start)) else {
1856                    return (SourceRangeSelection::Unmapped, run_selection);
1857                };
1858                mapped.merge(SourceRangeSelection::Mapped(range));
1859                rendered_end = rendered_end.max(hi);
1860            }
1861            if rendered_end < selection.end {
1862                (SourceRangeSelection::Unmapped, run_selection)
1863            } else {
1864                (mapped, run_selection)
1865            }
1866        };
1867
1868        let merge_images = |selected: &mut SourceRangeSelection, images: &mut Vec<Option<Span>>| {
1869            for span in images.drain(..) {
1870                selected.merge(
1871                    span.map(|span| SourceRangeSelection::Mapped(span.start..span.end))
1872                        .unwrap_or(SourceRangeSelection::Unmapped),
1873                );
1874            }
1875        };
1876
1877        for child in &self.children {
1878            if child.custom.is_some() {
1879                let (run_range, run_selection) = include_run(&child.state, &run);
1880                if run_selection.emitted && run_selection.at_start {
1881                    merge_images(&mut selected, &mut pending_images);
1882                }
1883                selected.merge(run_range);
1884
1885                match child.custom_selection.lock() {
1886                    Ok(value) if *value => {
1887                        if run.is_empty() || (run_selection.emitted && run_selection.at_end) {
1888                            merge_images(&mut selected, &mut pending_images);
1889                        }
1890                        selected.merge(
1891                            child
1892                                .custom
1893                                .as_ref()
1894                                .and_then(MarkdownNode::source_range)
1895                                .map(SourceRangeSelection::Mapped)
1896                                .unwrap_or(SourceRangeSelection::Unmapped),
1897                        );
1898                        enters_image = true;
1899                    }
1900                    Ok(_) => enters_image = false,
1901                    Err(_) => {
1902                        selected.merge(SourceRangeSelection::Unmapped);
1903                        enters_image = false;
1904                    }
1905                }
1906                pending_images.clear();
1907                run.clear();
1908                offset = 0;
1909                continue;
1910            }
1911            if let Some(image) = &child.image {
1912                let run_before = !run.is_empty();
1913                let (run_range, run_selection) = include_run(&child.state, &run);
1914                if run_selection.emitted && run_selection.at_start {
1915                    merge_images(&mut selected, &mut pending_images);
1916                }
1917                selected.merge(run_range);
1918                if run_before {
1919                    enters_image = run_selection.emitted && run_selection.at_end;
1920                }
1921                if enters_image {
1922                    pending_images.push(image.span);
1923                } else {
1924                    pending_images.clear();
1925                }
1926                run.clear();
1927                offset = 0;
1928                continue;
1929            }
1930            run.push((offset, child));
1931            offset += child.text.len();
1932        }
1933
1934        let (trailing_range, trailing) = include_run(&self.state, &run);
1935        if trailing.emitted && trailing.at_start {
1936            merge_images(&mut selected, &mut pending_images);
1937        }
1938        selected.merge(trailing_range);
1939        if !trailing.emitted
1940            && enters_image
1941            && !matches!(selected, SourceRangeSelection::Unselected)
1942        {
1943            merge_images(&mut selected, &mut pending_images);
1944        }
1945        selected
1946    }
1947
1948    /// Reconstruct the Markdown source for the current selection.
1949    ///
1950    /// Mirrors [`selected_text`](Self::selected_text), but emits Markdown
1951    /// instead of the rendered text, using each inline node's `marks` (see
1952    /// [`reconstruct_markdown`]).
1953    ///
1954    /// Selection offsets index an `InlineState.text`, and one such state spans
1955    /// *several* children: [`Paragraph::render`] concatenates children until it
1956    /// hits an inline image, stores that run in the image child's state, then
1957    /// starts over; whatever follows the last image is stored in `self.state`.
1958    /// So walk the children in the same runs and map each selected byte back to
1959    /// the child it was rendered from — mapping against a single child's text
1960    /// would attribute the same offsets to children in other runs.
1961    ///
1962    /// An image has no selection of its own, so it is emitted when the
1963    /// selection runs into it: reaching the end of the run before it, and
1964    /// starting at the beginning of the run after it. A paragraph that begins
1965    /// or ends with an image has no run on that side, which counts as reaching
1966    /// it.
1967    pub(super) fn selected_source(&self) -> String {
1968        self.selected_markdown().finish()
1969    }
1970
1971    /// How many styles the selection within this paragraph takes in.
1972    pub(super) fn selection_styles(&self) -> SelectionStyles {
1973        self.selected_markdown().styles()
1974    }
1975
1976    /// The selection as Markdown pieces, before their marks are serialized;
1977    /// see [`selected_source`](Self::selected_source).
1978    fn selected_markdown(&self) -> MarkdownSource {
1979        let mut source = MarkdownSource::default();
1980        let mut pending_images: Vec<String> = Vec::new();
1981        let mut run: Vec<(usize, &InlineNode)> = Vec::new();
1982        let mut offset = 0;
1983        let mut enters_image = true;
1984
1985        for child in self.children.iter() {
1986            if child.custom.is_some() {
1987                let selected = emit_run(&child.state, &run, &mut pending_images, &mut source);
1988                let object_selected = child
1989                    .custom_selection
1990                    .lock()
1991                    .is_ok_and(|selected| *selected);
1992                if object_selected {
1993                    if run.is_empty() || (selected.emitted && selected.at_end) {
1994                        source.push_images(&pending_images);
1995                    }
1996                    source.push_object(child);
1997                }
1998                pending_images.clear();
1999                enters_image = object_selected;
2000                run.clear();
2001                offset = 0;
2002                continue;
2003            }
2004            let Some(image) = &child.image else {
2005                run.push((offset, child));
2006                offset += child.text.len();
2007                continue;
2008            };
2009
2010            // The run before an image is stored in that image's own state.
2011            let run_before = !run.is_empty();
2012            let selected = emit_run(&child.state, &run, &mut pending_images, &mut source);
2013            if run_before {
2014                enters_image = selected.emitted && selected.at_end;
2015            }
2016            if enters_image {
2017                pending_images.push(image_markdown(image));
2018            } else {
2019                pending_images.clear();
2020            }
2021
2022            run.clear();
2023            offset = 0;
2024        }
2025
2026        let trailing = emit_run(&self.state, &run, &mut pending_images, &mut source);
2027        // Trailing images have no run after them to flush them.
2028        if !trailing.emitted && enters_image && !source.is_empty() {
2029            source.push_images(&pending_images);
2030        }
2031
2032        source
2033    }
2034
2035    pub(super) fn text(&self) -> String {
2036        let mut text = String::new();
2037        for node in self.children.iter() {
2038            text.push_str(&node.text);
2039        }
2040        text
2041    }
2042
2043    /// Synchronously clear the selection stored in every inline state.
2044    ///
2045    /// Mirrors the [`selected_text`](Self::selected_text) traversal.
2046    pub(super) fn has_selection(&self) -> bool {
2047        self.children.iter().any(|c| {
2048            c.state.lock().is_ok_and(|state| state.selection.is_some())
2049                || c.custom_selection.lock().is_ok_and(|selected| *selected)
2050        }) || self
2051            .state
2052            .lock()
2053            .is_ok_and(|state| state.selection.is_some())
2054    }
2055
2056    pub(super) fn clear_selection(&self) {
2057        for c in self.children.iter() {
2058            if let Ok(mut selected) = c.custom_selection.lock() {
2059                *selected = false;
2060            }
2061            if let Ok(mut state) = c.state.lock() {
2062                state.selection = None;
2063            }
2064        }
2065
2066        if let Ok(mut state) = self.state.lock() {
2067            state.selection = None;
2068        }
2069    }
2070}
2071
2072/// A table: rows of cell paragraphs and per-column alignment.
2073#[derive(Debug, Clone, Default, PartialEq)]
2074pub struct Table {
2075    pub(crate) children: Vec<TableRow>,
2076    pub(crate) column_aligns: Vec<ColumnumnAlign>,
2077    pub(crate) span: Option<Span>,
2078    /// The [`TableData`] handed to the `table_actions` hook, kept between
2079    /// frames; see [`Table::cached_table_data`].
2080    pub(crate) table_data_cache: TableDataCache,
2081    pub(crate) column_widths_cache: TableColumnWidthsCache,
2082}
2083
2084/// Derived state, invisible to `Debug` and equality.
2085///
2086/// A clone carries what was cached so far: a parsed table does not change
2087/// after parsing (cell mutations only touch selection state, which
2088/// [`TableData`] does not read), so a clone has the same data. Streaming
2089/// reparses deep-clone the document on every append, and an empty clone made
2090/// every table rebuild.
2091#[derive(Default)]
2092pub(crate) struct TableDataCache(Mutex<Option<Arc<TableData>>>);
2093
2094impl Clone for TableDataCache {
2095    fn clone(&self) -> Self {
2096        let cached = self.0.lock().ok().and_then(|cache| cache.clone());
2097        Self(Mutex::new(cached))
2098    }
2099}
2100
2101impl PartialEq for TableDataCache {
2102    fn eq(&self, _: &Self) -> bool {
2103        true
2104    }
2105}
2106
2107impl std::fmt::Debug for TableDataCache {
2108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2109        f.write_str("TableDataCache")
2110    }
2111}
2112
2113/// Like `TableDataCache`, derived widths survive clones of an unchanged
2114/// parsed table. A newly parsed table starts with an empty cache.
2115#[derive(Default)]
2116pub(crate) struct TableColumnWidthsCache(Mutex<Option<Arc<TableColumnWidths>>>);
2117
2118impl Clone for TableColumnWidthsCache {
2119    fn clone(&self) -> Self {
2120        let cached = self.0.lock().ok().and_then(|cache| cache.clone());
2121        Self(Mutex::new(cached))
2122    }
2123}
2124
2125impl PartialEq for TableColumnWidthsCache {
2126    fn eq(&self, _: &Self) -> bool {
2127        true
2128    }
2129}
2130
2131impl std::fmt::Debug for TableColumnWidthsCache {
2132    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2133        f.write_str("TableColumnWidthsCache")
2134    }
2135}
2136
2137fn text_system_id(window: &Window) -> usize {
2138    std::rc::Rc::as_ptr(window.text_system()) as usize
2139}
2140
2141struct TableColumnWidths {
2142    /// Identity of the window text system the widths were measured with.
2143    /// `WindowTextSystem` is `Rc`-shared and the cache must stay `Send`, so
2144    /// only its address is kept.
2145    text_system: usize,
2146    /// The styles the header row and the body rows render with.
2147    text_styles: TableTextStyles,
2148    rem_size: Pixels,
2149    mono_family: SharedString,
2150    inline_code: HighlightStyle,
2151    /// Maxima from ordinary text only. Custom cells may shrink after an update.
2152    widths: Vec<f32>,
2153    custom_cells: Vec<(usize, usize)>,
2154}
2155
2156/// The text styles table rows render with: the window's, refined by
2157/// `style.table` on the frame, `style.table_head` on the header row and
2158/// `style.table_cell` on every cell, in the order the elements apply them.
2159#[derive(Clone, PartialEq)]
2160struct TableTextStyles {
2161    head: gpui::TextStyle,
2162    body: gpui::TextStyle,
2163    head_refinement: TextStyleRefinement,
2164    body_refinement: TextStyleRefinement,
2165}
2166
2167impl TableTextStyles {
2168    fn new(style: &TextViewStyle, window: &Window) -> Self {
2169        let mut body_refinement = style.table().text.clone();
2170        let mut head_refinement = body_refinement.clone();
2171        head_refinement.refine(&style.table_head().text);
2172        head_refinement.refine(&style.table_cell().text);
2173        body_refinement.refine(&style.table_cell().text);
2174        let mut head = window.text_style();
2175        let mut body = head.clone();
2176        head.refine(&head_refinement);
2177        body.refine(&body_refinement);
2178        Self {
2179            head,
2180            body,
2181            head_refinement,
2182            body_refinement,
2183        }
2184    }
2185
2186    fn row(&self, row_ix: usize) -> &gpui::TextStyle {
2187        if row_ix == 0 { &self.head } else { &self.body }
2188    }
2189
2190    fn row_refinement(&self, row_ix: usize) -> &TextStyleRefinement {
2191        if row_ix == 0 {
2192            &self.head_refinement
2193        } else {
2194            &self.body_refinement
2195        }
2196    }
2197}
2198
2199/// Plain snapshot of a rendered Markdown table, passed to the
2200/// [`crate::text::TextView::table_actions`] hook.
2201#[derive(Debug, Clone, Default, PartialEq)]
2202pub struct TableData {
2203    /// First table row (header cells) as plain text.
2204    pub headers: Vec<String>,
2205    /// Rows after the header as plain text cells. May be ragged while
2206    /// a table is still streaming in.
2207    pub rows: Vec<Vec<String>>,
2208    /// The table serialized back to GFM pipe-table Markdown, alignments kept.
2209    pub markdown: String,
2210    /// Byte range of the table in the Markdown source, for callers that need
2211    /// to map the table back to the document.
2212    ///
2213    /// Not needed to keep element ids apart: the actions row is wrapped in its
2214    /// own identified element, so plain ids like `"copy"` are already scoped
2215    /// per table.
2216    pub span: Option<Range<usize>>,
2217}
2218
2219impl Table {
2220    /// A table of `rows` (one paragraph per cell) with the column alignments.
2221    pub fn new(rows: Vec<Vec<Paragraph>>, column_aligns: Vec<ColumnumnAlign>) -> Self {
2222        Self {
2223            children: rows
2224                .into_iter()
2225                .map(|row| TableRow {
2226                    children: row
2227                        .into_iter()
2228                        .map(|children| TableCell {
2229                            children,
2230                            width: None,
2231                        })
2232                        .collect(),
2233                })
2234                .collect(),
2235            column_aligns,
2236            ..Default::default()
2237        }
2238    }
2239
2240    /// The rows, each an iterator over its cells' paragraphs.
2241    pub fn rows(&self) -> impl Iterator<Item = impl Iterator<Item = &Paragraph>> {
2242        self.children
2243            .iter()
2244            .map(|row| row.children.iter().map(|cell| &cell.children))
2245    }
2246
2247    /// The alignment of each column.
2248    pub fn column_aligns(&self) -> &[ColumnumnAlign] {
2249        &self.column_aligns
2250    }
2251
2252    pub(crate) fn column_align(&self, index: usize) -> ColumnumnAlign {
2253        self.column_aligns.get(index).copied().unwrap_or_default()
2254    }
2255
2256    /// Serialize the table back to GFM pipe-table Markdown (`| a | b |`),
2257    /// preserving column alignments. Cell newlines collapse to spaces and
2258    /// `|` is escaped so rows stay intact.
2259    ///
2260    /// Mirrors [`table_selected_source`], which does the same for the selected
2261    /// cells only.
2262    pub(crate) fn to_markdown(&self) -> String {
2263        let mut lines: Vec<String> = Vec::with_capacity(self.children.len() + 1);
2264
2265        for (row_ix, row) in self.children.iter().enumerate() {
2266            let cells: Vec<String> = row
2267                .children
2268                .iter()
2269                .map(|cell| {
2270                    cell.children
2271                        .to_markdown()
2272                        .trim()
2273                        .replace('\n', " ")
2274                        .replace('|', "\\|")
2275                })
2276                .collect();
2277            lines.push(format!("| {} |", cells.join(" | ")));
2278
2279            // The Markdown delimiter row carries the column alignments and must
2280            // follow the header row.
2281            if row_ix == 0 {
2282                let aligns: Vec<String> = (0..row.children.len())
2283                    .map(|ix| {
2284                        match self.column_align(ix) {
2285                            ColumnumnAlign::None | ColumnumnAlign::Left => ":--",
2286                            ColumnumnAlign::Center => ":-:",
2287                            ColumnumnAlign::Right => "--:",
2288                        }
2289                        .to_string()
2290                    })
2291                    .collect();
2292                lines.push(format!("| {} |", aligns.join(" | ")));
2293            }
2294        }
2295
2296        lines.join("\n")
2297    }
2298
2299    /// Snapshot of this table for the [`crate::text::TextView::table_actions`]
2300    /// hook.
2301    pub(crate) fn table_data(&self) -> TableData {
2302        let row_text = |row: &TableRow| {
2303            row.children
2304                .iter()
2305                .map(|cell| cell.children.text().trim().to_string())
2306                .collect::<Vec<_>>()
2307        };
2308
2309        TableData {
2310            headers: self.children.first().map(row_text).unwrap_or_default(),
2311            rows: self.children.iter().skip(1).map(row_text).collect(),
2312            markdown: self.to_markdown(),
2313            span: self.span.map(|span| span.start..span.end),
2314        }
2315    }
2316
2317    /// [`Self::table_data`], built on the first render and reused by later
2318    /// ones: serializing every cell and the whole table back to Markdown on
2319    /// every scroll or stream frame is wasted work, and a parsed table does
2320    /// not change after parsing (a reparse builds a new one).
2321    fn cached_table_data(&self) -> Arc<TableData> {
2322        if let Ok(cache) = self.table_data_cache.0.lock()
2323            && let Some(cached) = cache.as_ref()
2324        {
2325            return cached.clone();
2326        }
2327
2328        let data = Arc::new(self.table_data());
2329        if let Ok(mut cache) = self.table_data_cache.0.lock() {
2330            *cache = Some(data.clone());
2331        }
2332        data
2333    }
2334}
2335
2336/// The alignment of a table column.
2337#[derive(Debug, Default, Copy, Clone, PartialEq)]
2338pub enum ColumnumnAlign {
2339    /// No alignment in the delimiter row (`---`); renders like `Left`.
2340    #[default]
2341    None,
2342    Left,
2343    Center,
2344    Right,
2345}
2346
2347impl From<mdast::AlignKind> for ColumnumnAlign {
2348    fn from(value: mdast::AlignKind) -> Self {
2349        match value {
2350            mdast::AlignKind::None => ColumnumnAlign::None,
2351            mdast::AlignKind::Left => ColumnumnAlign::Left,
2352            mdast::AlignKind::Center => ColumnumnAlign::Center,
2353            mdast::AlignKind::Right => ColumnumnAlign::Right,
2354        }
2355    }
2356}
2357
2358#[derive(Debug, Clone, Default, PartialEq)]
2359pub(crate) struct TableRow {
2360    pub children: Vec<TableCell>,
2361}
2362
2363#[derive(Debug, Clone, Default, PartialEq)]
2364pub(crate) struct TableCell {
2365    pub children: Paragraph,
2366    pub width: Option<DefiniteLength>,
2367}
2368
2369impl Paragraph {
2370    pub(crate) fn take(&mut self) -> Paragraph {
2371        std::mem::replace(
2372            self,
2373            Paragraph {
2374                span: None,
2375                children: vec![],
2376                link_refs: Default::default(),
2377                state: Arc::new(Mutex::new(InlineState::default())),
2378                render_cache: ParagraphRenderCache::default(),
2379            },
2380        )
2381    }
2382
2383    pub(crate) fn is_image(&self) -> bool {
2384        false
2385    }
2386
2387    pub(crate) fn set_span(&mut self, span: Span) {
2388        self.span = Some(span);
2389    }
2390
2391    pub(crate) fn push_str(&mut self, text: &str) {
2392        self.children.push(
2393            InlineNode::new(text.to_string()).marks(vec![(0..text.len(), TextMark::default())]),
2394        );
2395        self.invalidate_render_cache();
2396    }
2397
2398    /// Appends an inline run.
2399    pub fn push(&mut self, text: InlineNode) {
2400        self.children.push(text);
2401        self.invalidate_render_cache();
2402    }
2403
2404    /// The inline runs.
2405    pub fn children(&self) -> &[InlineNode] {
2406        &self.children
2407    }
2408
2409    /// Marks this paragraph as a leaf of an external editor: while a
2410    /// [`collect_leaf_geometry`](super::editor_host::collect_leaf_geometry)
2411    /// scope is active, it reports its geometry under `key` and paints the
2412    /// decorations given for `key`. Rekeying detaches runtime state from clones.
2413    pub fn with_leaf_key(mut self, key: u64) -> Self {
2414        set_leaf_key(&mut self.state, key);
2415        self
2416    }
2417
2418    pub(crate) fn push_image(&mut self, image: ImageNode) {
2419        self.children.push(InlineNode::image(image));
2420        self.invalidate_render_cache();
2421    }
2422
2423    /// The children changed, so what was derived from them is stale.
2424    fn invalidate_render_cache(&mut self) {
2425        self.render_cache = ParagraphRenderCache::default();
2426    }
2427
2428    pub(crate) fn is_empty(&self) -> bool {
2429        self.children.is_empty()
2430            || self
2431                .children
2432                .iter()
2433                .all(|node| node.text.is_empty() && node.image.is_none())
2434    }
2435
2436    /// Return length of children text.
2437    pub(crate) fn text_len(&self) -> usize {
2438        self.children
2439            .iter()
2440            .map(|node| node.text.len())
2441            .sum::<usize>()
2442    }
2443
2444    pub(crate) fn merge(&mut self, other: Self) {
2445        self.children.extend(other.children);
2446        self.invalidate_render_cache();
2447    }
2448}
2449
2450#[derive(Debug, Clone)]
2451pub struct CodeBlock {
2452    lang: Option<SharedString>,
2453    meta: Option<SharedString>,
2454    state: Arc<Mutex<InlineState>>,
2455    highlight_cache: Arc<Mutex<Option<CachedCodeBlockHighlights>>>,
2456    /// Rendered UTF-8 byte spans of the code paired with their exact Markdown
2457    /// source spans.
2458    pub(crate) source_segments: Vec<SourceSegment>,
2459    pub span: Option<Span>,
2460}
2461
2462struct CachedCodeBlockHighlights {
2463    highlighter: Arc<CodeBlockHighlighterFn>,
2464    styles: Vec<(Range<usize>, HighlightStyle)>,
2465}
2466
2467impl std::fmt::Debug for CachedCodeBlockHighlights {
2468    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2469        f.debug_struct("CachedCodeBlockHighlights")
2470            .field("styles", &self.styles)
2471            .finish_non_exhaustive()
2472    }
2473}
2474
2475impl PartialEq for CodeBlock {
2476    fn eq(&self, other: &Self) -> bool {
2477        self.lang == other.lang
2478            && self.meta == other.meta
2479            && self.code() == other.code()
2480            && self.span == other.span
2481    }
2482}
2483
2484impl CodeBlock {
2485    /// Get the language of the code block.
2486    pub fn lang(&self) -> Option<SharedString> {
2487        self.lang.clone()
2488    }
2489
2490    /// The rest of the fence's info string after the language, when any.
2491    pub fn meta(&self) -> Option<SharedString> {
2492        self.meta.clone()
2493    }
2494
2495    /// Sets the fence's info string after the language. It is kept for
2496    /// round trips and is not rendered.
2497    pub fn with_meta(mut self, meta: Option<SharedString>) -> Self {
2498        self.meta = meta;
2499        self
2500    }
2501
2502    /// Marks this code block as a leaf of an external editor, like
2503    /// [`Paragraph::with_leaf_key`]. Rekeying detaches runtime state from clones.
2504    pub fn with_leaf_key(mut self, key: u64) -> Self {
2505        set_leaf_key(&mut self.state, key);
2506        self
2507    }
2508
2509    /// Get the code content of the code block.
2510    pub fn code(&self) -> SharedString {
2511        self.state
2512            .lock()
2513            .map(|state| state.text.clone())
2514            .unwrap_or_default()
2515    }
2516
2517    /// Builds a code block that is not tied to a parsed document.
2518    ///
2519    /// [`crate::TextView::code_block_highlighter`] hands a `&CodeBlock` to the
2520    /// highlighter it is given, so anyone writing one needs a way to build a
2521    /// block to exercise it against.
2522    pub fn from_code(code: impl Into<SharedString>, lang: Option<impl Into<SharedString>>) -> Self {
2523        Self::new(code.into(), lang.map(Into::into), None::<Span>)
2524    }
2525
2526    /// A code block of `code` in `lang`.
2527    pub fn new(
2528        code: SharedString,
2529        lang: Option<SharedString>,
2530        span: Option<impl Into<Span>>,
2531    ) -> Self {
2532        let state = Arc::new(Mutex::new(InlineState::default()));
2533        if let Ok(mut state) = state.lock() {
2534            state.set_text(code);
2535        }
2536
2537        Self {
2538            lang,
2539            meta: None,
2540            state,
2541            highlight_cache: Arc::new(Mutex::new(None)),
2542            source_segments: vec![],
2543            span: span.map(|s| s.into()),
2544        }
2545    }
2546
2547    pub(crate) fn source_segments(mut self, source_segments: Vec<SourceSegment>) -> Self {
2548        self.source_segments = source_segments;
2549        self
2550    }
2551
2552    #[cfg(test)]
2553    pub(crate) fn set_selection(&self, selection: Range<usize>) {
2554        if let Ok(mut state) = self.state.lock() {
2555            state.selection = Some(selection.into());
2556        }
2557    }
2558
2559    pub(super) fn selected_source_range(&self) -> SourceRangeSelection {
2560        let Ok(state) = self.state.lock() else {
2561            return SourceRangeSelection::Unmapped;
2562        };
2563        let Some(selection) = state.selection else {
2564            return SourceRangeSelection::Unselected;
2565        };
2566        if selection.start >= selection.end {
2567            return SourceRangeSelection::Unselected;
2568        }
2569        source_range_for_segments(&self.source_segments, selection.start..selection.end)
2570            .map(SourceRangeSelection::Mapped)
2571            .unwrap_or(SourceRangeSelection::Unmapped)
2572    }
2573
2574    fn highlighted_styles(
2575        &self,
2576        highlighter: &Arc<CodeBlockHighlighterFn>,
2577    ) -> Vec<(Range<usize>, HighlightStyle)> {
2578        if let Ok(cache) = self.highlight_cache.lock()
2579            && let Some(cache) = cache.as_ref()
2580            && Arc::ptr_eq(&cache.highlighter, highlighter)
2581        {
2582            return cache.styles.clone();
2583        }
2584
2585        let code_len = self.code().len();
2586        let styles = highlighter(self)
2587            .into_iter()
2588            .filter(|(range, _)| range.start <= range.end && range.end <= code_len)
2589            .collect::<Vec<_>>();
2590        if let Ok(mut cache) = self.highlight_cache.lock() {
2591            *cache = Some(CachedCodeBlockHighlights {
2592                highlighter: highlighter.clone(),
2593                styles: styles.clone(),
2594            });
2595        }
2596        styles
2597    }
2598
2599    pub(super) fn selected_text(&self) -> String {
2600        let mut text = String::new();
2601        if let Ok(state) = self.state.lock()
2602            && let Some(selection) = &state.selection
2603        {
2604            text.push_str(&state.text[selection.start..selection.end]);
2605        }
2606        text
2607    }
2608
2609    /// Markdown source for the current selection.
2610    ///
2611    /// The selected code is wrapped in a fenced code block carrying the block's
2612    /// language, so a selected code block round-trips as Markdown (e.g.
2613    /// ```` ```rust\n…\n``` ````) instead of pasting as bare, unfenced text.
2614    /// A partial selection is still emitted as a valid fenced block.
2615    pub(super) fn selected_source(&self) -> String {
2616        let code = self.selected_text();
2617        if code.is_empty() {
2618            return String::new();
2619        }
2620        let lang = self.lang.clone().unwrap_or_default();
2621        // Trim trailing newlines so the closing fence sits on its own line
2622        // directly after the last code line (no blank line before it).
2623        let code = code.trim_end_matches('\n');
2624        format!("```{}\n{}\n```", lang, code)
2625    }
2626
2627    pub(super) fn text(&self) -> String {
2628        self.state
2629            .lock()
2630            .map(|state| state.text.to_string())
2631            .unwrap_or_default()
2632    }
2633
2634    /// Synchronously clear the selection stored in the inline state.
2635    ///
2636    /// Mirrors the [`selected_text`](Self::selected_text) traversal.
2637    pub(super) fn has_selection(&self) -> bool {
2638        self.state
2639            .lock()
2640            .is_ok_and(|state| state.selection.is_some())
2641    }
2642
2643    pub(super) fn clear_selection(&self) {
2644        if let Ok(mut state) = self.state.lock() {
2645            state.selection = None;
2646        }
2647    }
2648
2649    fn render(
2650        &self,
2651        options: &NodeRenderOptions,
2652        node_cx: &NodeContext,
2653        window: &mut Window,
2654        cx: &mut App,
2655    ) -> AnyElement {
2656        let style = &node_cx.style;
2657        let leaf_key = self.span.map(|span| TextLeafKey::block(span.start));
2658        // The language sits quietly in the top-right corner, where custom
2659        // actions go instead when the caller provides them; the top padding
2660        // keeps the first line clear of it. Like the actions, it stays out of
2661        // the scrolled content so it holds its corner.
2662        let lang_label = self
2663            .lang()
2664            .filter(|lang| !lang.is_empty() && node_cx.code_block_actions.is_none())
2665            .map(|lang| {
2666                div()
2667                    .absolute()
2668                    .top(px(7.))
2669                    .right_3()
2670                    .font_family(cx.theme().tokens.typography.sans)
2671                    .text_size(cx.theme().tokens.typography.xs.size)
2672                    .line_height(px(16.))
2673                    .text_color(style.muted_foreground())
2674                    .child(lang)
2675            });
2676
2677        let block = div()
2678            .w_full()
2679            .min_w_0()
2680            .px_4()
2681            .pt(if lang_label.is_some() {
2682                px(28.)
2683            } else {
2684                px(14.)
2685            })
2686            .pb(px(14.))
2687            .bg(style.code_background())
2688            .border_1()
2689            .border_color(style.border())
2690            .font_family(cx.theme().tokens.typography.mono)
2691            .text_size(cx.theme().tokens.typography.mono_md.size)
2692            .line_height(relative(1.6))
2693            .relative()
2694            .refine_style(&style.code_block())
2695            .child(
2696                Inline::new(
2697                    self.state.clone(),
2698                    vec![],
2699                    fade_highlights(
2700                        node_cx
2701                            .code_block_highlighter
2702                            .as_ref()
2703                            .map(|highlighter| self.highlighted_styles(highlighter))
2704                            .unwrap_or_default()
2705                            .into_iter()
2706                            .map(|(range, style)| (range, InlineHighlight::from(style)))
2707                            .collect(),
2708                        node_cx.stream_fades(leaf_key),
2709                    ),
2710                    node_cx.link_click_handler.clone(),
2711                )
2712                .range_backgrounds(node_cx.range_backgrounds(leaf_key).to_vec())
2713                .reveal(node_cx.reveal_at(leaf_key, 0, self.code().len())),
2714            );
2715        let actions = node_cx.code_block_actions.clone().map(|actions| {
2716            div()
2717                .id("actions")
2718                .absolute()
2719                .top_2()
2720                .right_2()
2721                .bg(style.code_background())
2722                .rounded(cx.theme().tokens.radius.md)
2723                .child(actions(&self, window, cx))
2724        });
2725        // The id scopes the caller's action ids per code block, so plain ids
2726        // like `"copy"` don't collide across blocks.
2727        let id = block_element_id("codeblock", self.span, options.ix);
2728        let block = if matches!(style.code_block().overflow.y, Some(Overflow::Scroll)) {
2729            let scroll_handle = window
2730                .use_keyed_state(
2731                    block_element_id("codeblock-scroll", self.span, options.ix),
2732                    cx,
2733                    |_, _| ScrollHandle::default(),
2734                )
2735                .read(cx)
2736                .clone();
2737            // Scroll mode is opted in by setting `style.code_block`'s
2738            // `overflow.y` to `Overflow::Scroll`.
2739            // The mask consumes the wheel in the capture phase, so an ancestor
2740            // `gpui::list` doesn't scroll on the same event. Mask, scrollbar
2741            // and actions are siblings of the scrolled block, so they stay
2742            // pinned to the viewport instead of moving with the code.
2743            div()
2744                .id(id.clone())
2745                .w_full()
2746                .min_w_0()
2747                .relative()
2748                .child(block.id("scroll").track_scroll(&scroll_handle))
2749                .child(ScrollableMask::new(Axis::Vertical, &scroll_handle).id(id))
2750                .child(
2751                    div()
2752                        .absolute()
2753                        .inset_0()
2754                        .child(Scrollbar::vertical(&scroll_handle)),
2755                )
2756                .children(actions)
2757                .children(lang_label)
2758                .into_any_element()
2759        } else {
2760            // Without actions nothing under the block needs element state.
2761            match actions {
2762                Some(actions) => block.id(id).child(actions).into_any_element(),
2763                None => block.children(lang_label).into_any_element(),
2764            }
2765        };
2766
2767        gapped(
2768            block,
2769            if options.is_last {
2770                rems(0.)
2771            } else {
2772                style.paragraph_gap()
2773            },
2774        )
2775    }
2776}
2777
2778/// A context for rendering nodes, contains link references.
2779#[derive(Default, Clone)]
2780pub(crate) struct NodeContext {
2781    /// The byte offset of the node in the original markdown text.
2782    /// Used for incremental updates.
2783    pub(crate) offset: usize,
2784    pub(crate) link_refs: HashMap<SharedString, LinkMark>,
2785    pub(crate) style: Arc<TextViewStyle>,
2786    pub(crate) code_block_actions: Option<Arc<CodeBlockActionsFn>>,
2787    pub(crate) code_block_highlighter: Option<Arc<CodeBlockHighlighterFn>>,
2788    pub(crate) table_actions: Option<Arc<TableActionsFn>>,
2789    pub(crate) image_source: Option<Arc<super::text_view::ImageSourceFn>>,
2790    pub(crate) link_click_handler: Option<Arc<LinkClickHandlerFn>>,
2791    /// Replaces each link before it is drawn; links are kept as written when
2792    /// `None`.
2793    pub(crate) link_hook: Option<Arc<LinkFn>>,
2794    pub(crate) task_toggle_handler: Option<Arc<TaskToggleHandlerFn>>,
2795    pub(crate) markdown_extensions: Arc<MarkdownExtensions>,
2796    /// This frame's streamed fade-in, when any text is still fading.
2797    pub(crate) stream_fade: Option<Arc<StreamFadeFrame>>,
2798    /// The application's range highlights, when there are any.
2799    pub(crate) range_highlights: Option<Arc<RangeHighlightFrame>>,
2800    /// Render-local glyph colors supplied by an external editor, keyed by leaf.
2801    pub(crate) foregrounds: Option<Arc<HashMap<u64, Vec<(Range<usize>, Hsla)>>>>,
2802    /// The line being scrolled into view, when there is one.
2803    pub(crate) reveal: Option<RevealRequest>,
2804    /// The font size the text view inherits this frame, or zero when not
2805    /// resolved; read it through `body_font_size`.
2806    pub(crate) body_font_size: Pixels,
2807}
2808
2809impl NodeContext {
2810    /// The link drawn for `link` as written: the definition a reference link
2811    /// names (or `link` itself), as the view's link hook replaces it. `None`
2812    /// draws the link as plain text.
2813    pub(crate) fn link(&self, link: &LinkMark, cx: &App) -> Option<LinkMark> {
2814        let resolved = link
2815            .identifier
2816            .as_ref()
2817            .and_then(|identifier| self.link_refs.get(identifier))
2818            .unwrap_or(link);
2819        let Some(hook) = &self.link_hook else {
2820            return Some(resolved.clone());
2821        };
2822        let replaced = hook(
2823            &Link {
2824                url: resolved.url.clone(),
2825                title: resolved.title.clone(),
2826            },
2827            cx,
2828        )?;
2829        Some(LinkMark {
2830            url: replaced.url,
2831            identifier: None,
2832            title: replaced.title,
2833        })
2834    }
2835
2836    fn foregrounds(&self, key: Option<u64>) -> &[(Range<usize>, Hsla)] {
2837        key.and_then(|key| self.foregrounds.as_ref()?.get(&key))
2838            .map_or(&[], Vec::as_slice)
2839    }
2840
2841    fn image_source(&self, image: &ImageNode) -> ImageSource {
2842        match &self.image_source {
2843            Some(resolve) => resolve(&image.url),
2844            None => image.source(),
2845        }
2846    }
2847
2848    pub(super) fn add_ref(&mut self, identifier: SharedString, link: LinkMark) {
2849        self.link_refs.insert(identifier, link);
2850    }
2851
2852    /// The fade ranges of the text leaf `key`, in its rendered byte space.
2853    fn stream_fades(&self, key: Option<TextLeafKey>) -> &[(Range<usize>, f32)] {
2854        match (&self.stream_fade, key) {
2855            (Some(frame), Some(key)) => frame.fades(key).unwrap_or_default(),
2856            _ => &[],
2857        }
2858    }
2859
2860    /// The range highlight backgrounds of the text leaf `key`, in its
2861    /// rendered byte space.
2862    fn range_backgrounds(&self, key: Option<TextLeafKey>) -> &[(Range<usize>, Hsla)] {
2863        match (&self.range_highlights, key) {
2864            (Some(frame), Some(key)) => frame.backgrounds(key),
2865            _ => &[],
2866        }
2867    }
2868
2869    /// The pending reveal, when it starts in the text leaf `key` between
2870    /// `start` and `end`, rebased to `start`.
2871    fn reveal_at(&self, key: Option<TextLeafKey>, start: usize, end: usize) -> Option<RevealAt> {
2872        self.reveal.as_ref()?.at(key, start, end)
2873    }
2874}
2875
2876impl PartialEq for NodeContext {
2877    fn eq(&self, other: &Self) -> bool {
2878        self.link_refs == other.link_refs && self.style == other.style
2879        // Note: code_block_actions, table_actions and markdown_extensions are
2880        // intentionally not compared (closures can't be compared)
2881    }
2882}
2883
2884/// The text color with more contrast against a highlight composited over the
2885/// theme background (WCAG relative luminance).
2886fn mark_text_color(highlight: Hsla, background: Hsla) -> Hsla {
2887    fn channel(value: f32) -> f32 {
2888        if value <= 0.04045 {
2889            value / 12.92
2890        } else {
2891            ((value + 0.055) / 1.055).powf(2.4)
2892        }
2893    }
2894    let rgb = background.to_rgb().blend(highlight.to_rgb());
2895    let luminance = 0.2126 * channel(rgb.r) + 0.7152 * channel(rgb.g) + 0.0722 * channel(rgb.b);
2896    // Contrast with black is (L + 0.05) / 0.05 and with white 1.05 / (L + 0.05);
2897    // they are equal where (L + 0.05)^2 = 0.0525.
2898    if (luminance + 0.05) * (luminance + 0.05) > 0.0525 {
2899        gpui::black()
2900    } else {
2901        gpui::white()
2902    }
2903}
2904
2905/// The highlight a text mark renders with. The link decoration is applied by
2906/// the caller, which also has to record the link range.
2907fn mark_highlight(mark: &TextMark, node_cx: &NodeContext, cx: &App) -> InlineHighlight {
2908    let mut highlight = HighlightStyle::default();
2909    if mark.bold {
2910        highlight.font_weight = Some(FontWeight::BOLD);
2911    }
2912    if mark.italic {
2913        highlight.font_style = Some(FontStyle::Italic);
2914    }
2915    if mark.strikethrough {
2916        highlight.strikethrough = Some(gpui::StrikethroughStyle {
2917            thickness: gpui::px(1.),
2918            ..Default::default()
2919        });
2920    }
2921    if mark.underline {
2922        highlight.underline = Some(gpui::UnderlineStyle {
2923            thickness: gpui::px(1.),
2924            ..Default::default()
2925        });
2926    }
2927    let mut font_family = None;
2928    if mark.code {
2929        highlight = highlight.highlight(node_cx.style.inline_code_highlight());
2930        let style = node_cx.style.inline_code_style();
2931        highlight = highlight.highlight(HighlightStyle {
2932            color: style.text.color,
2933            font_weight: style.text.font_weight,
2934            font_style: style.text.font_style,
2935            underline: style.text.underline,
2936            strikethrough: style.text.strikethrough,
2937            ..Default::default()
2938        });
2939        font_family = Some(
2940            style
2941                .text
2942                .font_family
2943                .clone()
2944                .unwrap_or_else(|| cx.theme().tokens.typography.mono),
2945        );
2946    }
2947    if let Some(color) = mark.highlight {
2948        highlight.background_color = Some(color);
2949        // Set the text color with the background, as the HTML standard's
2950        // `mark { background: yellow; color: black }` does, so a light
2951        // highlight stays readable in a dark theme.
2952        // A transparent mark leaves the underlying surface unchanged. Keep
2953        // its inherited foreground, including on custom-colored surfaces.
2954        if color.a > 0.0 {
2955            highlight.color = Some(mark_text_color(color, cx.theme().tokens.colors.background));
2956        }
2957    }
2958    InlineHighlight {
2959        style: highlight,
2960        font_family,
2961        font_size_scale: mark.code.then_some(0.875),
2962        code_style: mark.code.then(|| node_cx.style.inline_code_style().clone()),
2963    }
2964}
2965
2966fn append_node_highlights(
2967    highlights: &mut Vec<(Range<usize>, InlineHighlight)>,
2968    node_highlights: Vec<(Range<usize>, InlineHighlight)>,
2969) {
2970    // Nodes occupy disjoint byte ranges, so normally only their own marks
2971    // overlap. Preserve merging for caller-provided marks extending past a node.
2972    if highlights.last().is_some_and(|(last, _)| {
2973        node_highlights
2974            .iter()
2975            .any(|(range, _)| !range.is_empty() && range.start < last.end)
2976    }) {
2977        *highlights = combine_highlights(std::mem::take(highlights), node_highlights);
2978    } else {
2979        highlights.extend(combine_highlights([], node_highlights));
2980    }
2981}
2982
2983impl Paragraph {
2984    /// The highlights over [`Self::text`], for measuring the paragraph with
2985    /// the runs it renders with. Link colors are left out: they do not move
2986    /// glyphs.
2987    fn inline_highlights(
2988        &self,
2989        node_cx: &NodeContext,
2990        cx: &App,
2991    ) -> Vec<(Range<usize>, InlineHighlight)> {
2992        let mut highlights = vec![];
2993        let mut offset = 0;
2994        for inline_node in &self.children {
2995            let node_highlights = inline_node
2996                .marks
2997                .iter()
2998                .map(|(range, mark)| {
2999                    (
3000                        (offset + range.start)..(offset + range.end),
3001                        mark_highlight(mark, node_cx, cx),
3002                    )
3003                })
3004                .collect::<Vec<_>>();
3005            append_node_highlights(&mut highlights, node_highlights);
3006            offset += inline_node.text.len();
3007        }
3008        highlights
3009    }
3010
3011    /// `fade_key` names this paragraph's text for the streamed fade-in and
3012    /// for range highlights; the owning block supplies it because a heading
3013    /// or table cell paragraph carries no span of its own.
3014    fn render(
3015        &self,
3016        fade_key: Option<TextLeafKey>,
3017        node_cx: &NodeContext,
3018        _window: &mut Window,
3019        cx: &mut App,
3020    ) -> AnyElement {
3021        let children = &self.children;
3022        let fades = node_cx.stream_fades(fade_key);
3023        let backgrounds = node_cx.range_backgrounds(fade_key);
3024
3025        if self.should_render_inline_flow() {
3026            return InlineFlow::new(
3027                self.element_id(fade_key),
3028                self.inline_flow_items(fade_key, fades, backgrounds, node_cx, cx),
3029                node_cx.link_click_handler.clone(),
3030            )
3031            .editor_key(self.leaf_key())
3032            .into_any_element();
3033        }
3034
3035        let has_image = children.iter().any(|child| child.image.is_some());
3036        // Text alone is one `Inline`, which needs no box of its own, and its
3037        // text, highlights and links are cached across frames.
3038        if !has_image {
3039            let (text, highlights, links) = self.plain_render(node_cx, cx);
3040            // An editor leaf is laid out even when empty, so the editor gets
3041            // a line box for the caret.
3042            if text.is_empty() && self.leaf_key().is_none() {
3043                return div().into_any_element();
3044            }
3045            let highlights = fade_highlights(highlights, &slice_fades(fades, 0, text.len()));
3046            let backgrounds = slice_backgrounds(backgrounds, 0, text.len());
3047            let reveal = node_cx.reveal_at(fade_key, 0, text.len());
3048            if let Ok(mut state) = self.state.lock() {
3049                state.set_text(text);
3050            }
3051            return Inline::new(
3052                self.state.clone(),
3053                links,
3054                highlights,
3055                node_cx.link_click_handler.clone(),
3056            )
3057            .range_backgrounds(backgrounds)
3058            .reveal(reveal)
3059            .into_any_element();
3060        }
3061
3062        let mut child_nodes: Vec<AnyElement> = vec![];
3063
3064        let mut text = String::new();
3065        let mut highlights: Vec<(Range<usize>, InlineHighlight)> = vec![];
3066        let mut links: Vec<(Range<usize>, LinkMark)> = vec![];
3067        let mut offset = 0;
3068        // Where `text` starts in the paragraph's whole rendered text, which
3069        // is the byte space the fade ranges use.
3070        let mut consumed = 0;
3071
3072        for (ix, inline_node) in children.iter().enumerate() {
3073            let text_len = inline_node.text.len();
3074            text.push_str(&inline_node.text);
3075
3076            if let Some(image) = &inline_node.image {
3077                if text.len() > 0 {
3078                    if let Ok(mut state) = inline_node.state.lock() {
3079                        state.set_text(text.clone().into());
3080                    }
3081                    child_nodes.push(
3082                        Inline::new(
3083                            inline_node.state.clone(),
3084                            links.clone(),
3085                            fade_highlights(
3086                                highlights.clone(),
3087                                &slice_fades(fades, consumed, consumed + text.len()),
3088                            ),
3089                            node_cx.link_click_handler.clone(),
3090                        )
3091                        .range_backgrounds(slice_backgrounds(
3092                            backgrounds,
3093                            consumed,
3094                            consumed + text.len(),
3095                        ))
3096                        .reveal(node_cx.reveal_at(fade_key, consumed, consumed + text.len()))
3097                        .into_any_element(),
3098                    );
3099                }
3100                let link_click_handler = node_cx.link_click_handler.clone();
3101                let image_link = image.link.as_ref().and_then(|link| node_cx.link(link, cx));
3102                child_nodes.push(
3103                    img(node_cx.image_source(image))
3104                        .id(ix)
3105                        .object_fit(ObjectFit::Contain)
3106                        .max_w(relative(1.))
3107                        .when_some(image.width, |this, width| this.w(width))
3108                        .when_some(image_link, |this, link| {
3109                            let link_click_handler = link_click_handler.clone();
3110                            let aux_link = link.clone();
3111                            let aux_link_click_handler = link_click_handler.clone();
3112                            this.cursor_pointer()
3113                                .on_click(move |event, window, cx| {
3114                                    crate::TextSelection::end(window, cx);
3115                                    cx.stop_propagation();
3116                                    handle_link_click(
3117                                        &link_click_handler,
3118                                        link.url.clone(),
3119                                        event.clone(),
3120                                        window,
3121                                        cx,
3122                                    );
3123                                })
3124                                .on_aux_click(move |event, window, cx| {
3125                                    crate::TextSelection::end(window, cx);
3126                                    cx.stop_propagation();
3127                                    handle_link_click(
3128                                        &aux_link_click_handler,
3129                                        aux_link.url.clone(),
3130                                        event.clone(),
3131                                        window,
3132                                        cx,
3133                                    );
3134                                })
3135                        })
3136                        .into_any_element(),
3137                );
3138
3139                consumed += text.len();
3140                text.clear();
3141                links.clear();
3142                highlights.clear();
3143                offset = 0;
3144            } else {
3145                let mut node_highlights = vec![];
3146                for (range, style) in &inline_node.marks {
3147                    let inner_range = (offset + range.start)..(offset + range.end);
3148                    let mut highlight = mark_highlight(style, node_cx, cx);
3149
3150                    if let Some(link_mark) = style.link.as_ref()
3151                        && let Some(link) = node_cx.link(link_mark, cx)
3152                    {
3153                        highlight.style.color = Some(node_cx.style.link());
3154                        highlight.style.underline = Some(link_underline(&node_cx.style));
3155                        links.push((inner_range.clone(), link));
3156                    }
3157
3158                    node_highlights.push((inner_range, highlight));
3159                }
3160
3161                append_node_highlights(&mut highlights, node_highlights);
3162                offset += text_len;
3163            }
3164        }
3165
3166        // Add the last text node
3167        if text.len() > 0 {
3168            let text_end = consumed + text.len();
3169            let highlights = fade_highlights(highlights, &slice_fades(fades, consumed, text_end));
3170            if let Ok(mut state) = self.state.lock() {
3171                state.set_text(text.into());
3172            }
3173            child_nodes.push(
3174                Inline::new(
3175                    self.state.clone(),
3176                    links,
3177                    highlights,
3178                    node_cx.link_click_handler.clone(),
3179                )
3180                .range_backgrounds(slice_backgrounds(backgrounds, consumed, text_end))
3181                .reveal(node_cx.reveal_at(fade_key, consumed, text_end))
3182                .into_any_element(),
3183            );
3184        }
3185
3186        // Text alone is one `Inline`, which needs no box of its own. Images
3187        // keep an identified box: an image's element state is its animation,
3188        // and the box scopes that state per paragraph.
3189        if !has_image {
3190            return child_nodes
3191                .pop()
3192                .unwrap_or_else(|| div().into_any_element());
3193        }
3194
3195        div()
3196            .id(self.element_id(fade_key))
3197            .children(child_nodes)
3198            .into_any_element()
3199    }
3200
3201    /// The element id of this paragraph when it needs one: an inline flow,
3202    /// whose objects are accessibility nodes, or an image, whose element
3203    /// state is its animation. The leaf key is unique per paragraph in a
3204    /// parsed Markdown document. The HTML parser records no spans, so its
3205    /// paragraphs fall back to an id derived from their own render state:
3206    /// sharing one name mounted every span-less flow under the same id, and
3207    /// the flows read each other's cached layout.
3208    fn element_id(&self, fade_key: Option<TextLeafKey>) -> ElementId {
3209        match fade_key {
3210            Some(key) => ElementId::from(key),
3211            None => ElementId::NamedInteger(
3212                "p".into(),
3213                Arc::as_ptr(&self.state) as *const () as usize as u64,
3214            ),
3215        }
3216    }
3217
3218    /// The key an external editor gave this leaf, if any.
3219    fn leaf_key(&self) -> Option<u64> {
3220        self.state.lock().ok().and_then(|state| state.editor_key)
3221    }
3222
3223    fn should_render_inline_flow(&self) -> bool {
3224        let images = self
3225            .children
3226            .iter()
3227            .filter(|child| child.image.is_some())
3228            .count();
3229        let has_text = self.children.iter().any(|child| !child.text.is_empty());
3230        // An editor leaf with an image always uses the flow, which reports
3231        // its pieces to the editor (an image-only paragraph would otherwise
3232        // take the plain image path, which reports nothing).
3233        if images > 0 && self.leaf_key().is_some() {
3234            return true;
3235        }
3236        // Images are inline content: several of them share a line, as words
3237        // do, even with nothing between them. The plain path stacks them.
3238        self.children.iter().any(|child| child.custom.is_some())
3239            || images > 1
3240            || (images > 0 && has_text)
3241            || self
3242                .children
3243                .iter()
3244                .any(|child| child.marks.iter().any(|(_, mark)| mark.code))
3245    }
3246
3247    fn inline_flow_items(
3248        &self,
3249        leaf_key: Option<TextLeafKey>,
3250        fades: &[(Range<usize>, f32)],
3251        backgrounds: &[(Range<usize>, Hsla)],
3252        node_cx: &NodeContext,
3253        cx: &mut App,
3254    ) -> Vec<InlineFlowItem> {
3255        let mut items = Vec::new();
3256        let mut text = String::new();
3257        let mut highlights: Vec<(Range<usize>, InlineHighlight)> = vec![];
3258        let mut links: Vec<(Range<usize>, LinkMark)> = vec![];
3259        let mut offset = 0;
3260        // Where `text` starts in the paragraph's whole rendered text, which
3261        // is the byte space the fade and background ranges use.
3262        let mut consumed = 0;
3263
3264        for inline_node in &self.children {
3265            if let Some(node) = &inline_node.custom {
3266                if let Ok(mut state) = inline_node.state.lock() {
3267                    state.set_text(text.clone().into());
3268                }
3269                if !text.is_empty() {
3270                    let item_fades = slice_fades(fades, consumed, consumed + text.len());
3271                    let item_backgrounds =
3272                        slice_backgrounds(backgrounds, consumed, consumed + text.len());
3273                    let item_reveal = node_cx.reveal_at(leaf_key, consumed, consumed + text.len());
3274                    consumed += text.len();
3275                    items.push(InlineFlowItem::Text {
3276                        state: inline_node.state.clone(),
3277                        text: std::mem::take(&mut text).into(),
3278                        links: std::mem::take(&mut links),
3279                        highlights: fade_highlights(std::mem::take(&mut highlights), &item_fades),
3280                        backgrounds: item_backgrounds,
3281                        reveal: item_reveal,
3282                    });
3283                }
3284                let mut object_style = HighlightStyle::default();
3285                let mut object_link = None;
3286                for (_, mark) in &inline_node.marks {
3287                    object_style = object_style.highlight(mark_highlight(mark, node_cx, cx).style);
3288                    if let Some(link) = mark.link.as_ref().and_then(|link| node_cx.link(link, cx)) {
3289                        object_link = Some(link);
3290                        object_style.color = Some(node_cx.style.link());
3291                        object_style.underline = Some(link_underline(&node_cx.style));
3292                    }
3293                }
3294                let rendered_node = node.clone();
3295                let extensions = node_cx.markdown_extensions.clone();
3296                items.push(InlineFlowItem::Object {
3297                    text: node.shared_text(),
3298                    accessibility_label: node.shared_accessibility_name(),
3299                    id: node.source_range().map_or(items.len(), |range| range.start),
3300                    renderer: Arc::new(move |context, window, cx| {
3301                        extensions.render_inline(&rendered_node, context, window, cx)
3302                    }),
3303                    selected: inline_node.custom_selection.clone(),
3304                    style: object_style,
3305                    link: object_link,
3306                });
3307                consumed += inline_node.text.len();
3308                offset = 0;
3309                continue;
3310            }
3311            let text_len = inline_node.text.len();
3312            text.push_str(&inline_node.text);
3313
3314            if let Some(image) = &inline_node.image {
3315                if !text.is_empty() {
3316                    if let Ok(mut state) = inline_node.state.lock() {
3317                        state.set_text(text.clone().into());
3318                    }
3319                    items.push(InlineFlowItem::Text {
3320                        state: inline_node.state.clone(),
3321                        text: text.clone().into(),
3322                        links: links.clone(),
3323                        highlights: fade_highlights(
3324                            highlights.clone(),
3325                            &slice_fades(fades, consumed, consumed + text.len()),
3326                        ),
3327                        backgrounds: slice_backgrounds(
3328                            backgrounds,
3329                            consumed,
3330                            consumed + text.len(),
3331                        ),
3332                        reveal: node_cx.reveal_at(leaf_key, consumed, consumed + text.len()),
3333                    });
3334                }
3335
3336                items.push(InlineFlowItem::Image {
3337                    source: node_cx.image_source(image),
3338                    link: image.link.as_ref().and_then(|link| node_cx.link(link, cx)),
3339                    title: image.title(),
3340                    width: image.width,
3341                    height: image.height,
3342                });
3343
3344                consumed += text.len();
3345                text.clear();
3346                links.clear();
3347                highlights.clear();
3348                offset = 0;
3349            } else {
3350                let mut node_highlights = vec![];
3351                for (range, style) in &inline_node.marks {
3352                    let inner_range = (offset + range.start)..(offset + range.end);
3353                    let mut highlight = mark_highlight(style, node_cx, cx);
3354
3355                    if let Some(link_mark) = style.link.as_ref()
3356                        && let Some(link) = node_cx.link(link_mark, cx)
3357                    {
3358                        highlight.style.color = Some(node_cx.style.link());
3359                        highlight.style.underline = Some(link_underline(&node_cx.style));
3360                        links.push((inner_range.clone(), link));
3361                    }
3362
3363                    node_highlights.push((inner_range, highlight));
3364                }
3365
3366                append_node_highlights(&mut highlights, node_highlights);
3367                offset += text_len;
3368            }
3369        }
3370
3371        if !text.is_empty() {
3372            if let Ok(mut state) = self.state.lock() {
3373                state.set_text(text.clone().into());
3374            }
3375            let highlights = fade_highlights(
3376                highlights,
3377                &slice_fades(fades, consumed, consumed + text.len()),
3378            );
3379            let backgrounds = slice_backgrounds(backgrounds, consumed, consumed + text.len());
3380            let reveal = node_cx.reveal_at(leaf_key, consumed, consumed + text.len());
3381            items.push(InlineFlowItem::Text {
3382                state: self.state.clone(),
3383                text: text.into(),
3384                links,
3385                highlights,
3386                backgrounds,
3387                reveal,
3388            });
3389        }
3390
3391        let foregrounds = node_cx.foregrounds(self.leaf_key());
3392        if !foregrounds.is_empty() {
3393            let mut offset = 0;
3394            for item in &mut items {
3395                match item {
3396                    InlineFlowItem::Text {
3397                        text, highlights, ..
3398                    } => {
3399                        *highlights = foreground_highlights(
3400                            std::mem::take(highlights),
3401                            text,
3402                            offset,
3403                            foregrounds,
3404                        );
3405                        offset += text.len();
3406                    }
3407                    InlineFlowItem::Object { style, .. } => {
3408                        let end = offset + '\u{FFFC}'.len_utf8();
3409                        if let Some((_, color)) = foregrounds
3410                            .iter()
3411                            .rev()
3412                            .find(|(range, _)| range.start <= offset && end <= range.end)
3413                        {
3414                            style.color = Some(*color);
3415                        }
3416                        offset = end;
3417                    }
3418                    InlineFlowItem::Image { .. } => offset += '\u{FFFC}'.len_utf8(),
3419                }
3420            }
3421        }
3422        items
3423    }
3424}
3425
3426/// The element id of a block that needs one, from `kind` and the block's
3427/// source start, which is unique across a parsed Markdown document. The HTML
3428/// parser records no spans, so its blocks fall back to their index among
3429/// their siblings: unique among them, though not across nesting levels.
3430fn block_element_id(kind: &'static str, span: Option<Span>, ix: usize) -> ElementId {
3431    (kind, span.map_or(ix, |span| span.start)).into()
3432}
3433
3434/// A link's underline: a hairline in a translucent link color, so a run of
3435/// links reads as text first and as links second.
3436fn link_underline(style: &TextViewStyle) -> gpui::UnderlineStyle {
3437    gpui::UnderlineStyle {
3438        thickness: px(1.),
3439        color: Some(style.link().opacity(0.4)),
3440        ..Default::default()
3441    }
3442}
3443
3444/// The font size the blocks inherit, which heading sizes and the spacing of
3445/// lists, tables and rules are proportional to (like CSS `em`), so a compact
3446/// 14px view and a 16px document keep the same rhythm.
3447///
3448/// Resolved once per frame into the context; a context built without it
3449/// (as in tests) resolves it from the window.
3450fn body_font_size(node_cx: &NodeContext, window: &Window) -> Pixels {
3451    if node_cx.body_font_size > Pixels::ZERO {
3452        node_cx.body_font_size
3453    } else {
3454        window.text_style().font_size.to_pixels(window.rem_size())
3455    }
3456}
3457
3458/// A heading's `(size scale, line height, section gap)`, the size relative to
3459/// the body text and the gap above it relative to the heading itself.
3460/// Hierarchy comes from weight rather than size: every level is semibold and
3461/// the sizes step down gently from the body.
3462fn heading_metrics(level: u8) -> (f32, f32, f32) {
3463    match level {
3464        1 => (1.8, 1.25, 1.1),
3465        2 => (4. / 3., 1.35, 1.6),
3466        3 => (17. / 15., 1.35, 1.4),
3467        4 => (1., 1.35, 1.4),
3468        5 => (14. / 15., 1.35, 1.4),
3469        _ => (13. / 15., 1.35, 1.4),
3470    }
3471}
3472
3473/// The gap below a heading, relative to the heading's size.
3474const HEADING_BOTTOM_GAP: f32 = 0.35;
3475
3476/// The size a heading renders at, including one a caller's heading
3477/// refinement pins, which its gaps follow.
3478fn heading_size(level: u8, node_cx: &NodeContext, window: &Window) -> Pixels {
3479    node_cx.style.heading(level).text.font_size.map_or_else(
3480        || body_font_size(node_cx, window) * heading_metrics(level).0,
3481        |size| size.to_pixels(window.rem_size()),
3482    )
3483}
3484
3485/// The room above and below a horizontal rule.
3486fn rule_space(body_font_size: Pixels) -> Pixels {
3487    body_font_size * 1.6
3488}
3489
3490/// The gap below a block: a paragraph gap, unless nothing follows it.
3491fn block_gap(options: &NodeRenderOptions, style: &TextViewStyle) -> Rems {
3492    if options.in_list || options.is_last {
3493        rems(0.)
3494    } else {
3495        style.paragraph_gap()
3496    }
3497}
3498
3499/// `block` with `gap` below it. The box only exists to hold the padding,
3500/// so a block with no gap below it is returned as is.
3501fn gapped(block: AnyElement, gap: Rems) -> AnyElement {
3502    if gap.is_zero() {
3503        block
3504    } else {
3505        div().pb(gap).child(block).into_any_element()
3506    }
3507}
3508
3509/// The fade ranges overlapping `start..end`, rebased to start at `start`.
3510fn slice_fades(
3511    fades: &[(Range<usize>, f32)],
3512    start: usize,
3513    end: usize,
3514) -> Vec<(Range<usize>, f32)> {
3515    slice_ranges(fades, start, end, |range, fade_out| (range, *fade_out))
3516}
3517
3518/// The range highlight backgrounds overlapping `start..end`, rebased to
3519/// start at `start`.
3520fn slice_backgrounds(
3521    backgrounds: &[(Range<usize>, Hsla)],
3522    start: usize,
3523    end: usize,
3524) -> Vec<(Range<usize>, Hsla)> {
3525    slice_ranges(backgrounds, start, end, |range, color| (range, *color))
3526}
3527
3528/// A table column's cell widths for layout, excluding the divider after it.
3529struct TableColumn {
3530    /// The width that fits the content on its widest line.
3531    max: f32,
3532    /// The width below which the column stops shrinking.
3533    min: f32,
3534    divider: f32,
3535}
3536
3537/// Horizontal padding of a table cell: `px_3` unless `style.table_cell`
3538/// sets it.
3539fn table_cell_padding_x(style: &TextViewStyle, rem_size: Pixels) -> f32 {
3540    let padding = &style.table_cell().padding;
3541    let side = |length: Option<DefiniteLength>| match length {
3542        Some(DefiniteLength::Absolute(length)) => f32::from(length.to_pixels(rem_size)),
3543        _ => CELL_PAD_PX / 2.,
3544    };
3545    side(padding.left) + side(padding.right)
3546}
3547
3548const CELL_PAD_PX: f32 = 24.0; // px_3 horizontal padding
3549const CELL_MIN_PX: f32 = 48.0;
3550const CELL_BORDER_PX: f32 = 1.0; // border_r_1 drawn by every column but the last
3551
3552/// The max-content width of every table column: the widest cell line,
3553/// shaped with the runs the cell renders with, plus the cell's padding and
3554/// border. Never capped: a cap would clip overflowing text *and* leave it
3555/// outside the scrollable width, making it unreachable.
3556fn measure_table_columns(
3557    table: &Table,
3558    col_count: usize,
3559    node_cx: &NodeContext,
3560    window: &mut Window,
3561    cx: &mut App,
3562) -> Vec<f32> {
3563    let text_styles = TableTextStyles::new(&node_cx.style, window);
3564    let rem_size = window.rem_size();
3565    let mono_family = cx.theme().tokens.typography.mono;
3566    let inline_code = node_cx.style.inline_code_highlight();
3567    let cached = table.column_widths_cache.0.lock().ok().and_then(|cache| {
3568        cache
3569            .as_ref()
3570            .filter(|cached| {
3571                cached.widths.len() == col_count
3572                    && cached.text_styles == text_styles
3573                    && cached.rem_size == rem_size
3574                    && cached.mono_family == mono_family
3575                    && cached.inline_code == inline_code
3576                    && cached.text_system == text_system_id(window)
3577            })
3578            .cloned()
3579    });
3580    let measured = cached.unwrap_or_else(|| {
3581        let (widths, custom_cells) =
3582            measure_table_text_columns(table, col_count, &text_styles, node_cx, window, cx);
3583        let measured = Arc::new(TableColumnWidths {
3584            text_system: text_system_id(window),
3585            text_styles: text_styles.clone(),
3586            rem_size,
3587            mono_family,
3588            inline_code,
3589            widths,
3590            custom_cells,
3591        });
3592        if let Ok(mut cache) = table.column_widths_cache.0.lock() {
3593            *cache = Some(measured.clone());
3594        }
3595        measured
3596    });
3597
3598    // Resource-backed cells must be measured again, even when their text is
3599    // unchanged. Keep callbacks outside the cache lock and do not retain their
3600    // widths: a loaded image or a plugin can get narrower as well as wider.
3601    let mut col_w = measured.widths.clone();
3602    for &(row_ix, ix) in &measured.custom_cells {
3603        let cell = &table.children[row_ix].children[ix];
3604        let items = cell.children.inline_flow_items(None, &[], &[], node_cx, cx);
3605        let style = text_styles.row_refinement(row_ix).clone();
3606        let width = window.with_text_style(Some(style), |window| {
3607            super::inline_flow::intrinsic_width(&items, window, cx)
3608        });
3609        let border = if ix + 1 < col_count {
3610            CELL_BORDER_PX
3611        } else {
3612            0.
3613        };
3614        col_w[ix] = col_w[ix].max(f32::from(width) + CELL_PAD_PX + border);
3615    }
3616    col_w
3617}
3618
3619// The first measurement still visits all ordinary cells. This cache avoids
3620// repeating that work; it is not a budget for the initial table layout.
3621fn measure_table_text_columns(
3622    table: &Table,
3623    col_count: usize,
3624    text_styles: &TableTextStyles,
3625    node_cx: &NodeContext,
3626    window: &mut Window,
3627    cx: &mut App,
3628) -> (Vec<f32>, Vec<(usize, usize)>) {
3629    let mut col_w = vec![CELL_MIN_PX; col_count];
3630    let mut custom_cells = Vec::new();
3631    for (row_ix, row) in table.children.iter().enumerate() {
3632        let text_style = text_styles.row(row_ix);
3633        let font_size = text_style.font_size.to_pixels(window.rem_size());
3634        for (ix, cell) in row.children.iter().enumerate() {
3635            let Some(slot) = col_w.get_mut(ix) else {
3636                continue;
3637            };
3638            if cell
3639                .children
3640                .children
3641                .iter()
3642                .any(|node| node.custom.is_some() || node.image.is_some())
3643            {
3644                custom_cells.push((row_ix, ix));
3645                continue;
3646            }
3647            let text = cell.children.text();
3648            let highlights = cell.children.inline_highlights(node_cx, cx);
3649            let mut w = 0.0_f32;
3650            let mut line_start = 0;
3651            for line in text.split('\n') {
3652                let start = line_start + (line.len() - line.trim_start().len());
3653                let line_end = line_start + line.len();
3654                line_start = line_end + 1;
3655                let line = line.trim();
3656                if line.is_empty() {
3657                    continue;
3658                }
3659                let end = start + line.len();
3660                let line_highlights = highlights
3661                    .iter()
3662                    .filter_map(|(range, highlight)| {
3663                        let clipped = range.start.max(start)..range.end.min(end);
3664                        (clipped.start < clipped.end).then(|| {
3665                            (
3666                                clipped.start - start..clipped.end - start,
3667                                highlight.clone(),
3668                            )
3669                        })
3670                    })
3671                    .collect::<Vec<_>>();
3672                let mut line_w = gpui::Pixels::ZERO;
3673                for (range, scale) in
3674                    text_size_ranges(line.len(), &line_highlights, font_size, window.rem_size())
3675                {
3676                    let highlights = slice_ranges(
3677                        &line_highlights,
3678                        range.start,
3679                        range.end,
3680                        |range, highlight| (range, highlight.clone()),
3681                    );
3682                    let insets = code_insets(&highlights, font_size * scale, window.rem_size());
3683                    line_w += insets.left + insets.right;
3684                    let runs = text_runs(range.len(), text_style, &highlights);
3685                    line_w += window
3686                        .text_system()
3687                        .layout_line(&line[range], font_size * scale, &runs, None)
3688                        .width;
3689                }
3690                w = w.max(f32::from(line_w));
3691            }
3692            // Border-box widths, so the padding and border the cell draws
3693            // must leave the measured text its full width.
3694            let border = if ix + 1 < col_count {
3695                CELL_BORDER_PX
3696            } else {
3697                0.
3698            };
3699            *slot = slot.max(w + CELL_PAD_PX + border);
3700        }
3701    }
3702    (col_w, custom_cells)
3703}
3704
3705impl Paragraph {
3706    fn to_markdown(&self) -> String {
3707        if self.children.iter().any(|node| node.custom.is_some()) {
3708            let mut source = MarkdownSource::default();
3709            for node in &self.children {
3710                if node.custom.is_some() {
3711                    source.push_object(node);
3712                } else {
3713                    source.push_text(&node.text, &node.marks, 0..node.text.len());
3714                    if let Some(image) = &node.image {
3715                        source.push_str(&image_markdown(image));
3716                    }
3717                }
3718            }
3719            let mut text = source.finish();
3720            text.push_str("\n\n");
3721            return text;
3722        }
3723        let mut text = self
3724            .children
3725            .iter()
3726            .map(|text_node| {
3727                let mut text = text_node.text.to_string();
3728                for (range, style) in &text_node.marks {
3729                    if style.bold {
3730                        text = format!("**{}**", &text_node.text[range.clone()]);
3731                    }
3732                    if style.italic {
3733                        text = format!("*{}*", &text_node.text[range.clone()]);
3734                    }
3735                    if style.strikethrough {
3736                        text = format!("~~{}~~", &text_node.text[range.clone()]);
3737                    }
3738                    if style.code {
3739                        text = format!("`{}`", &text_node.text[range.clone()]);
3740                    }
3741                    if style.highlight.is_some() {
3742                        text = format!("=={}==", &text_node.text[range.clone()]);
3743                    }
3744                    if let Some(link) = &style.link {
3745                        text = format!("[{}]({})", &text_node.text[range.clone()], link.url);
3746                    }
3747                }
3748
3749                if let Some(image) = &text_node.image {
3750                    let alt = image.alt.clone().unwrap_or_default();
3751                    let title = image
3752                        .title
3753                        .clone()
3754                        .map_or(String::new(), |t| format!(" \"{}\"", t));
3755                    text.push_str(&format!("![{}]({}{})", alt, image.url, title))
3756                }
3757
3758                text
3759            })
3760            .collect::<Vec<_>>()
3761            .join("");
3762
3763        text.push_str("\n\n");
3764        text
3765    }
3766}
3767
3768impl BlockNode {
3769    /// Converts the node to markdown format.
3770    ///
3771    /// This is used to generate markdown for test.
3772    #[allow(dead_code)]
3773    pub(crate) fn to_markdown(&self) -> String {
3774        match self {
3775            BlockNode::Root { children, .. } => children
3776                .iter()
3777                .map(|child| child.to_markdown())
3778                .collect::<Vec<_>>()
3779                .join("\n\n"),
3780            BlockNode::Paragraph(paragraph) => paragraph.to_markdown(),
3781            BlockNode::Heading {
3782                level, children, ..
3783            } => {
3784                let hashes = "#".repeat(*level as usize);
3785                format!("{} {}", hashes, children.to_markdown())
3786            }
3787            BlockNode::Blockquote { children, .. } => {
3788                let content = children
3789                    .iter()
3790                    .map(|child| child.to_markdown())
3791                    .collect::<Vec<_>>()
3792                    .join("\n\n");
3793
3794                content
3795                    .lines()
3796                    .map(|line| format!("> {}", line))
3797                    .collect::<Vec<_>>()
3798                    .join("\n")
3799            }
3800            BlockNode::Surface { name, children, .. } => {
3801                let content = children
3802                    .iter()
3803                    .map(|child| child.to_markdown())
3804                    .collect::<Vec<_>>()
3805                    .join("\n\n");
3806                quoted_source(Some(name), &content)
3807            }
3808            BlockNode::List {
3809                children,
3810                ordered,
3811                start,
3812                ..
3813            } => children
3814                .iter()
3815                .enumerate()
3816                .map(|(i, child)| {
3817                    let prefix = if *ordered {
3818                        format!("{}. ", ordered_list_ordinal(*start, i))
3819                    } else {
3820                        "- ".to_string()
3821                    };
3822                    format!("{}{}", prefix, child.to_markdown())
3823                })
3824                .collect::<Vec<_>>()
3825                .join("\n"),
3826            BlockNode::ListItem {
3827                children, checked, ..
3828            } => {
3829                let checkbox = if let Some(checked) = checked {
3830                    if *checked { "[x] " } else { "[ ] " }
3831                } else {
3832                    ""
3833                };
3834                format!(
3835                    "{}{}",
3836                    checkbox,
3837                    children
3838                        .iter()
3839                        .map(|child| child.to_markdown())
3840                        .collect::<Vec<_>>()
3841                        .join("\n")
3842                )
3843            }
3844            BlockNode::CodeBlock(code_block) => {
3845                format!(
3846                    "```{}\n{}\n```",
3847                    code_block.lang.clone().unwrap_or_default(),
3848                    code_block.code()
3849                )
3850            }
3851            BlockNode::Table(table) => table.to_markdown(),
3852            BlockNode::Break { html, .. } => {
3853                if *html {
3854                    "<br>".to_string()
3855                } else {
3856                    "\n".to_string()
3857                }
3858            }
3859            BlockNode::HorizontalRule { .. } => "---".to_string(),
3860            BlockNode::Custom { node, .. } => node.to_markdown(),
3861            BlockNode::Definition {
3862                identifier,
3863                url,
3864                title,
3865                ..
3866            } => {
3867                if let Some(title) = title {
3868                    format!("[{}]: {} \"{}\"", identifier, url, title)
3869                } else {
3870                    format!("[{}]: {}", identifier, url)
3871                }
3872            }
3873            BlockNode::Unknown { .. } => "".to_string(),
3874        }
3875        .trim()
3876        .to_string()
3877    }
3878}
3879
3880impl BlockNode {
3881    /// `task_toggle` is the view's task toggle handler with the event a click
3882    /// on the item's checkbox reports, when the checkbox should be clickable.
3883    #[allow(clippy::too_many_arguments)]
3884    fn render_list_item_row(
3885        content: AnyElement,
3886        ix: usize,
3887        options: NodeRenderOptions,
3888        checked: Option<bool>,
3889        task_toggle: Option<(Arc<TaskToggleHandlerFn>, TaskToggleEvent)>,
3890        style: &TextViewStyle,
3891        line_height: Pixels,
3892        indent: Pixels,
3893    ) -> Div {
3894        h_flex()
3895            .w_full()
3896            .min_w_0()
3897            .relative()
3898            .items_start()
3899            .content_start()
3900            .when(!options.todo && checked.is_none(), |this| {
3901                // The marker hangs in an indent column, right-aligned against
3902                // the text like an outside list marker, and steps back in
3903                // color so the item text leads.
3904                this.child(
3905                    div()
3906                        .flex_none()
3907                        .min_w(indent)
3908                        .pr(indent * 0.3)
3909                        .text_right()
3910                        .text_color(style.muted_foreground())
3911                        .refine_style(style.list_style())
3912                        .child(
3913                            list_item_prefix(
3914                                ix,
3915                                options.list_start,
3916                                options.ordered,
3917                                options.depth,
3918                            )
3919                            .trim_end()
3920                            .to_string(),
3921                        ),
3922                )
3923            })
3924            .when_some(checked, |this, checked| {
3925                // Todo list checkbox
3926                let check_svg = if style.is_dark() {
3927                    CHECK_SVG_DARK
3928                } else {
3929                    CHECK_SVG_LIGHT
3930                };
3931                this.child(
3932                    div()
3933                        .flex()
3934                        .mr_2()
3935                        .h(line_height)
3936                        .flex_none()
3937                        .items_center()
3938                        .justify_center()
3939                        .child(
3940                            div()
3941                                .flex()
3942                                .size(rems(0.9375))
3943                                .items_center()
3944                                .justify_center()
3945                                .rounded(px(4.))
3946                                .border(px(1.5))
3947                                .border_color(
3948                                    style
3949                                        .list_style()
3950                                        .text
3951                                        .color
3952                                        .unwrap_or(style.muted_foreground()),
3953                                )
3954                                .when(checked, |this| {
3955                                    this.bg(style.link()).border_color(style.link()).child(
3956                                        img(Arc::new(Image::from_bytes(
3957                                            ImageFormat::Svg,
3958                                            check_svg.to_vec(),
3959                                        )))
3960                                        .size(rems(0.75)),
3961                                    )
3962                                }),
3963                        )
3964                        .map(|checkbox| match task_toggle {
3965                            Some((handler, event)) => checkbox
3966                                .id(("task-toggle", event.item_range().start))
3967                                .on_click(move |_, window, cx| {
3968                                    crate::TextSelection::end(window, cx);
3969                                    cx.stop_propagation();
3970                                    handler(&event, window, cx);
3971                                })
3972                                .into_any_element(),
3973                            None => checkbox.into_any_element(),
3974                        }),
3975                )
3976            })
3977            .child(
3978                div()
3979                    // Include the body in intrinsic width measurement, while
3980                    // still letting it shrink and wrap in a constrained row.
3981                    .flex_auto()
3982                    .min_w_0()
3983                    .overflow_hidden()
3984                    // A done task steps back so the open ones stand out.
3985                    .when(checked == Some(true), |this| {
3986                        this.text_color(style.muted_foreground())
3987                    })
3988                    .child(content),
3989            )
3990    }
3991
3992    fn render_list_item(
3993        item: &BlockNode,
3994        ix: usize,
3995        options: NodeRenderOptions,
3996        node_cx: &NodeContext,
3997        window: &mut Window,
3998        cx: &mut App,
3999    ) -> AnyElement {
4000        match item {
4001            BlockNode::ListItem {
4002                children,
4003                spread,
4004                checked,
4005                task_marker,
4006                span,
4007            } => {
4008                let body = body_font_size(node_cx, window);
4009                let indent = body * 1.4;
4010                let task_toggle = match (&node_cx.task_toggle_handler, checked, span, task_marker) {
4011                    (Some(handler), Some(checked), Some(item), Some(marker)) => Some((
4012                        handler.clone(),
4013                        TaskToggleEvent::new(
4014                            !checked,
4015                            item.start..item.end,
4016                            marker.start..marker.end,
4017                        ),
4018                    )),
4019                    _ => None,
4020                };
4021                div()
4022                    .w_full()
4023                    .min_w_0()
4024                    // Items breathe a little apart, less than paragraphs do.
4025                    .when(ix > 0, |this| this.pt(body * 0.25))
4026                    .when(*spread, |this| this.child(div()))
4027                    .children({
4028                        let mut items: Vec<Div> = Vec::with_capacity(children.len());
4029
4030                        for (child_ix, child) in children.iter().enumerate() {
4031                            match child {
4032                                BlockNode::Paragraph { .. } => {
4033                                    let continuation = child_ix > 0;
4034                                    let last_not_list = continuation
4035                                        && !matches!(
4036                                            children[child_ix - 1],
4037                                            BlockNode::List { .. }
4038                                        );
4039
4040                                    let text = child.render_block(
4041                                        NodeRenderOptions {
4042                                            depth: options.depth + 1,
4043                                            todo: checked.is_some(),
4044                                            is_last: true,
4045                                            ..options
4046                                        },
4047                                        node_cx,
4048                                        window,
4049                                        cx,
4050                                    );
4051
4052                                    // Continuation paragraph — stack vertically below
4053                                    // the previous row, indented to align with the text
4054                                    // column (past bullet/number prefix).
4055                                    if last_not_list {
4056                                        if let Some(preceding_row) = items.pop() {
4057                                            items.push(
4058                                                div().child(preceding_row).child(
4059                                                    div()
4060                                                        .w_full()
4061                                                        .pl(indent)
4062                                                        .overflow_hidden()
4063                                                        .child(text),
4064                                                ),
4065                                            );
4066                                            continue;
4067                                        }
4068                                    }
4069
4070                                    // A paragraph after a nested sub-list still
4071                                    // belongs to this item: it takes no marker of
4072                                    // its own, but lines up with the item's text.
4073                                    if continuation {
4074                                        items.push(
4075                                            div()
4076                                                .w_full()
4077                                                .min_w_0()
4078                                                .pl(indent)
4079                                                .overflow_hidden()
4080                                                .child(text),
4081                                        );
4082                                        continue;
4083                                    }
4084
4085                                    items.push(Self::render_list_item_row(
4086                                        text,
4087                                        ix,
4088                                        options,
4089                                        *checked,
4090                                        task_toggle.clone(),
4091                                        &node_cx.style,
4092                                        window.line_height(),
4093                                        indent,
4094                                    ));
4095                                }
4096                                BlockNode::List { .. } => {
4097                                    items.push(div().ml(indent).child(child.render_block(
4098                                        NodeRenderOptions {
4099                                            depth: options.depth + 1,
4100                                            todo: checked.is_some(),
4101                                            is_last: true,
4102                                            ..options
4103                                        },
4104                                        node_cx,
4105                                        window,
4106                                        cx,
4107                                    )));
4108                                }
4109                                BlockNode::Root { .. }
4110                                | BlockNode::Heading { .. }
4111                                | BlockNode::Blockquote { .. }
4112                                | BlockNode::Surface { .. }
4113                                | BlockNode::CodeBlock(_)
4114                                | BlockNode::Custom { .. }
4115                                | BlockNode::Table(_)
4116                                | BlockNode::HorizontalRule { .. } => {
4117                                    let block = child.render_block(
4118                                        NodeRenderOptions {
4119                                            depth: options.depth + 1,
4120                                            todo: checked.is_some(),
4121                                            is_last: true,
4122                                            ..options
4123                                        },
4124                                        node_cx,
4125                                        window,
4126                                        cx,
4127                                    );
4128
4129                                    if child_ix == 0 {
4130                                        items.push(Self::render_list_item_row(
4131                                            block,
4132                                            ix,
4133                                            options,
4134                                            *checked,
4135                                            task_toggle.clone(),
4136                                            &node_cx.style,
4137                                            window.line_height(),
4138                                            indent,
4139                                        ));
4140                                    } else {
4141                                        // Indent continuation blocks to align with a
4142                                        // nested sub-list (`ml(indent)`) and with
4143                                        // continuation paragraphs.
4144                                        items.push(
4145                                            div()
4146                                                .w_full()
4147                                                .min_w_0()
4148                                                .pl(indent)
4149                                                .overflow_hidden()
4150                                                .child(block),
4151                                        );
4152                                    }
4153                                }
4154                                BlockNode::ListItem { .. }
4155                                | BlockNode::Break { .. }
4156                                | BlockNode::Definition { .. }
4157                                | BlockNode::Unknown => {}
4158                            }
4159                        }
4160                        items
4161                    })
4162                    .into_any_element()
4163            }
4164            _ => div().into_any_element(),
4165        }
4166    }
4167
4168    /// Render a Markdown table.
4169    ///
4170    /// Columns are sized from the measured max-content width of their cells,
4171    /// so they line up and fit their content on proportional fonts and mixed
4172    /// scripts alike. The layout adapts to the frame:
4173    ///
4174    /// - Wider than the content: every column fits its content and the spare
4175    ///   width is shared in proportion to it.
4176    /// - Narrower: the narrow columns keep their full content width and only
4177    ///   the widest ones shrink and wrap, all down to one common width (see
4178    ///   [`Self::render_table_rows`]). Shrinking every column by the same
4179    ///   ratio would wrap the last word or character of a column that nearly
4180    ///   fits onto a line of its own.
4181    /// - Narrower than the column floors: the default layout clips, while
4182    ///   `style.table` overflow-x: scroll keeps the floors and scrolls
4183    ///   horizontally, so no content ever becomes unreachable.
4184    ///
4185    /// `white_space: nowrap` on `style.table_cell` composes like in CSS: the
4186    /// refinement keeps cell text on a single line, and the scroll layout
4187    /// raises the floors to the full content widths so the single-line
4188    /// columns never shrink.
4189    fn render_table(
4190        item: &BlockNode,
4191        options: &NodeRenderOptions,
4192        node_cx: &NodeContext,
4193        text_size: Pixels,
4194        window: &mut Window,
4195        cx: &mut App,
4196    ) -> impl IntoElement {
4197        // A scrolling column stops shrinking (and the table starts to scroll)
4198        // at a floor scaled to its content: roughly the width at which the
4199        // text wraps to `CELL_WRAP_MAX_LINES` lines, clamped between the two
4200        // bounds so moderate columns can still wrap meaningfully while one
4201        // huge column cannot push the scroll threshold arbitrarily high.
4202        const CELL_WRAP_MAX_LINES: f32 = 2.0;
4203        const CELL_WRAP_MIN_PX: f32 = 160.0;
4204        const CELL_WRAP_MAX_PX: f32 = 480.0;
4205        const TABLE_BORDER_PX: f32 = 2.0; // the frame's border_1, left + right
4206
4207        let table = match item {
4208            BlockNode::Table(table) => table,
4209            _ => return div().into_any_element(),
4210        };
4211
4212        let style = &node_cx.style;
4213        let col_count = table
4214            .children
4215            .iter()
4216            .map(|row| row.children.len())
4217            .max()
4218            .unwrap_or(0);
4219        let col_w = measure_table_columns(table, col_count, node_cx, window, cx);
4220        let scroll = matches!(style.table().overflow.x, Some(Overflow::Scroll));
4221        let nowrap = style.table_cell().text.white_space == Some(WhiteSpace::Nowrap);
4222        let rem_size = window.rem_size();
4223        let wrap_min_px = f32::from(rems(4.).to_pixels(rem_size));
4224        // Widths were measured with the default cell padding.
4225        let padding_delta = table_cell_padding_x(style, rem_size) - CELL_PAD_PX;
4226        // Lengths are rounded to device pixels for layout. Round the content
4227        // widths up, or a column can lose the fraction of a pixel that keeps
4228        // its text on one line.
4229        let scale_factor = window.scale_factor();
4230        let device_ceil = |width: f32| (width * scale_factor).ceil() / scale_factor;
4231        let columns: Vec<TableColumn> = col_w
4232            .iter()
4233            .enumerate()
4234            .map(|(ix, &w)| {
4235                let w = w + padding_delta;
4236                let floor = if scroll && nowrap {
4237                    w
4238                } else if scroll {
4239                    (w / CELL_WRAP_MAX_LINES)
4240                        .clamp(CELL_WRAP_MIN_PX, CELL_WRAP_MAX_PX)
4241                        .min(w)
4242                } else {
4243                    w.min(wrap_min_px)
4244                };
4245                let divider = if ix + 1 < col_count {
4246                    CELL_BORDER_PX
4247                } else {
4248                    0.
4249                };
4250                let max = device_ceil(w - divider);
4251                TableColumn {
4252                    min: device_ceil(floor - divider).min(max),
4253                    max,
4254                    divider,
4255                }
4256            })
4257            .collect();
4258
4259        let rows = Self::render_table_rows(table, &columns, node_cx, window, cx);
4260        let frame = StyleRefinement::default()
4261            .text_size(text_size)
4262            .bg(style
4263                .table_background()
4264                .unwrap_or(cx.theme().tokens.colors.surface))
4265            .border_1()
4266            .border_color(style.border())
4267            .refine_style(style.table());
4268        let body = if scroll {
4269            let scroll_handle = window
4270                .use_keyed_state(
4271                    block_element_id("table-scroll", table.span, options.ix),
4272                    cx,
4273                    |_, _| ScrollHandle::default(),
4274                )
4275                .read(cx)
4276                .clone();
4277            let min_total_w = columns
4278                .iter()
4279                .map(|column| column.min + column.divider)
4280                .sum::<f32>()
4281                + TABLE_BORDER_PX;
4282            // Scroll viewport owns the visible frame, including any
4283            // caller-provided radius. Keeping the border here makes the
4284            // rounded frame stable while the wider row track moves below it.
4285            //
4286            // `horizontal_scroll_area` clips with `overflow_hidden` and
4287            // delegates the wheel to a sibling `ScrollableMask`, so the
4288            // gesture is locked to its starting axis and a horizontal swipe
4289            // is consumed before an ancestor scroller (`gpui::list` under
4290            // `TextView::scrollable`) can take its vertical component.
4291            horizontal_scroll_area(
4292                block_element_id("table", table.span, options.ix),
4293                &scroll_handle,
4294                &frame,
4295                // Row track sized to `max(viewport, column floors)`:
4296                // `min_w_full` fills the frame while the columns can still
4297                // shrink-to-fit (their text wrapping), the definite
4298                // `w(min_total_w)` keeps the floors once they are reached,
4299                // letting the track exceed the viewport and scroll.
4300                div().min_w_full().w(px(min_total_w)).children(rows),
4301            )
4302            .into_any_element()
4303        } else {
4304            div()
4305                // Scopes the row ids to this table, as the scroll area's id
4306                // does, so rows of two tables never share hover state.
4307                .id(block_element_id("table", table.span, options.ix))
4308                .w_full()
4309                .overflow_hidden()
4310                .refine_style(&frame)
4311                .children(rows)
4312                .into_any_element()
4313        };
4314
4315        div()
4316            .pb(block_gap(options, style))
4317            .w_full()
4318            .child(body)
4319            // Custom actions row (e.g. copy / download) rendered below the
4320            // table. The hook's element spans full width; alignment is up to
4321            // the caller (e.g. `h_flex().justify_end()`). The gap keeps hover
4322            // backgrounds of the action buttons off the table border, and the
4323            // id scopes the caller's element ids per table, so plain ids like
4324            // `"copy"` don't collide across tables (same as code blocks).
4325            .children(node_cx.table_actions.clone().map(|f| {
4326                div()
4327                    .id(block_element_id("table-actions", table.span, options.ix))
4328                    .mt_1()
4329                    .child(f(&table.cached_table_data(), window, cx))
4330            }))
4331            .into_any_element()
4332    }
4333
4334    /// Corner radii for the first and last table rows, derived from the
4335    /// frame radius in `style.table()`.
4336    ///
4337    /// GPUI clips children with a rectangular content mask, so a square row
4338    /// background (e.g. the header fill) pokes out of a rounded table frame
4339    /// at the corners. Rounding the first row's top and the last row's
4340    /// bottom corners to the frame radius — inset by the frame's 1px border
4341    /// sitting between frame and rows — keeps the row fills inside the
4342    /// frame. (A horizontally scrolled track can still meet the viewport
4343    /// corner with a square edge mid-scroll; only a rounded content mask
4344    /// could clip that, and gpui masks are rectangular.)
4345    fn table_row_corner_radii(style: &TextViewStyle, window: &Window) -> [Option<Pixels>; 4] {
4346        let rem_size = window.rem_size();
4347        let inset = |radius: Option<gpui::AbsoluteLength>| {
4348            radius.map(|radius| (radius.to_pixels(rem_size) - px(1.)).max(px(0.)))
4349        };
4350        let radii = &style.table().corner_radii;
4351        [
4352            inset(radii.top_left),
4353            inset(radii.top_right),
4354            inset(radii.bottom_left),
4355            inset(radii.bottom_right),
4356        ]
4357    }
4358
4359    /// The table rows, each a flex row laid out on the same column grid.
4360    ///
4361    /// Every column is a cell plus slack beside it. A cell grows from zero up
4362    /// to its content width `max` and never below its floor `min`:
4363    /// flex layout grows all cells equally and freezes each one that reaches
4364    /// its content width, so the narrow columns fit their content and the
4365    /// widest ones share what is left. The slack grows only after every cell
4366    /// is frozen, so a frame wider than the content spreads the extra width
4367    /// in proportion to the columns, placed after, around or before the cell
4368    /// to follow the column alignment.
4369    ///
4370    /// A row with fewer cells than the table keeps empty cells in their
4371    /// place, so its columns line up with the other rows.
4372    fn render_table_rows(
4373        table: &Table,
4374        columns: &[TableColumn],
4375        node_cx: &NodeContext,
4376        window: &mut Window,
4377        cx: &mut App,
4378    ) -> Vec<AnyElement> {
4379        // The slack's share of the frame while any cell is still growing is
4380        // `SLACK_GROW / (cells * CELL_GROW)`, a negligible fraction of a
4381        // pixel. The slack factors still add up to `SLACK_GROW`: flex layout
4382        // hands out only that fraction of the free space when the factors
4383        // sum to less than one, and the slack must take all of it.
4384        const CELL_GROW: f32 = 1e6;
4385        const SLACK_GROW: f32 = 1.0;
4386
4387        let style = &node_cx.style;
4388        let col_count = columns.len();
4389        let total_w = columns.iter().map(|column| column.max).sum::<f32>().max(1.);
4390        // The slack is part of the column, so it carries the cell's fill and
4391        // the column divider in the cell's border color.
4392        let mut slack_style = StyleRefinement::default();
4393        slack_style.background = style.table_cell().background.clone();
4394        slack_style.border_color = style.table_cell().border_color;
4395        let slack = |grow: f32| {
4396            div()
4397                .flex_basis(px(0.))
4398                .flex_grow(grow)
4399                .flex_shrink(0.)
4400                .border_color(style.border())
4401                .refine_style(&slack_style)
4402        };
4403
4404        let row_count = table.children.len();
4405        let [top_left, top_right, bottom_left, bottom_right] =
4406            Self::table_row_corner_radii(style, window);
4407        let mut rows = Vec::with_capacity(row_count);
4408        let mut cell_ordinal = 0;
4409        for (row_ix, row) in table.children.iter().enumerate() {
4410            let mut cells = Vec::with_capacity(col_count * 2);
4411            for (ix, column) in columns.iter().enumerate() {
4412                let is_last_col = ix + 1 == col_count;
4413                let align = table.column_align(ix);
4414                let content = row.children.get(ix).map(|cell| {
4415                    let fade_key = table
4416                        .span
4417                        .map(|span| TextLeafKey::table_cell(span.start, cell_ordinal));
4418                    cell_ordinal += 1;
4419                    cell.children.render(fade_key, node_cx, window, cx)
4420                });
4421
4422                let grow = SLACK_GROW * column.max / total_w;
4423                let (lead, trail) = match align {
4424                    ColumnumnAlign::None | ColumnumnAlign::Left => (0., grow),
4425                    ColumnumnAlign::Center => (grow / 2., grow / 2.),
4426                    ColumnumnAlign::Right => (grow, 0.),
4427                };
4428                if lead > 0. {
4429                    cells.push(slack(lead).into_any_element());
4430                }
4431                cells.push(
4432                    TableCellElement(
4433                        div()
4434                            .flex_basis(px(0.))
4435                            .flex_grow(CELL_GROW)
4436                            .min_w(px(column.min))
4437                            .max_w(px(column.max))
4438                            .overflow_hidden()
4439                            // Align the content box, not its text: GPUI
4440                            // paints `text_align` with an offset that
4441                            // `TextLayout` hit-testing leaves out, so
4442                            // aligned text could not be selected where it
4443                            // shows.
4444                            .when(align == ColumnumnAlign::Center, |this| {
4445                                this.flex().flex_col().items_center()
4446                            })
4447                            .when(align == ColumnumnAlign::Right, |this| {
4448                                this.flex().flex_col().items_end()
4449                            })
4450                            .px_3()
4451                            .py(px(7.))
4452                            .refine_style(&style.table_cell())
4453                            .children(content)
4454                            .into_any_element(),
4455                    )
4456                    .into_any_element(),
4457                );
4458                if trail > 0. || !is_last_col {
4459                    cells.push(
4460                        slack(trail)
4461                            .when(!is_last_col, |this| this.border_r_1())
4462                            .into_any_element(),
4463                    );
4464                }
4465            }
4466            rows.push(
4467                div()
4468                    // GPUI keys hover state by element id, so each row needs
4469                    // its own for its hover highlight to follow the pointer.
4470                    .id(("row", row_ix))
4471                    .w_full()
4472                    .when(row_ix < row_count - 1, |this| this.border_b_1())
4473                    .border_color(style.border())
4474                    .flex()
4475                    .flex_row()
4476                    // The first row is the header, as everywhere else that
4477                    // reads a table (`table_data`, `to_markdown`). The
4478                    // refinement comes last so it can override the defaults.
4479                    .when(row_ix == 0, |this| {
4480                        this.bg(style.code_background())
4481                            .text_color(style.foreground())
4482                            .when_some(top_left, |this, radius| this.rounded_tl(radius))
4483                            .when_some(top_right, |this, radius| this.rounded_tr(radius))
4484                            .refine_style(&style.table_head())
4485                    })
4486                    .when(row_ix + 1 == row_count, |this| {
4487                        this.when_some(bottom_left, |this, radius| this.rounded_bl(radius))
4488                            .when_some(bottom_right, |this, radius| this.rounded_br(radius))
4489                    })
4490                    // Body rows only: the header keeps its own fill.
4491                    .when_some(
4492                        style.table_row_hover().filter(|_| row_ix > 0),
4493                        |this, color| this.hover(|this| this.bg(color)),
4494                    )
4495                    .children(cells)
4496                    .into_any_element(),
4497            );
4498        }
4499        rows
4500    }
4501
4502    pub(crate) fn render_block(
4503        &self,
4504        options: NodeRenderOptions,
4505        node_cx: &NodeContext,
4506        window: &mut Window,
4507        cx: &mut App,
4508    ) -> AnyElement {
4509        let mb = block_gap(&options, &node_cx.style);
4510
4511        match self {
4512            BlockNode::Root { children, .. } => div()
4513                .children(children.into_iter().enumerate().map(move |(ix, node)| {
4514                    // A nested root (an HTML block container) continues the
4515                    // flow around it: until it shows a block of its own, it
4516                    // stands where the container stands.
4517                    let (is_first, prev) = match flow_position(children, ix) {
4518                        (true, _) => (options.is_first, options.prev),
4519                        (false, prev) => (false, prev),
4520                    };
4521                    node.render_block(
4522                        NodeRenderOptions {
4523                            ix,
4524                            is_first,
4525                            prev,
4526                            is_last: options.is_last && ix + 1 == children.len(),
4527                            ..options
4528                        },
4529                        node_cx,
4530                        window,
4531                        cx,
4532                    )
4533                }))
4534                .into_any_element(),
4535            BlockNode::Paragraph(paragraph) => gapped(
4536                paragraph.render(
4537                    paragraph.span.map(|span| TextLeafKey::block(span.start)),
4538                    node_cx,
4539                    window,
4540                    cx,
4541                ),
4542                mb,
4543            ),
4544            BlockNode::Heading {
4545                level,
4546                children,
4547                span,
4548            } => {
4549                let (_, line_height, section_gap) = heading_metrics(*level);
4550                let refinement = node_cx.style.heading(*level);
4551                let text_size = heading_size(*level, node_cx, window);
4552                // The previous block already leaves a gap below itself, so
4553                // only the rest of the section gap is added here -- the two
4554                // collapse like CSS margins. A heading right after another one
4555                // belongs to the same section and stays close. Nested in a
4556                // list item, a heading sits flush with the item.
4557                let top = if options.is_first || options.depth > 0 {
4558                    px(0.)
4559                } else {
4560                    match options.prev {
4561                        PrevBlock::Heading(_) => text_size * 0.25,
4562                        PrevBlock::Rule => (text_size * section_gap
4563                            - rule_space(body_font_size(node_cx, window)))
4564                        .max(px(0.)),
4565                        PrevBlock::Other => (text_size * section_gap
4566                            - node_cx.style.paragraph_gap().to_pixels(window.rem_size()))
4567                        .max(px(0.)),
4568                    }
4569                };
4570                let bottom = if options.is_last {
4571                    px(0.)
4572                } else {
4573                    text_size * HEADING_BOTTOM_GAP
4574                };
4575
4576                div()
4577                    .pt(top)
4578                    .pb(bottom)
4579                    .whitespace_normal()
4580                    .text_size(text_size)
4581                    .line_height(relative(line_height))
4582                    .font_weight(FontWeight::SEMIBOLD)
4583                    .when(*level >= 6, |this| {
4584                        this.text_color(node_cx.style.muted_foreground())
4585                    })
4586                    .refine_style(&refinement)
4587                    .child(children.render(
4588                        span.map(|span| TextLeafKey::block(span.start)),
4589                        node_cx,
4590                        window,
4591                        cx,
4592                    ))
4593                    .into_any_element()
4594            }
4595            BlockNode::Blockquote { children, .. } => gapped(
4596                div()
4597                    .w_full()
4598                    .text_color(node_cx.style.muted_foreground())
4599                    .border_l_2()
4600                    .border_color(node_cx.style.border())
4601                    .pl(body_font_size(node_cx, window) * 0.9)
4602                    .refine_style(node_cx.style.blockquote_style())
4603                    // Nested tables measure while rendering, before this div applies its text style.
4604                    .children({
4605                        let children_len = children.len();
4606                        children.into_iter().enumerate().map(move |(index, c)| {
4607                            let is_last = index == children_len - 1;
4608                            let (is_first, prev) = flow_position(children, index);
4609                            window.with_text_style(
4610                                Some(node_cx.style.blockquote_style().text.clone()),
4611                                |window| {
4612                                    c.render_block(
4613                                        NodeRenderOptions {
4614                                            is_first,
4615                                            prev,
4616                                            ..options.is_last(is_last)
4617                                        },
4618                                        node_cx,
4619                                        window,
4620                                        cx,
4621                                    )
4622                                },
4623                            )
4624                        })
4625                    })
4626                    .into_any_element(),
4627                mb,
4628            ),
4629            BlockNode::Surface { name, children, .. } => {
4630                if children.iter().all(Self::draws_nothing) {
4631                    // Nothing to hold, as when a stream has only sent the marker.
4632                    return div().into_any_element();
4633                }
4634                // Unless the container sets its own width, it takes the row's,
4635                // as a blockquote does, so lists and tables in it wrap to the
4636                // view instead of measuring at their unwrapped width.
4637                let mut container = node_cx
4638                    .markdown_extensions
4639                    .render_block_surface(name, window, cx)
4640                    .unwrap_or_else(div)
4641                    .map(|mut this| {
4642                        let style = this.style();
4643                        let unset_width = style.size.width.is_none();
4644                        let unset_min_width = style.min_size.width.is_none();
4645                        this.when(unset_width, |this| this.w_full())
4646                            .when(unset_min_width, |this| this.min_w_0())
4647                    });
4648                // Nested tables measure while rendering, before the container
4649                // applies its text style.
4650                let text_style = container.style().text.clone();
4651                let blocks = window.with_text_style(Some(text_style), |window| {
4652                    children
4653                        .iter()
4654                        .enumerate()
4655                        .map(|(ix, child)| {
4656                            let (is_first, prev) = flow_position(children, ix);
4657                            child.render_block(
4658                                NodeRenderOptions {
4659                                    is_first,
4660                                    prev,
4661                                    ..options
4662                                        .is_last(children[ix + 1..].iter().all(Self::draws_nothing))
4663                                },
4664                                node_cx,
4665                                window,
4666                                cx,
4667                            )
4668                        })
4669                        .collect::<Vec<_>>()
4670                });
4671                gapped(container.children(blocks).into_any_element(), mb)
4672            }
4673            BlockNode::List {
4674                children,
4675                ordered,
4676                start,
4677                ..
4678            } => div()
4679                .w_full()
4680                .min_w_0()
4681                .pb(mb)
4682                .children({
4683                    let mut items = Vec::with_capacity(children.len());
4684                    let mut item_index = 0;
4685                    for (ix, item) in children.into_iter().enumerate() {
4686                        let is_item = item.is_list_item();
4687
4688                        items.push(Self::render_list_item(
4689                            item,
4690                            item_index,
4691                            NodeRenderOptions {
4692                                ix,
4693                                ordered: *ordered,
4694                                list_start: *start,
4695                                ..options
4696                            },
4697                            node_cx,
4698                            window,
4699                            cx,
4700                        ));
4701
4702                        if is_item {
4703                            item_index += 1;
4704                        }
4705                    }
4706                    items
4707                })
4708                .into_any_element(),
4709            BlockNode::CodeBlock(code_block) => code_block.render(&options, node_cx, window, cx),
4710            BlockNode::Custom { node, state } => {
4711                let inner = match node_cx.markdown_extensions.render_block(node, window, cx) {
4712                    Some(rendered) => rendered,
4713                    None => div().child(node.as_text().to_string()).into_any_element(),
4714                };
4715
4716                div()
4717                    .pb(mb)
4718                    .child(CustomBlockElement {
4719                        content: inner,
4720                        state: state.clone(),
4721                        reveal: node_cx.reveal_at(
4722                            node.span.map(|span| TextLeafKey::block(span.start)),
4723                            0,
4724                            1,
4725                        ),
4726                    })
4727                    .into_any_element()
4728            }
4729            BlockNode::Table { .. } => {
4730                // Tables are data and read a step denser than the body. The
4731                // columns are measured while rendering, so they are measured
4732                // at the same size the cells are laid out with; the actions
4733                // row below keeps the body size.
4734                let text_size = body_font_size(node_cx, window) * (14. / 15.);
4735                window.with_text_style(
4736                    Some(TextStyleRefinement {
4737                        font_size: Some(text_size.into()),
4738                        ..Default::default()
4739                    }),
4740                    |window| {
4741                        Self::render_table(self, &options, node_cx, text_size, window, cx)
4742                            .into_any_element()
4743                    },
4744                )
4745            }
4746            BlockNode::HorizontalRule { .. } => {
4747                // A section break: a hairline with more room around it than
4748                // a paragraph gap. The previous block's own gap counts toward
4749                // the space above, as with headings.
4750                let space = rule_space(body_font_size(node_cx, window));
4751                let top = if options.is_first || options.depth > 0 {
4752                    px(0.)
4753                } else {
4754                    let above = match options.prev {
4755                        PrevBlock::Rule => space,
4756                        PrevBlock::Heading(level) => {
4757                            heading_size(level, node_cx, window) * HEADING_BOTTOM_GAP
4758                        }
4759                        PrevBlock::Other => {
4760                            node_cx.style.paragraph_gap().to_pixels(window.rem_size())
4761                        }
4762                    };
4763                    (space - above).max(px(0.))
4764                };
4765                div()
4766                    .pt(top)
4767                    .when(!options.is_last, |this| this.pb(space))
4768                    .child(div().bg(node_cx.style.border()).h(px(1.)))
4769                    .into_any_element()
4770            }
4771            BlockNode::Break { .. } => div().into_any_element(),
4772            BlockNode::Unknown { .. } | BlockNode::Definition { .. } => div().into_any_element(),
4773            _ => {
4774                if cfg!(debug_assertions) {
4775                    tracing::warn!("unknown implementation: {:?}", self);
4776                }
4777
4778                div().into_any_element()
4779            }
4780        }
4781    }
4782}
4783
4784#[cfg(test)]
4785mod tests {
4786    use super::*;
4787
4788    #[test]
4789    fn paragraph_highlights_preserve_overlaps_and_utf8_boundaries() {
4790        let mut app = gpui::TestApp::new();
4791        let mut window = app.open_window(|_, _| gpui::Empty);
4792        window.update(|_, _, cx| {
4793            cx.set_global(crate::Theme::default());
4794            let context = NodeContext::default();
4795            let link = LinkMark {
4796                url: "https://example.com".into(),
4797                ..Default::default()
4798            };
4799            let paragraph = Paragraph {
4800                children: vec![
4801                    InlineNode::new("a中😀").marks(vec![
4802                        (0..8, TextMark::default().bold()),
4803                        (1..8, TextMark::default().italic()),
4804                        (4..8, TextMark::default().code()),
4805                    ]),
4806                    InlineNode::new("文b").marks(vec![
4807                        (0..4, TextMark::default().link(link.clone())),
4808                        (0..3, TextMark::default().bold()),
4809                    ]),
4810                ],
4811                ..Default::default()
4812            };
4813            let measured = paragraph.inline_highlights(&context, cx);
4814            let (text, highlights, links) = paragraph.plain_render(&context, cx);
4815            assert_eq!(text.as_ref(), "a中😀文b");
4816            assert_eq!(links, vec![(8..12, link)]);
4817            for spans in [&measured, &highlights] {
4818                assert_eq!(
4819                    spans
4820                        .iter()
4821                        .map(|(range, _)| range.clone())
4822                        .collect::<Vec<_>>(),
4823                    vec![0..1, 1..4, 4..8, 8..11, 11..12]
4824                );
4825                for ix in [1, 2] {
4826                    assert_eq!(spans[ix].1.style.font_weight, Some(FontWeight::BOLD));
4827                    assert_eq!(spans[ix].1.style.font_style, Some(FontStyle::Italic));
4828                }
4829                assert!(spans[2].1.code_style.is_some());
4830                assert_eq!(spans[2].1.font_size_scale, Some(0.875));
4831                assert_eq!(spans[3].1.style.font_weight, Some(FontWeight::BOLD));
4832                assert_eq!(spans[3].1.style.font_style, None);
4833                assert!(spans[3].1.code_style.is_none());
4834                assert_eq!(spans[4].1.style.font_weight, None);
4835            }
4836            assert!(highlights[3..].iter().all(|(_, highlight)| {
4837                highlight.style.color == Some(context.style.link())
4838                    && highlight.style.underline.is_some()
4839            }));
4840            let items = paragraph.inline_flow_items(None, &[], &[], &context, cx);
4841            let [
4842                InlineFlowItem::Text {
4843                    text: flow_text,
4844                    highlights: flow_highlights,
4845                    links: flow_links,
4846                    ..
4847                },
4848            ] = items.as_slice()
4849            else {
4850                panic!("one text item");
4851            };
4852            assert_eq!(flow_text, &text);
4853            assert_eq!(flow_highlights, &highlights);
4854            assert_eq!(flow_links, &links);
4855
4856            // Public callers can supply marks extending into the next node.
4857            let paragraph = Paragraph {
4858                children: vec![
4859                    InlineNode::new("a").marks(vec![(0..2, TextMark::default().bold())]),
4860                    InlineNode::new("bc").marks(vec![(0..2, TextMark::default().italic())]),
4861                ],
4862                ..Default::default()
4863            };
4864            let highlights = paragraph.inline_highlights(&context, cx);
4865            assert_eq!(
4866                highlights
4867                    .iter()
4868                    .map(|(range, _)| range.clone())
4869                    .collect::<Vec<_>>(),
4870                vec![0..1, 1..2, 2..3]
4871            );
4872            assert_eq!(highlights[1].1.style.font_weight, Some(FontWeight::BOLD));
4873            assert_eq!(highlights[1].1.style.font_style, Some(FontStyle::Italic));
4874            assert_eq!(highlights[2].1.style.font_weight, None);
4875        });
4876    }
4877
4878    #[test]
4879    fn paragraph_highlight_builders_merge_each_mark_once() {
4880        use super::super::inline::COMBINED_HIGHLIGHT_INPUTS;
4881
4882        let mut app = gpui::TestApp::new();
4883        let mut window = app.open_window(|_, _| gpui::Empty);
4884        window.update(|_, _, cx| {
4885            cx.set_global(crate::Theme::default());
4886            let context = NodeContext::default();
4887            let inputs = || COMBINED_HIGHLIGHT_INPUTS.with(|inputs| inputs.get());
4888            for node_count in [64, 128] {
4889                let paragraph = Paragraph {
4890                    children: (0..node_count)
4891                        .map(|_| {
4892                            InlineNode::new("a中😀").marks(vec![
4893                                (0..8, TextMark::default().bold()),
4894                                (1..8, TextMark::default().italic()),
4895                                (4..8, TextMark::default().code()),
4896                            ])
4897                        })
4898                        .collect(),
4899                    ..Default::default()
4900                };
4901                let before = inputs();
4902                paragraph.inline_highlights(&context, cx);
4903                assert_eq!(inputs() - before, 3 * node_count);
4904                let before = inputs();
4905                paragraph.plain_render(&context, cx);
4906                assert_eq!(inputs() - before, 3 * node_count);
4907                let before = inputs();
4908                paragraph.inline_flow_items(None, &[], &[], &context, cx);
4909                assert_eq!(inputs() - before, 3 * node_count);
4910            }
4911        });
4912    }
4913
4914    #[test]
4915    fn host_foregrounds_follow_the_render_context_without_entering_the_paragraph_cache() {
4916        let mut app = gpui::TestApp::new();
4917        let mut window = app.open_window(|_, _| gpui::Empty);
4918        window.update(|_, _, cx| {
4919            cx.set_global(crate::Theme::default());
4920            let link = LinkMark {
4921                url: "https://example.com".into(),
4922                ..Default::default()
4923            };
4924            let mut paragraph = Paragraph::default().with_leaf_key(7);
4925            paragraph.push(InlineNode::new("a中😀link").marks(vec![
4926                (0..12, TextMark::default().bold()),
4927                (1..12, TextMark::default().italic().link(link.clone())),
4928            ]));
4929            let original = paragraph.clone();
4930            let base = NodeContext::default();
4931            let (_, inherited, _) = paragraph.plain_render(&base, cx);
4932            let cached = paragraph.render_cache.0.lock().unwrap().clone().unwrap();
4933            for color in [gpui::red(), gpui::blue()] {
4934                let context = NodeContext {
4935                    foregrounds: Some(Arc::new(HashMap::from([(7, vec![(0..12, color)])]))),
4936                    ..base.clone()
4937                };
4938                let (text, highlights, links) = paragraph.plain_render(&context, cx);
4939                assert_eq!(text.as_ref(), "a中😀link");
4940                assert_eq!(links, vec![(1..12, link.clone())]);
4941                assert!(highlights.iter().all(|(_, h)| h.style.color == Some(color)));
4942                assert!(
4943                    highlights
4944                        .iter()
4945                        .all(|(_, h)| h.style.font_weight == Some(FontWeight::BOLD))
4946                );
4947                assert!(
4948                    highlights
4949                        .iter()
4950                        .filter(|(r, _)| r.start >= 1)
4951                        .all(|(_, h)| h.style.font_style == Some(FontStyle::Italic)
4952                            && h.style.underline.is_some())
4953                );
4954                assert!(Arc::ptr_eq(
4955                    &cached,
4956                    paragraph.render_cache.0.lock().unwrap().as_ref().unwrap()
4957                ));
4958            }
4959            // Clearing a context's ranges restores inherited mark/link colors,
4960            // even though the document and cached mark styles are unchanged.
4961            let context = NodeContext {
4962                foregrounds: Some(Arc::new(HashMap::from([(7, vec![])]))),
4963                ..base.clone()
4964            };
4965            assert_eq!(paragraph.plain_render(&context, cx).1, inherited);
4966            let invalid = NodeContext {
4967                foregrounds: Some(Arc::new(HashMap::from([(7, vec![(2..3, gpui::red())])]))),
4968                ..base.clone()
4969            };
4970            assert_eq!(paragraph.plain_render(&invalid, cx).1, inherited);
4971            let other_leaf = NodeContext {
4972                foregrounds: Some(Arc::new(HashMap::from([(8, vec![(0..12, gpui::red())])]))),
4973                ..base
4974            };
4975            assert_eq!(paragraph.plain_render(&other_leaf, cx).1, inherited);
4976            assert_eq!(paragraph, original);
4977        });
4978    }
4979
4980    #[test]
4981    fn host_foregrounds_override_mixed_links_and_preserve_atom_byte_coordinates() {
4982        let mut app = gpui::TestApp::new();
4983        let mut window = app.open_window(|_, _| gpui::Empty);
4984        window.update(|_, _, cx| {
4985            cx.set_global(crate::Theme::default());
4986            let link = LinkMark {
4987                url: "https://example.com".into(),
4988                ..Default::default()
4989            };
4990            let mut paragraph = Paragraph::default().with_leaf_key(7);
4991            paragraph.push(InlineNode::new("a中😀link").marks(vec![
4992                (0..12, TextMark::default().bold()),
4993                (1..12, TextMark::default().link(link.clone())),
4994                (4..8, TextMark::default().code()),
4995            ]));
4996            paragraph.push(
4997                InlineNode::custom(MarkdownNode::new("atom", ()).text("long fallback"))
4998                    .marks(vec![(0..13, TextMark::default().link(link.clone()))]),
4999            );
5000            paragraph.push(InlineNode::new("尾"));
5001            paragraph.push(InlineNode::image(ImageNode::default()));
5002            paragraph.push(InlineNode::new("z"));
5003            let context = NodeContext {
5004                foregrounds: Some(Arc::new(HashMap::from([(
5005                    7,
5006                    vec![
5007                        (0..22, gpui::red()),
5008                        (15..18, gpui::blue()),
5009                        (21..22, gpui::blue()),
5010                    ],
5011                )]))),
5012                ..Default::default()
5013            };
5014            let items = paragraph.inline_flow_items(None, &[], &[], &context, cx);
5015            assert_eq!(items.len(), 5);
5016            let InlineFlowItem::Text {
5017                text,
5018                highlights,
5019                links,
5020                ..
5021            } = &items[0]
5022            else {
5023                panic!("text");
5024            };
5025            assert_eq!(text.as_ref(), "a中😀link");
5026            assert_eq!(links, &vec![(1..12, link.clone())]);
5027            assert!(
5028                highlights
5029                    .iter()
5030                    .all(|(_, h)| h.style.color == Some(gpui::red()))
5031            );
5032            assert!(
5033                highlights
5034                    .iter()
5035                    .any(|(r, h)| r.start == 4 && h.code_style.is_some())
5036            );
5037            let InlineFlowItem::Object {
5038                style,
5039                link: actual_link,
5040                ..
5041            } = &items[1]
5042            else {
5043                panic!("object");
5044            };
5045            assert_eq!(style.color, Some(gpui::red()));
5046            assert_eq!(actual_link.as_ref(), Some(&link));
5047            assert!(style.underline.is_some());
5048            for ix in [2, 4] {
5049                let InlineFlowItem::Text { highlights, .. } = &items[ix] else {
5050                    panic!("trailing text");
5051                };
5052                assert!(
5053                    highlights
5054                        .iter()
5055                        .all(|(_, h)| h.style.color == Some(gpui::blue()))
5056                );
5057                assert!(!highlights.is_empty());
5058            }
5059        });
5060    }
5061
5062    #[test]
5063    fn block_plugin_selection_copies_both_formats_and_clears_synchronously() {
5064        let source = "$$\nx\n$$";
5065        let mut node = MarkdownNode::new("math", ()).text("x").markdown(source);
5066        node.set_span(Some(Span {
5067            start: 0,
5068            end: source.len(),
5069        }));
5070        let state = BlockState::default();
5071        let same_content = BlockNode::Custom {
5072            node: node.clone(),
5073            state: BlockState::default(),
5074        };
5075        let block = BlockNode::Custom {
5076            node,
5077            state: state.clone(),
5078        };
5079        let document = crate::text::document::ParsedDocument {
5080            source: source.into(),
5081            blocks: Arc::new(vec![block.clone()]),
5082        };
5083        assert!(!block.has_selection());
5084        state.set_selection(Some(BlockSelection::Full));
5085        // Runtime selection does not affect parsed content equality.
5086        assert_eq!(block, same_content);
5087        for blocks in [None, Some(0..=0)] {
5088            assert_eq!(
5089                document.selected_text(SelectionFormat::Plain, blocks.clone()),
5090                "x\n"
5091            );
5092            assert_eq!(
5093                document.selected_text(SelectionFormat::Source, blocks),
5094                source
5095            );
5096        }
5097        assert_eq!(document.selected_source_range(), Some(0..source.len()));
5098
5099        // A clone shares the retained state, including clearing before repaint.
5100        block.clear_selection();
5101        assert!(!document.blocks[0].has_selection());
5102        assert_eq!(
5103            document.selected_text(SelectionFormat::Plain, Some(0..=0)),
5104            ""
5105        );
5106        assert_eq!(document.selected_source_range(), None);
5107    }
5108
5109    #[test]
5110    fn block_plugin_empty_endpoint_suppresses_virtualized_copy_fallback() {
5111        let state = BlockState::default();
5112        let block = BlockNode::Custom {
5113            node: MarkdownNode::new("math", ())
5114                .text("formula")
5115                .markdown("$$formula$$"),
5116            state: state.clone(),
5117        };
5118        let after = CodeBlock::from_code("after", None::<SharedString>);
5119        after.set_selection(0..5);
5120        let document = crate::text::document::ParsedDocument {
5121            blocks: Arc::new(vec![block, BlockNode::CodeBlock(after)]),
5122            ..Default::default()
5123        };
5124        assert!(
5125            document
5126                .selected_text(SelectionFormat::Plain, Some(0..=1))
5127                .contains("formula")
5128        );
5129        state.set_selection(Some(BlockSelection::Empty));
5130        assert!(document.blocks[0].has_selection());
5131        for format in [SelectionFormat::Plain, SelectionFormat::Source] {
5132            let text = document.selected_text(format, Some(0..=1));
5133            assert!(text.contains("after"));
5134            assert!(!text.contains("formula"));
5135        }
5136    }
5137
5138    #[test]
5139    fn block_plugin_geometry_selects_whole_blocks_in_both_drag_directions() {
5140        let bounds = Bounds::new(gpui::point(px(10.), px(20.)), gpui::size(px(100.), px(40.)));
5141        let inside = bounds.center();
5142        let above = gpui::point(px(0.), px(0.));
5143        let below = gpui::point(px(0.), px(80.));
5144        for (start, end) in [(above, inside), (inside, below), (above, below)] {
5145            assert!(custom_block_is_selected(bounds, start, end));
5146            assert!(custom_block_is_selected(bounds, end, start));
5147        }
5148        assert!(!custom_block_is_selected(bounds, inside, inside));
5149        // Pointer travel during a click, and any drag that never leaves the
5150        // block, select nothing.
5151        for (start, end) in [
5152            (inside, inside + gpui::point(px(1.), px(0.))),
5153            (
5154                bounds.origin,
5155                bounds.bottom_right() - gpui::point(px(1.), px(1.)),
5156            ),
5157        ] {
5158            assert!(!custom_block_is_selected(bounds, start, end));
5159            assert!(!custom_block_is_selected(bounds, end, start));
5160        }
5161        assert!(!custom_block_is_selected(
5162            bounds,
5163            gpui::point(px(150.), px(30.)),
5164            gpui::point(px(160.), px(40.))
5165        ));
5166    }
5167
5168    #[test]
5169    fn selected_inline_objects_coalesce_surrounding_emphasis() {
5170        for (object_mark, expected) in [
5171            (TextMark::default().italic(), "*fore $x$ aft*"),
5172            (TextMark::default().italic().bold(), "*fore **$x$** aft*"),
5173        ] {
5174            let italic = TextMark::default().italic();
5175            let before = InlineNode::new("before ").marks(vec![(0..7, italic.clone())]);
5176            let formula =
5177                InlineNode::custom(MarkdownNode::new("math", ()).text("x").markdown("$x$"))
5178                    .marks(vec![(0..1, object_mark)]);
5179            let after = InlineNode::new(" after").marks(vec![(0..6, italic)]);
5180            {
5181                let mut state = formula.state.lock().unwrap();
5182                state.text = "before ".into();
5183                state.selection = Some((2..7).into());
5184            }
5185            *formula.custom_selection.lock().unwrap() = true;
5186            let paragraph = Paragraph {
5187                children: vec![before, formula, after],
5188                ..Default::default()
5189            };
5190            {
5191                let mut state = paragraph.state.lock().unwrap();
5192                state.text = " after".into();
5193                state.selection = Some((0..4).into());
5194            }
5195            assert_eq!(paragraph.selected_source(), expected);
5196        }
5197    }
5198
5199    #[test]
5200    fn consecutive_inline_objects_copy_atomically_without_neighboring_text() {
5201        let first =
5202            InlineNode::custom(MarkdownNode::new("math", ()).text("甲²").markdown("$甲^2$"));
5203        let second = InlineNode::custom(MarkdownNode::new("math", ()).text("b").markdown("$b$"));
5204        *first.custom_selection.lock().unwrap() = true;
5205        *second.custom_selection.lock().unwrap() = true;
5206        let paragraph = Paragraph {
5207            children: vec![first, second],
5208            ..Default::default()
5209        };
5210        assert_eq!(paragraph.selected_text(), "甲²b");
5211        assert_eq!(paragraph.selected_source(), "$甲^2$$b$");
5212        assert!(paragraph.has_selection());
5213        paragraph.clear_selection();
5214        assert_eq!(paragraph.selected_text(), "");
5215        assert_eq!(paragraph.selected_source(), "");
5216        assert!(!paragraph.has_selection());
5217    }
5218
5219    #[test]
5220    fn selected_inline_object_interleaves_runs_and_preserves_enclosing_mark() {
5221        let before = InlineNode::new("中文 ");
5222        let formula =
5223            InlineNode::custom(MarkdownNode::new("math", ()).text("x²").markdown("$x^2$"))
5224                .marks(vec![(0..3, TextMark::default().bold())]);
5225        let after = InlineNode::new(" English");
5226        {
5227            let mut preceding = formula.state.lock().unwrap();
5228            preceding.text = "中文 ".into();
5229            preceding.selection = Some((3..7).into());
5230        }
5231        *formula.custom_selection.lock().unwrap() = true;
5232        let paragraph = Paragraph {
5233            children: vec![before, formula, after],
5234            ..Default::default()
5235        };
5236        {
5237            let mut trailing = paragraph.state.lock().unwrap();
5238            trailing.text = " English".into();
5239            trailing.selection = Some((0..4).into());
5240        }
5241        assert_eq!(paragraph.selected_text(), "文 x² Eng");
5242        assert_eq!(paragraph.selected_source(), "文 **$x^2$** Eng");
5243    }
5244
5245    #[test]
5246    fn mark_sets_a_readable_text_color_with_its_background() {
5247        use gpui::{Empty, TestApp};
5248        let mut app = TestApp::new();
5249        let mut window = app.open_window(|_, _| Empty);
5250        window.update(|_, _, cx| {
5251            cx.set_global(crate::Theme::default());
5252            let node_cx = NodeContext::default();
5253
5254            // The default `<mark>` yellow needs dark text, whatever the theme's
5255            // text color is (light in a dark theme).
5256            let yellow: Hsla = gpui::rgb(0xfef08a).into();
5257            let style = mark_highlight(&TextMark::default().highlight(yellow), &node_cx, cx).style;
5258            assert_eq!(style.background_color, Some(yellow));
5259            assert_eq!(style.color, Some(gpui::black()));
5260
5261            // A dark custom highlight gets light text instead.
5262            let navy: Hsla = gpui::rgb(0x1e3a8a).into();
5263            let style = mark_highlight(&TextMark::default().highlight(navy), &node_cx, cx).style;
5264            assert_eq!(style.color, Some(gpui::white()));
5265
5266            // A translucent mark is composited with the theme surface before
5267            // choosing the text color. Fully transparent marks keep inherited ink.
5268            let translucent_black: Hsla = gpui::rgba(0x00000080).into();
5269            let translucent_white: Hsla = gpui::rgba(0xffffff4d).into();
5270            assert_eq!(
5271                mark_text_color(translucent_black, gpui::white()),
5272                gpui::black()
5273            );
5274            assert_eq!(
5275                mark_text_color(translucent_white, gpui::black()),
5276                gpui::white()
5277            );
5278            let transparent: Hsla = gpui::rgba(0x00000000).into();
5279            let style =
5280                mark_highlight(&TextMark::default().highlight(transparent), &node_cx, cx).style;
5281            assert_eq!(style.color, None);
5282
5283            // Text that is not marked keeps the inherited color.
5284            let style = mark_highlight(&TextMark::default().bold(), &node_cx, cx).style;
5285            assert_eq!(style.color, None);
5286        });
5287    }
5288
5289    #[test]
5290    fn translucent_mark_cache_tracks_theme_background() {
5291        use gpui::{Empty, TestApp};
5292        let mut app = TestApp::new();
5293        let mut window = app.open_window(|_, _| Empty);
5294        window.update(|_, _, cx| {
5295            cx.set_global(crate::Theme::default());
5296            let paragraph = Paragraph {
5297                children: vec![InlineNode::new("mark").marks(vec![(
5298                    0..4,
5299                    TextMark::default().highlight(gpui::rgba(0x00000033).into()),
5300                )])],
5301                ..Default::default()
5302            };
5303            let context = NodeContext::default();
5304            crate::Theme::global_mut(cx).tokens.colors.background = gpui::white();
5305            let (_, light, _) = paragraph.plain_render(&context, cx);
5306            assert_eq!(light[0].1.style.color, Some(gpui::black()));
5307            crate::Theme::global_mut(cx).tokens.colors.background = gpui::black();
5308            let (_, dark, _) = paragraph.plain_render(&context, cx);
5309            assert_eq!(dark[0].1.style.color, Some(gpui::white()));
5310        });
5311    }
5312
5313    #[test]
5314    fn link_hook_replaces_or_drops_links_and_the_cache_follows_it() {
5315        use gpui::{Empty, TestApp};
5316        let mut app = TestApp::new();
5317        let mut window = app.open_window(|_, _| Empty);
5318        window.update(|_, _, cx| {
5319            cx.set_global(crate::Theme::default());
5320            let link = |url: &str| {
5321                TextMark::default().link(LinkMark {
5322                    url: url.to_string().into(),
5323                    ..Default::default()
5324                })
5325            };
5326            let mut by_reference = TextMark::default();
5327            by_reference.link = Some(LinkMark {
5328                identifier: Some("ref".into()),
5329                ..Default::default()
5330            });
5331            // "live dead cited": three links, the last a reference link.
5332            let paragraph = Paragraph {
5333                children: vec![InlineNode::new("live dead cited").marks(vec![
5334                    (0..4, link("https://live.example")),
5335                    (5..9, link("app://dead")),
5336                    (10..15, by_reference.clone()),
5337                ])],
5338                ..Default::default()
5339            };
5340            let mut node_cx = NodeContext::default();
5341            node_cx.link_refs.insert(
5342                "ref".into(),
5343                LinkMark {
5344                    url: "https://cited.example".into(),
5345                    ..Default::default()
5346                },
5347            );
5348            let underlined = |highlights: &[(Range<usize>, InlineHighlight)], at: usize| {
5349                highlights.iter().any(|(range, highlight)| {
5350                    range.contains(&at) && highlight.style.underline.is_some()
5351                })
5352            };
5353
5354            let (_, highlights, links) = paragraph.plain_render(&node_cx, cx);
5355            assert_eq!(links.len(), 3, "without a hook every link is drawn");
5356            assert_eq!(links[2].1.url.as_ref(), "https://cited.example");
5357            assert!(underlined(&highlights, 5));
5358
5359            // The hook sees resolved URLs; it drops `app://` and rewrites the
5360            // reference link.
5361            let seen = Arc::new(Mutex::new(Vec::<String>::new()));
5362            let recorded = seen.clone();
5363            node_cx.link_hook = Some(Arc::new(move |link: &Link, _: &App| {
5364                recorded.lock().unwrap().push(link.url.to_string());
5365                if link.url.starts_with("app://") {
5366                    None
5367                } else if link.url.contains("cited") {
5368                    Some(link.clone().url("https://moved.example"))
5369                } else {
5370                    Some(link.clone())
5371                }
5372            }));
5373            let (_, highlights, links) = paragraph.plain_render(&node_cx, cx);
5374            let drawn: Vec<_> = links
5375                .iter()
5376                .map(|(range, link)| (range.clone(), link.url.to_string()))
5377                .collect();
5378            assert_eq!(
5379                drawn,
5380                [
5381                    (0..4, "https://live.example".to_string()),
5382                    (10..15, "https://moved.example".to_string()),
5383                ],
5384                "the cached render must follow the hook"
5385            );
5386            assert!(underlined(&highlights, 0) && underlined(&highlights, 10));
5387            assert!(!underlined(&highlights, 5), "a dropped link is plain text");
5388            assert!(
5389                seen.lock()
5390                    .unwrap()
5391                    .contains(&"https://cited.example".to_string())
5392            );
5393
5394            // Inline code sends the paragraph through the inline flow, which
5395            // must apply the hook too; so must a linked custom inline.
5396            let flow = Paragraph {
5397                children: vec![
5398                    InlineNode::new("dead").marks(vec![(0..4, link("app://dead"))]),
5399                    InlineNode::new("code").marks(vec![(0..4, TextMark::default().code())]),
5400                    InlineNode::custom(MarkdownNode::new("test", ()).text("x"))
5401                        .marks(vec![(0..1, link("app://dead"))]),
5402                    InlineNode::custom(MarkdownNode::new("test", ()).text("y"))
5403                        .marks(vec![(0..1, by_reference)]),
5404                ],
5405                ..Default::default()
5406            };
5407            let items = flow.inline_flow_items(None, &[], &[], &node_cx, cx);
5408            for item in &items {
5409                if let InlineFlowItem::Text { links, .. } = item {
5410                    assert!(links.is_empty(), "dropped link survived in the inline flow");
5411                }
5412            }
5413            let objects: Vec<_> = items
5414                .iter()
5415                .filter_map(|item| match item {
5416                    InlineFlowItem::Object { link, .. } => {
5417                        Some(link.as_ref().map(|l| l.url.to_string()))
5418                    }
5419                    _ => None,
5420                })
5421                .collect();
5422            assert_eq!(objects, [None, Some("https://moved.example".to_string())]);
5423        });
5424    }
5425
5426    #[test]
5427    fn custom_inline_inherits_marks_and_resolves_link_references() {
5428        use gpui::{Empty, TestApp};
5429        let mut app = TestApp::new();
5430        let mut window = app.open_window(|_, _| Empty);
5431        window.update(|_, _, cx| {
5432            cx.set_global(crate::Theme::default());
5433            let mut node_cx = NodeContext::default();
5434            let mut mark = TextMark::default().bold();
5435            mark.italic = true;
5436            mark.strikethrough = true;
5437            mark.link = Some(LinkMark {
5438                identifier: Some("ref".into()),
5439                ..Default::default()
5440            });
5441            node_cx.link_refs.insert(
5442                "ref".into(),
5443                LinkMark {
5444                    url: "https://example.com".into(),
5445                    ..Default::default()
5446                },
5447            );
5448            let paragraph = Paragraph {
5449                children: vec![
5450                    InlineNode::custom(MarkdownNode::new("test", ()).text("x"))
5451                        .marks(vec![(0..1, mark)]),
5452                ],
5453                ..Default::default()
5454            };
5455            let items = paragraph.inline_flow_items(None, &[], &[], &node_cx, cx);
5456            let InlineFlowItem::Object { style, link, .. } = &items[0] else {
5457                panic!()
5458            };
5459            assert_eq!(style.font_weight, Some(FontWeight::BOLD));
5460            assert_eq!(style.font_style, Some(FontStyle::Italic));
5461            assert!(style.strikethrough.is_some());
5462            assert_eq!(link.as_ref().unwrap().url.as_ref(), "https://example.com");
5463        });
5464    }
5465
5466    #[test]
5467    fn table_column_uses_prepared_inline_metrics_after_resource_update() {
5468        use crate::text::InlineElement;
5469        use crate::text::inline::test_draw::in_prepaint;
5470        use gpui::{Image, ImageFormat, TestApp};
5471        let mut app = TestApp::new();
5472        let width = Arc::new(std::sync::atomic::AtomicUsize::new(400));
5473        let render_width = width.clone();
5474        let mut node_cx = NodeContext::default();
5475        node_cx.markdown_extensions = Arc::new(MarkdownExtensions::default().plugin(
5476            crate::text::markdown_ext::TestInlinePlugin::new("test").render_with(
5477                move |_, _, _, _| {
5478                    Some(
5479                        InlineElement::new(
5480                            gpui::img(Arc::new(Image::from_bytes(
5481                                ImageFormat::Svg,
5482                                b"<svg/>".to_vec(),
5483                            )))
5484                            .w(px(
5485                                render_width.load(std::sync::atomic::Ordering::Relaxed) as f32
5486                            ))
5487                            .h(px(20.)),
5488                        )
5489                        .with_baseline(px(15.)),
5490                    )
5491                },
5492            ),
5493        ));
5494        let table = table_of(
5495            vec![
5496                vec![plain_cell("ordinary text")],
5497                vec![TableCell {
5498                    children: Paragraph {
5499                        children: vec![InlineNode::custom(MarkdownNode::new("test", ()).text("x"))],
5500                        ..Default::default()
5501                    },
5502                    width: None,
5503                }],
5504            ],
5505            vec![],
5506        );
5507        in_prepaint(&mut app, move |window, cx| {
5508            let mut cached = None;
5509            for expected in [400, 600, 10, 400] {
5510                width.store(expected, std::sync::atomic::Ordering::Relaxed);
5511                let measured = measure_table_columns(&table, 1, &node_cx, window, cx)[0];
5512                let current = cached_column_widths(&table);
5513                assert_eq!(
5514                    measured,
5515                    current.widths[0].max(expected as f32 + CELL_PAD_PX)
5516                );
5517                assert_eq!(current.custom_cells, vec![(1, 0)]);
5518                if let Some(cached) = cached.replace(current.clone()) {
5519                    assert!(Arc::ptr_eq(&cached, &current));
5520                }
5521            }
5522        });
5523    }
5524
5525    fn cached_column_widths(table: &Table) -> Arc<TableColumnWidths> {
5526        table.column_widths_cache.0.lock().unwrap().clone().unwrap()
5527    }
5528
5529    #[test]
5530    fn blockquote_typography_reaches_nested_table_measurement() {
5531        use crate::text::inline::test_draw::in_prepaint;
5532        use crate::text::inline::test_fonts::{BODY, MONO, WideMonoTextSystem};
5533        use gpui::TestApp;
5534
5535        let quote = BlockNode::Blockquote {
5536            children: vec![BlockNode::Table(table_of(
5537                vec![vec![plain_cell("0123456789")]],
5538                vec![],
5539            ))],
5540            span: None,
5541        };
5542        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
5543        in_prepaint(&mut app, move |window, cx| {
5544            cx.set_global(crate::Theme::default());
5545            window.with_text_style(
5546                Some(
5547                    StyleRefinement::default()
5548                        .font_family(BODY)
5549                        .text_size(px(15.))
5550                        .text,
5551                ),
5552                |window| {
5553                    for (refinement, expected_width) in [
5554                        (StyleRefinement::default(), 94.),
5555                        (
5556                            StyleRefinement::default()
5557                                .font_family(MONO)
5558                                .text_size(px(30.))
5559                                .font_weight(FontWeight::BOLD),
5560                            199.,
5561                        ),
5562                    ] {
5563                        let node_cx = NodeContext {
5564                            style: Arc::new(
5565                                TextViewStyle::default().with_blockquote_style(refinement),
5566                            ),
5567                            body_font_size: px(15.),
5568                            ..Default::default()
5569                        };
5570                        quote.render_block(NodeRenderOptions::default(), &node_cx, window, cx);
5571                        let BlockNode::Blockquote { children, .. } = &quote else {
5572                            unreachable!()
5573                        };
5574                        let BlockNode::Table(table) = &children[0] else {
5575                            unreachable!()
5576                        };
5577                        // Ten glyphs at the table's 14px size, plus 24px cell padding.
5578                        assert_eq!(cached_column_widths(table).widths, vec![expected_width]);
5579                    }
5580                },
5581            );
5582        });
5583    }
5584
5585    #[test]
5586    fn block_surface_typography_reaches_nested_table_measurement() {
5587        use crate::text::MarkdownExtensions;
5588        use crate::text::inline::test_draw::in_prepaint;
5589        use crate::text::inline::test_fonts::{BODY, MONO, WideMonoTextSystem};
5590        use gpui::TestApp;
5591
5592        let surface = BlockNode::Surface {
5593            name: "large".into(),
5594            children: vec![BlockNode::Table(table_of(
5595                vec![vec![plain_cell("0123456789")]],
5596                vec![],
5597            ))],
5598            span: None,
5599        };
5600        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
5601        in_prepaint(&mut app, move |window, cx| {
5602            cx.set_global(crate::Theme::default());
5603            window.with_text_style(
5604                Some(
5605                    StyleRefinement::default()
5606                        .font_family(BODY)
5607                        .text_size(px(15.))
5608                        .text,
5609                ),
5610                |window| {
5611                    let node_cx = NodeContext {
5612                        body_font_size: px(15.),
5613                        markdown_extensions: Arc::new(MarkdownExtensions::default().block_surface(
5614                            "large",
5615                            |_, _| {
5616                                div()
5617                                    .font_family(MONO)
5618                                    .text_size(px(30.))
5619                                    .font_weight(FontWeight::BOLD)
5620                            },
5621                        )),
5622                        ..Default::default()
5623                    };
5624                    surface.render_block(NodeRenderOptions::default(), &node_cx, window, cx);
5625                    let BlockNode::Surface { children, .. } = &surface else {
5626                        unreachable!()
5627                    };
5628                    let BlockNode::Table(table) = &children[0] else {
5629                        unreachable!()
5630                    };
5631                    // The same as a blockquote with this text style.
5632                    assert_eq!(cached_column_widths(table).widths, vec![199.]);
5633                },
5634            );
5635        });
5636    }
5637
5638    #[test]
5639    fn table_columns_cache_preserves_plain_widths_and_clones() {
5640        use crate::text::inline::test_draw::in_prepaint;
5641        use crate::text::inline::test_fonts::{BODY, WideMonoTextSystem, record_shaped_lines};
5642        use gpui::{Refineable as _, TestApp, TextStyle};
5643
5644        let long = "é界".repeat(2048);
5645        let table = table_of(
5646            vec![
5647                vec![plain_cell(&format!(" \t{long} \nshort\n ")), plain_cell("")],
5648                vec![plain_cell("short")],
5649                vec![],
5650                vec![plain_cell(""), plain_cell("a\nabcdefghijklmnop")],
5651            ],
5652            vec![],
5653        );
5654        let uncached = table.clone();
5655        let node_cx = NodeContext::default();
5656        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
5657        let (table, node_cx, cached) = in_prepaint(&mut app, move |window, cx| {
5658            window.set_rem_size(px(20.));
5659            let style = TextStyle {
5660                font_family: BODY.into(),
5661                font_size: rems(1.).into(),
5662                ..Default::default()
5663            };
5664            let cached =
5665                window.with_text_style(Some(style.subtract(&Default::default())), |window| {
5666                    let (widths, shaped) = record_shaped_lines(|| {
5667                        measure_table_columns(&table, 2, &node_cx, window, cx)
5668                    });
5669                    assert_eq!(widths, vec![40960. + CELL_PAD_PX + CELL_BORDER_PX, 184.]);
5670                    assert!(shaped.iter().any(|line| line == &long));
5671                    assert_eq!(
5672                        table, uncached,
5673                        "derived widths do not change table equality"
5674                    );
5675                    assert!(uncached.column_widths_cache.0.lock().unwrap().is_none());
5676
5677                    let cached = cached_column_widths(&table);
5678                    let cloned = table.clone();
5679                    for same in [&table, &cloned] {
5680                        let (again, shaped) = record_shaped_lines(|| {
5681                            measure_table_columns(same, 2, &node_cx, window, cx)
5682                        });
5683                        assert_eq!(again, widths);
5684                        assert!(shaped.is_empty());
5685                        assert!(Arc::ptr_eq(&cached, &cached_column_widths(same)));
5686                    }
5687
5688                    // A different column count changes which cells draw borders.
5689                    assert_eq!(
5690                        measure_table_columns(&cloned, 3, &node_cx, window, cx),
5691                        vec![widths[0], widths[1] + CELL_BORDER_PX, CELL_MIN_PX]
5692                    );
5693                    assert!(!Arc::ptr_eq(&cached, &cached_column_widths(&cloned)));
5694                    assert!(Arc::ptr_eq(&cached, &cached_column_widths(&table)));
5695                    assert!(
5696                        measure_table_columns(&Table::default(), 0, &node_cx, window, cx)
5697                            .is_empty()
5698                    );
5699                    cached
5700                });
5701            (table, node_cx, cached)
5702        });
5703        // A parsed table can be rendered in another window. Do not reuse a
5704        // pixel-width cache from a different window's text system.
5705        in_prepaint(&mut app, move |window, cx| {
5706            window.set_rem_size(cached.rem_size);
5707            window.with_text_style(
5708                Some(cached.text_styles.body.subtract(&Default::default())),
5709                |window| {
5710                    measure_table_columns(&table, 2, &node_cx, window, cx);
5711                    assert!(!Arc::ptr_eq(&cached, &cached_column_widths(&table)));
5712                },
5713            );
5714        });
5715    }
5716
5717    #[test]
5718    fn table_columns_cache_tracks_typography() {
5719        use crate::text::inline::test_draw::in_prepaint;
5720        use crate::text::inline::test_fonts::{BODY, MONO, WideMonoTextSystem};
5721        use gpui::{Refineable as _, TestApp, TextStyle};
5722
5723        let code = "0123456789";
5724        let mut paragraph = Paragraph::default();
5725        paragraph
5726            .push(InlineNode::new(code).marks(vec![(0..code.len(), TextMark::default().code())]));
5727        let table = table_of(
5728            vec![vec![
5729                plain_cell(code),
5730                TableCell {
5731                    children: paragraph,
5732                    width: None,
5733                },
5734            ]],
5735            vec![],
5736        );
5737        let base = TextStyle {
5738            font_family: BODY.into(),
5739            font_size: rems(1.).into(),
5740            ..Default::default()
5741        };
5742        let mut larger = base.clone();
5743        larger.font_size = rems(2.).into();
5744        let mut bold = base.clone();
5745        bold.font_weight = FontWeight::BOLD;
5746        let mut mono = base.clone();
5747        mono.font_family = MONO.into();
5748        let normal_code = HighlightStyle::default();
5749        let bold_code = HighlightStyle {
5750            font_weight: Some(FontWeight::BOLD),
5751            ..Default::default()
5752        };
5753        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
5754        in_prepaint(&mut app, move |window, cx| {
5755            let mut previous = None;
5756            for (style, rem_size, family, inline_code, expected) in [
5757                (base.clone(), 20., MONO, normal_code, [125., 207.]),
5758                (base.clone(), 30., MONO, normal_code, [175., 294.5]),
5759                (larger, 20., MONO, normal_code, [225., 382.]),
5760                (bold, 20., MONO, normal_code, [175., 250.75]),
5761                (mono, 20., MONO, normal_code, [225., 207.]),
5762                (base.clone(), 20., MONO, normal_code, [125., 207.]),
5763                (base.clone(), 20., BODY, normal_code, [125., 119.5]),
5764                (base.clone(), 20., MONO, normal_code, [125., 207.]),
5765                (base, 20., MONO, bold_code, [125., 250.75]),
5766            ] {
5767                let mut theme = crate::Theme::default();
5768                theme.tokens.typography.mono = family.into();
5769                cx.set_global(theme);
5770                window.set_rem_size(px(rem_size));
5771                let node_cx = NodeContext {
5772                    style: Arc::new(TextViewStyle::default().with_inline_code(inline_code)),
5773                    ..Default::default()
5774                };
5775                window.with_text_style(Some(style.subtract(&Default::default())), |window| {
5776                    let widths = measure_table_columns(&table, 2, &node_cx, window, cx);
5777                    for (width, expected) in widths.iter().zip(expected) {
5778                        assert!((width - expected).abs() < 0.01, "{width} != {expected}");
5779                    }
5780                    let cached = cached_column_widths(&table);
5781                    if let Some(previous) = previous.replace(cached.clone()) {
5782                        assert!(!Arc::ptr_eq(&previous, &cached));
5783                    }
5784                    assert_eq!(
5785                        measure_table_columns(&table, 2, &node_cx, window, cx),
5786                        widths
5787                    );
5788                    assert!(Arc::ptr_eq(&cached, &cached_column_widths(&table)));
5789                });
5790            }
5791        });
5792    }
5793
5794    #[test]
5795    fn table_columns_cache_is_rebuilt_for_reparsed_tables() {
5796        use crate::text::format::markdown;
5797        use crate::text::inline::test_draw::in_prepaint;
5798        use crate::text::inline::test_fonts::{BODY, WideMonoTextSystem};
5799        use gpui::{Refineable as _, TestApp, TextStyle};
5800
5801        let mut node_cx = NodeContext::default();
5802        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
5803        in_prepaint(&mut app, move |window, cx| {
5804            let style = TextStyle {
5805                font_family: BODY.into(),
5806                font_size: px(20.).into(),
5807                ..Default::default()
5808            };
5809            window.with_text_style(Some(style.subtract(&Default::default())), |window| {
5810                let mut previous = None;
5811                for (text, expected) in [("longer cell", 134.), ("x", CELL_MIN_PX)] {
5812                    let source = format!("| h |\n| - |\n| {text} |\n");
5813                    let document = markdown::parse(&source, &mut node_cx).unwrap();
5814                    let BlockNode::Table(table) = &document.blocks[0] else {
5815                        panic!("expected a parsed table");
5816                    };
5817                    assert!(table.column_widths_cache.0.lock().unwrap().is_none());
5818                    assert_eq!(
5819                        measure_table_columns(table, 1, &node_cx, window, cx),
5820                        vec![expected]
5821                    );
5822                    let cached = cached_column_widths(table);
5823                    if let Some(previous) = previous.replace(cached.clone()) {
5824                        assert!(!Arc::ptr_eq(&previous, &cached));
5825                    }
5826                    assert_eq!(document.source.as_ref(), source);
5827                }
5828            });
5829        });
5830    }
5831
5832    /// Table columns are sized from shaped text, so a column of inline code
5833    /// has to be measured in the code family. Measured in the body font, the
5834    /// wide-mono test font makes `col_w` come out at half the rendered width.
5835    #[test]
5836    fn table_column_of_inline_code_cells_fits_the_mono_width() {
5837        use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
5838        use gpui::{Empty, TestApp};
5839
5840        let code = "method_name()";
5841        let mut paragraph = Paragraph::default();
5842        paragraph
5843            .push(InlineNode::new(code).marks(vec![(0..code.len(), TextMark::default().code())]));
5844        let table = Table {
5845            children: vec![TableRow {
5846                children: vec![TableCell {
5847                    children: paragraph,
5848                    width: None,
5849                }],
5850            }],
5851            column_aligns: vec![],
5852            span: None,
5853            table_data_cache: TableDataCache::default(),
5854            column_widths_cache: TableColumnWidthsCache::default(),
5855        };
5856        let node_cx = NodeContext::default();
5857
5858        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
5859        let mut window = app.open_window(|_, _| Empty);
5860        let (col_w, font_size) = window.update(|_, window, cx| {
5861            let mut theme = crate::Theme::default();
5862            theme.tokens.typography.mono = MONO.into();
5863            cx.set_global(theme);
5864            let font_size = window.text_style().font_size.to_pixels(window.rem_size());
5865            (
5866                measure_table_columns(&table, 1, &node_cx, window, cx),
5867                font_size,
5868            )
5869        });
5870
5871        let mono_w = f32::from(WideMonoTextSystem::width_of(code, MONO, font_size * 0.875));
5872        assert!(
5873            (col_w[0]
5874                - (mono_w + CELL_PAD_PX + crate::text::inline_flow::INLINE_CODE_PADDING * 2.))
5875                .abs()
5876                < 0.01,
5877            "col_w {} must fit the mono width {} plus padding {}",
5878            col_w[0],
5879            mono_w,
5880            CELL_PAD_PX
5881        );
5882    }
5883
5884    /// A column must fit the images in its cells, as a browser's column fits
5885    /// its `<img>`: an image adds no text, so its cell is measured again
5886    /// outside the cache, where its explicit size counts. Measured at a
5887    /// fixed 100x50 so the test needs no image to load.
5888    #[test]
5889    fn table_column_of_an_image_cell_fits_the_image_width() {
5890        use crate::text::inline::test_draw::in_prepaint;
5891        use crate::text::inline::test_fonts::{BODY, WideMonoTextSystem};
5892        use gpui::{Refineable as _, TestApp, TextStyle};
5893
5894        let mut paragraph = Paragraph::default();
5895        paragraph.push(InlineNode::image(ImageNode {
5896            url: "https://example.com/photo.png".into(),
5897            width: Some(px(100.).into()),
5898            height: Some(px(50.).into()),
5899            ..Default::default()
5900        }));
5901        let table = Table {
5902            children: vec![TableRow {
5903                children: vec![TableCell {
5904                    children: paragraph,
5905                    width: None,
5906                }],
5907            }],
5908            column_aligns: vec![],
5909            span: None,
5910            table_data_cache: TableDataCache::default(),
5911            column_widths_cache: TableColumnWidthsCache::default(),
5912        };
5913        let node_cx = NodeContext::default();
5914
5915        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
5916        in_prepaint(&mut app, move |window, cx| {
5917            let style = TextStyle {
5918                font_family: BODY.into(),
5919                font_size: px(20.).into(),
5920                ..Default::default()
5921            };
5922            window.with_text_style(Some(style.subtract(&Default::default())), |window| {
5923                assert_eq!(
5924                    measure_table_columns(&table, 1, &node_cx, window, cx),
5925                    vec![100. + CELL_PAD_PX]
5926                );
5927            });
5928        });
5929    }
5930
5931    #[test]
5932    fn code_block_highlights_are_cached_by_highlighter_identity() {
5933        use std::sync::atomic::{AtomicUsize, Ordering};
5934
5935        let calls = Arc::new(AtomicUsize::new(0));
5936        let calls_for_highlighter = calls.clone();
5937        let highlighter: Arc<CodeBlockHighlighterFn> = Arc::new(move |_| {
5938            calls_for_highlighter.fetch_add(1, Ordering::Relaxed);
5939            Vec::new()
5940        });
5941        let block = CodeBlock::new("fn main() {}".into(), Some("rust".into()), None::<Span>);
5942
5943        block.highlighted_styles(&highlighter);
5944        block.highlighted_styles(&highlighter);
5945        assert_eq!(calls.load(Ordering::Relaxed), 1);
5946
5947        let replacement: Arc<CodeBlockHighlighterFn> = Arc::new(|_| Vec::new());
5948        block.highlighted_styles(&replacement);
5949        assert!(Arc::ptr_eq(
5950            &block
5951                .highlight_cache
5952                .lock()
5953                .unwrap()
5954                .as_ref()
5955                .unwrap()
5956                .highlighter,
5957            &replacement
5958        ));
5959    }
5960
5961    #[test]
5962    fn a_new_highlighter_replaces_styles_instead_of_reusing_the_cache() {
5963        // Swapping the highlighter is how a theme change reaches a code block:
5964        // the parsed document is untouched, so the styles must come from the
5965        // new highlighter rather than from the styles cached for the old one.
5966        let light: Arc<CodeBlockHighlighterFn> = Arc::new(|_| {
5967            vec![(
5968                0..2,
5969                HighlightStyle {
5970                    color: Some(gpui::rgb(0x0000ff).into()),
5971                    ..Default::default()
5972                },
5973            )]
5974        });
5975        let dark: Arc<CodeBlockHighlighterFn> = Arc::new(|_| {
5976            vec![(
5977                0..2,
5978                HighlightStyle {
5979                    color: Some(gpui::rgb(0xffff00).into()),
5980                    ..Default::default()
5981                },
5982            )]
5983        });
5984        let block = CodeBlock::from_code("42", Some("json"));
5985
5986        let light_styles = block.highlighted_styles(&light);
5987        let dark_styles = block.highlighted_styles(&dark);
5988
5989        assert_eq!(light_styles[0].1.color, Some(gpui::rgb(0x0000ff).into()));
5990        assert_eq!(dark_styles[0].1.color, Some(gpui::rgb(0xffff00).into()));
5991        assert_eq!(block.code(), "42", "the document must survive the swap");
5992    }
5993
5994    #[test]
5995    fn reconstruct_markdown_wraps_marked_runs() {
5996        // "bold" fully covered by a bold mark.
5997        let marks = vec![(0..4, TextMark::default().bold())];
5998        assert_eq!(reconstruct_markdown("bold", &marks, 0..4), "**bold**");
5999        // Partial selection inside the bold run still wraps the slice.
6000        assert_eq!(reconstruct_markdown("bold", &marks, 1..3), "**ol**");
6001    }
6002
6003    #[test]
6004    fn reconstruct_markdown_emits_unmarked_text_verbatim() {
6005        // "a b c": plain, code, plain across three runs concatenated.
6006        let text = "a b c";
6007        let marks = vec![(2..3, TextMark::default().code())];
6008        assert_eq!(reconstruct_markdown(text, &marks, 0..5), "a `b` c");
6009        // Selecting only the plain tail.
6010        assert_eq!(reconstruct_markdown(text, &marks, 3..5), " c");
6011    }
6012
6013    #[test]
6014    fn reconstruct_markdown_handles_code_italic_strike_link() {
6015        assert_eq!(
6016            reconstruct_markdown("x", &[(0..1, TextMark::default().code())], 0..1),
6017            "`x`"
6018        );
6019        assert_eq!(
6020            reconstruct_markdown("x", &[(0..1, TextMark::default().italic())], 0..1),
6021            "*x*"
6022        );
6023        assert_eq!(
6024            reconstruct_markdown("x", &[(0..1, TextMark::default().strikethrough())], 0..1),
6025            "~~x~~"
6026        );
6027        let link = TextMark::default().link(LinkMark {
6028            url: "https://example.com".into(),
6029            ..Default::default()
6030        });
6031        assert_eq!(
6032            reconstruct_markdown("x", &[(0..1, link)], 0..1),
6033            "[x](https://example.com)"
6034        );
6035    }
6036
6037    #[test]
6038    fn reconstruct_markdown_nested_bold_italic() {
6039        // A single run marked both bold and italic (as produced by `**_x_**`).
6040        let mark = TextMark::default().bold().italic();
6041        // Inner (italic) is applied first, then bold: `***x***`.
6042        assert_eq!(reconstruct_markdown("x", &[(0..1, mark)], 0..1), "***x***");
6043    }
6044
6045    /// Build a paragraph whose combined `state.text` is the concatenation of
6046    /// its children (mirroring `Paragraph::render`), then set the paragraph
6047    /// selection so `selected_source` can be exercised without a real paint.
6048    fn paragraph_with_children(children: Vec<InlineNode>) -> Paragraph {
6049        let combined: String = children.iter().map(|c| c.text.to_string()).collect();
6050        let paragraph = Paragraph {
6051            span: None,
6052            children,
6053            link_refs: HashMap::new(),
6054            state: Arc::new(Mutex::new(InlineState::default())),
6055            render_cache: ParagraphRenderCache::default(),
6056        };
6057        if let Ok(mut state) = paragraph.state.lock() {
6058            state.set_text(combined.into());
6059        }
6060        paragraph
6061    }
6062
6063    fn set_paragraph_selection(paragraph: &Paragraph, range: Range<usize>) {
6064        if let Ok(mut state) = paragraph.state.lock() {
6065            state.selection = Some(range.into());
6066        }
6067    }
6068
6069    #[test]
6070    fn paragraph_selected_source_maps_partial_selection_across_runs() {
6071        // "This has **bold** text." rendered as ["This has ", "bold", " text."].
6072        let children = vec![
6073            InlineNode::new("This has ").marks(vec![(0..9, TextMark::default())]),
6074            InlineNode::new("bold").marks(vec![(0..4, TextMark::default().bold())]),
6075            InlineNode::new(" text.").marks(vec![(0..6, TextMark::default())]),
6076        ];
6077        let paragraph = paragraph_with_children(children);
6078
6079        // Select the whole paragraph: "This has bold text." -> source with **.
6080        set_paragraph_selection(&paragraph, 0..(9 + 4 + 6));
6081        assert_eq!(paragraph.selected_source(), "This has **bold** text.");
6082
6083        // Select only across the boundary "has **bold** te".
6084        // Rendered offsets: "has " starts at 5, "bold" at 9..13, " te" 13..16.
6085        set_paragraph_selection(&paragraph, 5..16);
6086        assert_eq!(paragraph.selected_source(), "has **bold** te");
6087
6088        // Select entirely inside the bold run -> still wrapped.
6089        set_paragraph_selection(&paragraph, 10..12);
6090        assert_eq!(paragraph.selected_source(), "**ol**");
6091    }
6092
6093    #[test]
6094    fn paragraph_selected_source_matches_text_when_no_marks() {
6095        let children =
6096            vec![InlineNode::new("plain words").marks(vec![(0..11, TextMark::default())])];
6097        let paragraph = paragraph_with_children(children);
6098        set_paragraph_selection(&paragraph, 0..11);
6099        assert_eq!(paragraph.selected_source(), "plain words");
6100        assert_eq!(paragraph.selected_text(), "plain words");
6101    }
6102
6103    /// Copy `blocks` the way a view in [`SelectionFormat::SourceAcrossStyles`]
6104    /// does, with every block painted.
6105    fn copy_across_styles(blocks: Vec<BlockNode>) -> String {
6106        let document = crate::text::document::ParsedDocument {
6107            blocks: blocks.into(),
6108            ..Default::default()
6109        };
6110        document.selected_text(SelectionFormat::SourceAcrossStyles, None)
6111    }
6112
6113    #[test]
6114    fn source_across_styles_copies_plain_text_within_one_style() {
6115        // "This has **bold** text." rendered as ["This has ", "bold", " text."].
6116        let paragraph = || {
6117            paragraph_with_children(vec![
6118                InlineNode::new("This has ").marks(vec![(0..9, TextMark::default())]),
6119                InlineNode::new("bold").marks(vec![(0..4, TextMark::default().bold())]),
6120                InlineNode::new(" text.").marks(vec![(0..6, TextMark::default())]),
6121            ])
6122        };
6123        let copy = |range: Range<usize>| {
6124            let paragraph = paragraph();
6125            set_paragraph_selection(&paragraph, range);
6126            copy_across_styles(vec![BlockNode::Paragraph(paragraph)])
6127        };
6128
6129        // Inside the bold run, and up to both of its boundaries.
6130        assert_eq!(copy(10..12), "ol\n");
6131        assert_eq!(copy(9..13), "bold\n");
6132        // Inside the plain text before it, up to the boundary.
6133        assert_eq!(copy(0..9), "This has \n");
6134        // Across the boundary, the selection takes in two styles.
6135        assert_eq!(copy(5..16), "has **bold** te");
6136        assert_eq!(copy(8..10), " **b**");
6137    }
6138
6139    #[test]
6140    fn source_across_styles_drops_the_url_of_a_link_selected_alone() {
6141        let link = TextMark::default().link(LinkMark {
6142            url: "https://example.com".into(),
6143            ..Default::default()
6144        });
6145        let paragraph = paragraph_with_children(vec![
6146            InlineNode::new("see ").marks(vec![(0..4, TextMark::default())]),
6147            InlineNode::new("the docs").marks(vec![(0..8, link)]),
6148        ]);
6149
6150        set_paragraph_selection(&paragraph, 4..12);
6151        assert_eq!(
6152            copy_across_styles(vec![BlockNode::Paragraph(paragraph.clone())]),
6153            "the docs\n"
6154        );
6155
6156        set_paragraph_selection(&paragraph, 0..12);
6157        assert_eq!(
6158            copy_across_styles(vec![BlockNode::Paragraph(paragraph)]),
6159            "see [the docs](https://example.com)"
6160        );
6161    }
6162
6163    #[test]
6164    fn source_across_styles_drops_the_markup_of_a_single_block() {
6165        let heading = BlockNode::Heading {
6166            level: 2,
6167            children: selected_paragraph("Title"),
6168            span: None,
6169        };
6170        assert_eq!(copy_across_styles(vec![heading]), "Title\n");
6171
6172        let code = CodeBlock::from_code("let a = 1;\nlet b = 2;", Some("rust"));
6173        code.set_selection(0..10);
6174        assert_eq!(
6175            copy_across_styles(vec![BlockNode::CodeBlock(code)]),
6176            "let a = 1;\n"
6177        );
6178
6179        let item = |text: &str| BlockNode::ListItem {
6180            children: vec![BlockNode::Paragraph(selected_paragraph(text))],
6181            spread: false,
6182            checked: None,
6183            task_marker: None,
6184            span: None,
6185        };
6186        let unselected_item = BlockNode::ListItem {
6187            children: vec![BlockNode::Paragraph(paragraph_with_children(vec![
6188                InlineNode::new("two"),
6189            ]))],
6190            spread: false,
6191            checked: None,
6192            task_marker: None,
6193            span: None,
6194        };
6195        let list = BlockNode::List {
6196            ordered: false,
6197            start: None,
6198            span: None,
6199            children: vec![item("one"), unselected_item],
6200        };
6201        assert_eq!(copy_across_styles(vec![list]), "one\n");
6202    }
6203
6204    #[test]
6205    fn source_across_styles_keeps_the_source_across_blocks() {
6206        let item = |text: &str| BlockNode::ListItem {
6207            children: vec![BlockNode::Paragraph(selected_paragraph(text))],
6208            spread: false,
6209            checked: None,
6210            task_marker: None,
6211            span: None,
6212        };
6213        let list = BlockNode::List {
6214            ordered: false,
6215            start: None,
6216            span: None,
6217            children: vec![item("one"), item("two")],
6218        };
6219        assert_eq!(copy_across_styles(vec![list]), "- one\n- two");
6220
6221        assert_eq!(
6222            copy_across_styles(vec![
6223                BlockNode::Paragraph(selected_paragraph("start")),
6224                BlockNode::Paragraph(selected_paragraph("end")),
6225            ]),
6226            "start\n\nend"
6227        );
6228    }
6229
6230    #[test]
6231    fn source_across_styles_keeps_the_source_of_an_inline_object() {
6232        let formula = InlineNode::custom(MarkdownNode::new("math", ()).text("x").markdown("$x$"));
6233        *formula.custom_selection.lock().unwrap() = true;
6234        let paragraph = Paragraph {
6235            children: vec![formula],
6236            ..Default::default()
6237        };
6238        assert_eq!(
6239            copy_across_styles(vec![BlockNode::Paragraph(paragraph)]),
6240            "$x$"
6241        );
6242    }
6243
6244    fn selected_paragraph(text: &str) -> Paragraph {
6245        let len = text.len();
6246        let paragraph = paragraph_with_children(vec![
6247            InlineNode::new(text).marks(vec![(0..len, TextMark::default())]),
6248        ]);
6249        set_paragraph_selection(&paragraph, 0..len);
6250        paragraph
6251    }
6252
6253    #[test]
6254    fn heading_selected_source_prefixes_hashes() {
6255        let heading = BlockNode::Heading {
6256            level: 2,
6257            children: selected_paragraph("Title"),
6258            span: None,
6259        };
6260        assert_eq!(heading.selected_text(SelectionFormat::Source), "## Title\n");
6261        // Rendered text keeps no marker.
6262        assert_eq!(heading.selected_text(SelectionFormat::Plain), "Title\n");
6263    }
6264
6265    #[test]
6266    fn unordered_list_selected_source_prefixes_dash() {
6267        let list = BlockNode::List {
6268            ordered: false,
6269            start: None,
6270            span: None,
6271            children: vec![
6272                BlockNode::ListItem {
6273                    children: vec![BlockNode::Paragraph(selected_paragraph("one"))],
6274                    spread: false,
6275                    checked: None,
6276                    task_marker: None,
6277                    span: None,
6278                },
6279                BlockNode::ListItem {
6280                    children: vec![BlockNode::Paragraph(selected_paragraph("two"))],
6281                    spread: false,
6282                    checked: None,
6283                    task_marker: None,
6284                    span: None,
6285                },
6286            ],
6287        };
6288        assert_eq!(
6289            list.selected_text(SelectionFormat::Source),
6290            "- one\n- two\n"
6291        );
6292    }
6293
6294    #[test]
6295    fn ordered_list_selected_source_preserves_start() {
6296        let list = BlockNode::List {
6297            ordered: true,
6298            start: Some(3),
6299            span: None,
6300            children: vec![
6301                BlockNode::ListItem {
6302                    children: vec![BlockNode::Paragraph(selected_paragraph("three"))],
6303                    spread: false,
6304                    checked: None,
6305                    task_marker: None,
6306                    span: None,
6307                },
6308                BlockNode::ListItem {
6309                    children: vec![BlockNode::Paragraph(selected_paragraph("four"))],
6310                    spread: false,
6311                    checked: None,
6312                    task_marker: None,
6313                    span: None,
6314                },
6315            ],
6316        };
6317        assert_eq!(list.to_markdown(), "3. three\n4. four");
6318        assert_eq!(
6319            list.selected_text(SelectionFormat::Source),
6320            "3. three\n4. four\n"
6321        );
6322    }
6323
6324    #[test]
6325    fn ordered_list_selected_source_preserves_nested_starts_and_continuations() {
6326        let nested = BlockNode::List {
6327            ordered: true,
6328            start: Some(4),
6329            span: None,
6330            children: vec![
6331                BlockNode::ListItem {
6332                    children: vec![BlockNode::Paragraph(selected_paragraph("nested"))],
6333                    spread: false,
6334                    checked: None,
6335                    task_marker: None,
6336                    span: None,
6337                },
6338                BlockNode::ListItem {
6339                    children: vec![BlockNode::Paragraph(selected_paragraph("again"))],
6340                    spread: false,
6341                    checked: None,
6342                    task_marker: None,
6343                    span: None,
6344                },
6345            ],
6346        };
6347        let nested_list = BlockNode::List {
6348            ordered: true,
6349            start: Some(3),
6350            span: None,
6351            children: vec![
6352                BlockNode::ListItem {
6353                    children: vec![BlockNode::Paragraph(selected_paragraph("three")), nested],
6354                    spread: false,
6355                    checked: None,
6356                    task_marker: None,
6357                    span: None,
6358                },
6359                BlockNode::ListItem {
6360                    children: vec![BlockNode::Paragraph(selected_paragraph("four"))],
6361                    spread: false,
6362                    checked: None,
6363                    task_marker: None,
6364                    span: None,
6365                },
6366            ],
6367        };
6368        assert_eq!(
6369            nested_list.selected_text(SelectionFormat::Source),
6370            "3. three\n   4. nested\n   5. again\n4. four\n"
6371        );
6372
6373        let loose_list = BlockNode::List {
6374            ordered: true,
6375            start: Some(3),
6376            span: None,
6377            children: vec![
6378                BlockNode::ListItem {
6379                    children: vec![
6380                        BlockNode::Paragraph(selected_paragraph("loose")),
6381                        BlockNode::Paragraph(selected_paragraph("continuation")),
6382                    ],
6383                    spread: true,
6384                    checked: None,
6385                    task_marker: None,
6386                    span: None,
6387                },
6388                BlockNode::ListItem {
6389                    children: vec![BlockNode::Paragraph(selected_paragraph("four"))],
6390                    spread: false,
6391                    checked: None,
6392                    task_marker: None,
6393                    span: None,
6394                },
6395            ],
6396        };
6397        assert_eq!(
6398            loose_list.selected_text(SelectionFormat::Source),
6399            "3. loose\n   continuation\n4. four\n"
6400        );
6401    }
6402
6403    #[test]
6404    fn nested_list_selected_source_indents_sublists() {
6405        // - one
6406        //   - nested
6407        // - two
6408        let nested = BlockNode::List {
6409            ordered: false,
6410            start: None,
6411            span: None,
6412            children: vec![BlockNode::ListItem {
6413                children: vec![BlockNode::Paragraph(selected_paragraph("nested"))],
6414                spread: false,
6415                checked: None,
6416                task_marker: None,
6417                span: None,
6418            }],
6419        };
6420        let list = BlockNode::List {
6421            ordered: false,
6422            start: None,
6423            span: None,
6424            children: vec![
6425                BlockNode::ListItem {
6426                    children: vec![BlockNode::Paragraph(selected_paragraph("one")), nested],
6427                    spread: false,
6428                    checked: None,
6429                    task_marker: None,
6430                    span: None,
6431                },
6432                BlockNode::ListItem {
6433                    children: vec![BlockNode::Paragraph(selected_paragraph("two"))],
6434                    spread: false,
6435                    checked: None,
6436                    task_marker: None,
6437                    span: None,
6438                },
6439            ],
6440        };
6441        assert_eq!(
6442            list.selected_text(SelectionFormat::Source),
6443            "- one\n  - nested\n- two\n"
6444        );
6445    }
6446
6447    #[test]
6448    fn task_list_selected_source_restores_checkboxes() {
6449        let list = BlockNode::List {
6450            ordered: false,
6451            start: None,
6452            span: None,
6453            children: vec![
6454                BlockNode::ListItem {
6455                    children: vec![BlockNode::Paragraph(selected_paragraph("done"))],
6456                    spread: false,
6457                    checked: Some(true),
6458                    task_marker: None,
6459                    span: None,
6460                },
6461                BlockNode::ListItem {
6462                    children: vec![BlockNode::Paragraph(selected_paragraph("todo"))],
6463                    spread: false,
6464                    checked: Some(false),
6465                    task_marker: None,
6466                    span: None,
6467                },
6468            ],
6469        };
6470        assert_eq!(
6471            list.selected_text(SelectionFormat::Source),
6472            "- [x] done\n- [ ] todo\n"
6473        );
6474    }
6475
6476    #[test]
6477    fn blockquote_selected_source_prefixes_gt() {
6478        let quote = BlockNode::Blockquote {
6479            span: None,
6480            children: vec![BlockNode::Paragraph(selected_paragraph("quoted text"))],
6481        };
6482        assert_eq!(
6483            quote.selected_text(SelectionFormat::Source),
6484            "> quoted text\n"
6485        );
6486    }
6487
6488    #[test]
6489    fn table_selected_source_pipes_cells_with_alignment_row() {
6490        let cell = |text: &str| TableCell {
6491            children: selected_paragraph(text),
6492            width: None,
6493        };
6494        let table = Table {
6495            children: vec![
6496                TableRow {
6497                    children: vec![cell("Name"), cell("Age")],
6498                },
6499                TableRow {
6500                    children: vec![cell("Alice"), cell("30")],
6501                },
6502            ],
6503            column_aligns: vec![ColumnumnAlign::Left, ColumnumnAlign::Right],
6504            span: None,
6505            table_data_cache: TableDataCache::default(),
6506            column_widths_cache: TableColumnWidthsCache::default(),
6507        };
6508        let block = BlockNode::Table(table);
6509        assert_eq!(
6510            block.selected_text(SelectionFormat::Source),
6511            "| Name | Age |\n| :-- | --: |\n| Alice | 30 |\n"
6512        );
6513    }
6514
6515    /// A drag that starts in a table cell stays in it, so the copy is the
6516    /// cell's text alone: no pipes, no delimiter row, no other cells or rows.
6517    #[test]
6518    fn a_selection_in_one_table_cell_copies_only_that_cell() {
6519        let table = table_of(
6520            vec![
6521                vec![plain_cell("Name"), plain_cell("Age")],
6522                vec![
6523                    TableCell {
6524                        children: selected_paragraph("Alice"),
6525                        width: None,
6526                    },
6527                    plain_cell("30"),
6528                ],
6529            ],
6530            vec![ColumnumnAlign::Left, ColumnumnAlign::Right],
6531        );
6532        let block = BlockNode::Table(table);
6533        assert_eq!(block.selected_text(SelectionFormat::Plain).trim(), "Alice");
6534        assert_eq!(block.selected_text(SelectionFormat::Source), "Alice\n");
6535    }
6536
6537    /// A cell holding plain text, as `Table::to_markdown` and
6538    /// `Table::table_data` see it (neither needs a selection).
6539    fn plain_cell(text: &str) -> TableCell {
6540        TableCell {
6541            children: Paragraph::new(text.to_string()),
6542            width: None,
6543        }
6544    }
6545
6546    fn table_of(rows: Vec<Vec<TableCell>>, column_aligns: Vec<ColumnumnAlign>) -> Table {
6547        Table {
6548            children: rows
6549                .into_iter()
6550                .map(|children| TableRow { children })
6551                .collect(),
6552            column_aligns,
6553            span: None,
6554            table_data_cache: TableDataCache::default(),
6555            column_widths_cache: TableColumnWidthsCache::default(),
6556        }
6557    }
6558
6559    #[test]
6560    fn table_to_markdown_pipes_cells_with_alignment_row() {
6561        let table = table_of(
6562            vec![
6563                vec![plain_cell("Name"), plain_cell("Age"), plain_cell("Score")],
6564                vec![plain_cell("Alice"), plain_cell("30"), plain_cell("9.5")],
6565            ],
6566            vec![
6567                ColumnumnAlign::Left,
6568                ColumnumnAlign::Center,
6569                ColumnumnAlign::Right,
6570            ],
6571        );
6572
6573        assert_eq!(
6574            table.to_markdown(),
6575            "| Name | Age | Score |\n| :-- | :-: | --: |\n| Alice | 30 | 9.5 |"
6576        );
6577        // The block arm delegates to it.
6578        assert_eq!(
6579            BlockNode::Table(table.clone()).to_markdown(),
6580            table.to_markdown()
6581        );
6582    }
6583
6584    #[test]
6585    fn table_to_markdown_keeps_outer_pipes_for_a_single_column() {
6586        let table = table_of(
6587            vec![vec![plain_cell("Symbol")], vec![plain_cell("TSLA.US")]],
6588            vec![ColumnumnAlign::Left],
6589        );
6590
6591        assert_eq!(table.to_markdown(), "| Symbol |\n| :-- |\n| TSLA.US |");
6592    }
6593
6594    #[test]
6595    fn table_to_markdown_escapes_pipes_and_keeps_inline_marks() {
6596        let bold = TableCell {
6597            children: paragraph_with_children(vec![
6598                InlineNode::new("bold").marks(vec![(0..4, TextMark::default().bold())]),
6599            ]),
6600            width: None,
6601        };
6602        let table = table_of(
6603            vec![
6604                vec![plain_cell("a | b"), plain_cell("plain")],
6605                vec![plain_cell("c"), bold],
6606            ],
6607            vec![ColumnumnAlign::Left, ColumnumnAlign::Left],
6608        );
6609
6610        assert_eq!(
6611            table.to_markdown(),
6612            "| a \\| b | plain |\n| :-- | :-- |\n| c | **bold** |"
6613        );
6614    }
6615
6616    #[test]
6617    fn table_data_snapshots_plain_cells_and_markdown() {
6618        let mut table = table_of(
6619            vec![
6620                vec![plain_cell("  Name  "), plain_cell("Age")],
6621                vec![plain_cell("Alice"), plain_cell("30")],
6622            ],
6623            vec![ColumnumnAlign::Left, ColumnumnAlign::Right],
6624        );
6625        table.span = Some(Span { start: 4, end: 42 });
6626
6627        let data = table.table_data();
6628        assert_eq!(data.headers, vec!["Name", "Age"]);
6629        assert_eq!(data.rows, vec![vec!["Alice", "30"]]);
6630        assert_eq!(data.markdown, table.to_markdown());
6631        assert_eq!(data.span, Some(4..42));
6632    }
6633
6634    #[test]
6635    fn cloned_table_keeps_cached_table_data() {
6636        // Streaming appends deep-clone every block; the clone must reuse the
6637        // cached snapshot instead of rebuilding it.
6638        let table = table_of(
6639            vec![vec![plain_cell("Name")], vec![plain_cell("Alice")]],
6640            vec![ColumnumnAlign::Left],
6641        );
6642        let data = table.cached_table_data();
6643
6644        #[expect(
6645            clippy::redundant_clone,
6646            reason = "This test verifies that cloning a table shares its cached snapshot"
6647        )]
6648        let cloned = table.clone();
6649        assert!(Arc::ptr_eq(&data, &cloned.cached_table_data()));
6650    }
6651
6652    #[test]
6653    fn table_data_handles_tables_without_rows() {
6654        // Header only: still a valid table, with no data rows.
6655        let header_only = table_of(
6656            vec![vec![plain_cell("Name"), plain_cell("Age")]],
6657            vec![ColumnumnAlign::Left, ColumnumnAlign::Left],
6658        );
6659        let data = header_only.table_data();
6660        assert_eq!(data.headers, vec!["Name", "Age"]);
6661        assert!(data.rows.is_empty());
6662        assert_eq!(data.markdown, "| Name | Age |\n| :-- | :-- |");
6663
6664        // No rows at all (a table still streaming in): an empty snapshot.
6665        assert_eq!(Table::default().table_data(), TableData::default());
6666    }
6667
6668    #[test]
6669    fn test_image_node_source() {
6670        use gpui::{ImageFormat, ImageSource, Resource};
6671
6672        fn image_node(url: &str) -> ImageNode {
6673            ImageNode {
6674                url: url.into(),
6675                ..Default::default()
6676            }
6677        }
6678
6679        // Document-provided values stay URI-backed, including `file://` and
6680        // scheme-less strings, so the document never gets implicit
6681        // filesystem access through `Resource::Embedded`.
6682        fn assert_uri(url: &str) {
6683            match image_node(url).source() {
6684                ImageSource::Resource(Resource::Uri(uri)) => assert_eq!(uri.as_ref(), url),
6685                _ => panic!("expected Uri for {url:?}"),
6686            }
6687        }
6688        assert_uri("https://example.com/logo.png");
6689        assert_uri("http://example.com/logo.png");
6690        assert_uri("website/public/logo.svg");
6691        assert_uri("./images/a.png");
6692        assert_uri("../images/a.png");
6693        assert_uri("/absolute/path/logo.svg");
6694        assert_uri("file:///absolute/path/logo.svg");
6695        assert_uri(r"C:\images\logo.png");
6696        assert_uri("docs/a:b.png");
6697        assert_uri("data:text/plain;base64,aGVsbG8=");
6698
6699        // A `data:` image is decoded once and the same decoded image is
6700        // handed to every render.
6701        let node = image_node("data:image/png;base64,iVBORw0KGgo=");
6702        let ImageSource::Image(first) = node.source() else {
6703            panic!("expected an embedded image");
6704        };
6705        assert_eq!(first.format(), ImageFormat::Png);
6706        assert_eq!(first.bytes(), b"\x89PNG\r\n\x1a\n");
6707        let ImageSource::Image(second) = node.source() else {
6708            panic!("expected an embedded image");
6709        };
6710        assert!(Arc::ptr_eq(&first, &second));
6711    }
6712
6713    /// Images with nothing between them share a line, as a browser draws
6714    /// `<img>` inline; the plain image path stacked them one per row.
6715    #[test]
6716    fn a_paragraph_of_several_images_is_an_inline_flow() {
6717        use crate::text::format::markdown;
6718
6719        let mut node_cx = NodeContext::default();
6720        for (source, expected) in [
6721            ("![a](a.png)", false),
6722            ("![a](a.png)![b](b.png)", true),
6723            (
6724                "[![a](a.png)](https://a.com)[![b](b.png)](https://b.com)",
6725                true,
6726            ),
6727            ("![a](a.png) ![b](b.png)", true),
6728        ] {
6729            let document = markdown::parse(source, &mut node_cx).unwrap();
6730            let BlockNode::Paragraph(paragraph) = &document.blocks[0] else {
6731                panic!("expected a paragraph for {source}");
6732            };
6733            assert_eq!(paragraph.should_render_inline_flow(), expected, "{source}");
6734        }
6735    }
6736
6737    fn image_paragraph(alt: &str, url: &str) -> Paragraph {
6738        let image = ImageNode {
6739            url: url.into(),
6740            alt: Some(alt.into()),
6741            ..Default::default()
6742        };
6743        Paragraph {
6744            span: None,
6745            children: vec![InlineNode::image(image)],
6746            link_refs: HashMap::new(),
6747            state: Arc::new(Mutex::new(InlineState::default())),
6748            render_cache: ParagraphRenderCache::default(),
6749        }
6750    }
6751
6752    /// Every mark round-trips, including the two Markdown has no plain syntax
6753    /// for.
6754    #[test]
6755    fn marks_round_trip_through_reconstruction() {
6756        let wrap = |mark: TextMark| reconstruct_markdown("x", &[(0..1, mark)], 0..1);
6757
6758        assert_eq!(wrap(TextMark::default().bold()), "**x**");
6759        assert_eq!(wrap(TextMark::default().italic()), "*x*");
6760        assert_eq!(wrap(TextMark::default().code()), "`x`");
6761        assert_eq!(wrap(TextMark::default().strikethrough()), "~~x~~");
6762        assert_eq!(
6763            wrap(TextMark::default().highlight(gpui::rgb(0xfef08a).into())),
6764            "==x=="
6765        );
6766        // No Markdown syntax for underline, so it keeps the tag it came from.
6767        assert_eq!(wrap(TextMark::default().underline()), "<u>x</u>");
6768
6769        // A link keeps its title, which Markdown carries after the URL.
6770        assert_eq!(
6771            wrap(TextMark::default().link(LinkMark {
6772                url: "https://example.com".into(),
6773                title: Some("Tip".into()),
6774                ..Default::default()
6775            })),
6776            "[x](https://example.com \"Tip\")"
6777        );
6778    }
6779
6780    /// A block the selection covers whole comes straight from the source, so it
6781    /// keeps what the author wrote instead of a normalized reconstruction.
6782    #[test]
6783    fn document_selected_source_slices_covered_blocks_from_the_source() {
6784        use crate::text::document::ParsedDocument;
6785
6786        // `_italic_`, the `3.` start and the column padding all survive only
6787        // because the block is copied, not rebuilt.
6788        let source = "start\n\n3. _one_\n4. two\n\n---\n\nend";
6789        let list = "3. _one_\n4. two";
6790        let list_start = source.find(list).unwrap();
6791        let rule_start = source.find("---").unwrap();
6792
6793        let document = ParsedDocument {
6794            source: source.into(),
6795            blocks: vec![
6796                BlockNode::Paragraph(selected_paragraph("start")),
6797                BlockNode::List {
6798                    ordered: true,
6799                    start: Some(3),
6800                    children: vec![],
6801                    span: Some(Span {
6802                        start: list_start,
6803                        end: list_start + list.len(),
6804                    }),
6805                },
6806                BlockNode::HorizontalRule {
6807                    span: Some(Span {
6808                        start: rule_start,
6809                        end: rule_start + 3,
6810                    }),
6811                },
6812                BlockNode::Paragraph(selected_paragraph("end")),
6813            ]
6814            .into(),
6815        };
6816
6817        assert_eq!(
6818            document.selected_text(SelectionFormat::Source, None),
6819            "start\n\n3. _one_\n4. two\n\n---\n\nend"
6820        );
6821    }
6822
6823    #[test]
6824    fn document_selected_source_includes_enclosed_image() {
6825        use crate::text::document::ParsedDocument;
6826
6827        // A standalone image between two selected paragraphs is covered by the
6828        // selection, so it is copied whole even though it holds no selection of
6829        // its own — straight out of the source the parser located it in.
6830        let source = "before\n\n![alt](https://example.com/i.png)\n\nafter";
6831        let image_markdown = "![alt](https://example.com/i.png)";
6832        let start = source.find(image_markdown).unwrap();
6833        let mut image = image_paragraph("alt", "https://example.com/i.png");
6834        image.span = Some(Span {
6835            start,
6836            end: start + image_markdown.len(),
6837        });
6838
6839        let document = ParsedDocument {
6840            source: source.into(),
6841            blocks: vec![
6842                BlockNode::Paragraph(selected_paragraph("before")),
6843                BlockNode::Paragraph(image),
6844                BlockNode::Paragraph(selected_paragraph("after")),
6845            ]
6846            .into(),
6847        };
6848        assert_eq!(
6849            document.selected_text(SelectionFormat::Source, None),
6850            "before\n\n![alt](https://example.com/i.png)\n\nafter"
6851        );
6852    }
6853
6854    #[test]
6855    fn document_selected_source_drops_unenclosed_image() {
6856        use crate::text::document::ParsedDocument;
6857
6858        // An image after the only selected block, with nothing selected after
6859        // it, is not enclosed and is dropped.
6860        let document = ParsedDocument {
6861            source: String::new().into(),
6862            blocks: vec![
6863                BlockNode::Paragraph(selected_paragraph("before")),
6864                BlockNode::Paragraph(image_paragraph("alt", "u")),
6865            ]
6866            .into(),
6867        };
6868        assert_eq!(
6869            document.selected_text(SelectionFormat::Source, None),
6870            "before"
6871        );
6872    }
6873
6874    fn selected_code_block(code: &str, lang: Option<&str>) -> BlockNode {
6875        let block = CodeBlock::new(
6876            code.to_string().into(),
6877            lang.map(|l| l.to_string().into()),
6878            None::<Span>,
6879        );
6880        if let Ok(mut state) = block.state.lock() {
6881            let len = state.text.len();
6882            state.selection = Some((0..len).into());
6883        }
6884        BlockNode::CodeBlock(block)
6885    }
6886
6887    #[test]
6888    fn code_block_selected_source_wraps_in_fence_with_lang() {
6889        let block = selected_code_block("let x = 1;\n", Some("rust"));
6890        let code = block.selected_text(SelectionFormat::Plain);
6891        let code_trimmed = code.trim_end_matches('\n');
6892        // The source wraps the (trailing-newline-trimmed) selected code in a
6893        // fenced block carrying the language; the block arm adds one trailing
6894        // newline.
6895        assert_eq!(
6896            block.selected_text(SelectionFormat::Source),
6897            format!("```rust\n{}\n```\n", code_trimmed)
6898        );
6899        assert!(
6900            block
6901                .selected_text(SelectionFormat::Source)
6902                .starts_with("```rust\n")
6903        );
6904        assert!(
6905            block
6906                .selected_text(SelectionFormat::Source)
6907                .trim_end()
6908                .ends_with("\n```")
6909        );
6910    }
6911
6912    #[test]
6913    fn code_block_selected_source_without_lang() {
6914        let block = selected_code_block("plain\n", None);
6915        let code_trimmed = block.selected_text(SelectionFormat::Plain);
6916        let code_trimmed = code_trimmed.trim_end_matches('\n');
6917        assert_eq!(
6918            block.selected_text(SelectionFormat::Source),
6919            format!("```\n{}\n```\n", code_trimmed)
6920        );
6921    }
6922
6923    #[test]
6924    fn document_selected_source_joins_blocks_with_blank_line() {
6925        use crate::text::document::ParsedDocument;
6926
6927        // A heading, a paragraph, and a two-item ordered list, each fully
6928        // selected. Top-level blocks must be separated by a blank line so the
6929        // copied Markdown re-renders with the same structure.
6930        let document = ParsedDocument {
6931            source: String::new().into(),
6932            blocks: vec![
6933                BlockNode::Heading {
6934                    level: 1,
6935                    children: selected_paragraph("Title"),
6936                    span: None,
6937                },
6938                BlockNode::Paragraph(selected_paragraph("A paragraph.")),
6939                selected_code_block("let x = 1;\n", Some("rust")),
6940                BlockNode::List {
6941                    ordered: true,
6942                    start: Some(1),
6943                    span: None,
6944                    children: vec![
6945                        BlockNode::ListItem {
6946                            children: vec![BlockNode::Paragraph(selected_paragraph("one"))],
6947                            spread: false,
6948                            checked: None,
6949                            task_marker: None,
6950                            span: None,
6951                        },
6952                        BlockNode::ListItem {
6953                            children: vec![BlockNode::Paragraph(selected_paragraph("two"))],
6954                            spread: false,
6955                            checked: None,
6956                            task_marker: None,
6957                            span: None,
6958                        },
6959                    ],
6960                },
6961            ]
6962            .into(),
6963        };
6964
6965        assert_eq!(
6966            document.selected_text(SelectionFormat::Source, None),
6967            "# Title\n\nA paragraph.\n\n```rust\nlet x = 1;\n```\n\n1. one\n2. two"
6968        );
6969    }
6970
6971    #[test]
6972    fn code_block_equality_includes_code_content() {
6973        let first = CodeBlock::new("let value = 1;".into(), Some("rust".into()), None::<Span>);
6974        let second = CodeBlock::new("let value = 2;".into(), Some("rust".into()), None::<Span>);
6975
6976        assert_ne!(first, second);
6977    }
6978}