Skip to main content

wgpui_base/text/
node.rs

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