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