Skip to main content

gpui_component/text/
node.rs

1use std::{
2    cell::RefCell,
3    collections::HashMap,
4    ops::Range,
5    sync::{Arc, Mutex},
6};
7
8use gpui::{
9    AnyElement, App, DefiniteLength, Div, ElementId, FontStyle, FontWeight, Half, HighlightStyle,
10    Hsla, InteractiveElement as _, IntoElement, Length, ObjectFit, Overflow, ParentElement,
11    ScrollHandle, SharedString, SharedUri, StatefulInteractiveElement, Styled, StyledImage as _,
12    WhiteSpace, Window, div, img, prelude::FluentBuilder as _, px, relative, rems,
13};
14use markdown::mdast;
15use ropey::Rope;
16
17use crate::{
18    ActiveTheme as _, Icon, IconName, StyledExt, h_flex,
19    highlighter::{HighlightTheme, LanguageRegistry, SyntaxHighlighter},
20    input::{InputEdit, Point, RopeExt as _},
21    scroll::horizontal_scroll_area,
22    text::{
23        CodeBlockActionsFn, LinkClickHandlerFn, MarkdownExtensions, MarkdownNode, TableActionsFn,
24        document::NodeRenderOptions,
25        inline::{Inline, InlineState},
26        inline_flow::{InlineFlow, InlineFlowItem},
27        text_view::handle_link_click,
28    },
29    tooltip::Tooltip,
30    v_flex,
31};
32
33use super::{
34    SelectionFormat, TextViewStyle,
35    utils::{image_source, list_item_prefix},
36};
37
38thread_local! {
39    static CODE_BLOCK_HIGHLIGHTERS: RefCell<HashMap<SharedString, SyntaxHighlighter>> =
40        RefCell::new(HashMap::new());
41}
42
43/// The block-level nodes.
44#[derive(Debug, Clone, PartialEq)]
45pub(crate) enum BlockNode {
46    /// Something like a Div container in HTML.
47    Root {
48        children: Vec<BlockNode>,
49        span: Option<Span>,
50    },
51    Paragraph(Paragraph),
52    Heading {
53        level: u8,
54        children: Paragraph,
55        span: Option<Span>,
56    },
57    Blockquote {
58        children: Vec<BlockNode>,
59        span: Option<Span>,
60    },
61    List {
62        /// Only contains ListItem, others will be ignored
63        children: Vec<BlockNode>,
64        ordered: bool,
65        span: Option<Span>,
66    },
67    ListItem {
68        children: Vec<BlockNode>,
69        spread: bool,
70        /// Whether the list item is checked, if None, it's not a checkbox
71        checked: Option<bool>,
72        span: Option<Span>,
73    },
74    CodeBlock(CodeBlock),
75    /// A custom Markdown node produced by [`MarkdownExtensions`].
76    Custom(MarkdownNode),
77    Table(Table),
78    Break {
79        html: bool,
80        span: Option<Span>,
81    },
82    HorizontalRule {
83        span: Option<Span>,
84    },
85    /// Use for to_markdown get raw definition
86    Definition {
87        identifier: SharedString,
88        url: SharedString,
89        title: Option<SharedString>,
90        span: Option<Span>,
91    },
92    Unknown,
93}
94
95#[derive(Clone, Copy)]
96enum BlockTextKind {
97    All,
98    Selected,
99    /// Like `Selected`, but reconstructs Markdown source for the selection
100    /// instead of the rendered plain text.
101    SelectedSource,
102}
103
104impl BlockNode {
105    pub(super) fn is_list_item(&self) -> bool {
106        matches!(self, Self::ListItem { .. })
107    }
108
109    /// Combine all children, omitting the empt parent nodes.
110    pub(super) fn compact(self) -> BlockNode {
111        match self {
112            Self::Root { mut children, .. } if children.len() == 1 => children.remove(0).compact(),
113            _ => self,
114        }
115    }
116
117    /// Get the span of the node.
118    pub(crate) fn span(&self) -> Option<Span> {
119        match self {
120            BlockNode::Root { span, .. } => *span,
121            BlockNode::Paragraph(paragraph) => paragraph.span,
122            BlockNode::Heading { span, .. } => *span,
123            BlockNode::Blockquote { span, .. } => *span,
124            BlockNode::List { span, .. } => *span,
125            BlockNode::ListItem { span, .. } => *span,
126            BlockNode::CodeBlock(code_block) => code_block.span,
127            BlockNode::Custom(el) => el.span,
128            BlockNode::Table(table) => table.span,
129            BlockNode::Break { span, .. } => *span,
130            BlockNode::HorizontalRule { span, .. } => *span,
131            BlockNode::Definition { span, .. } => *span,
132            BlockNode::Unknown { .. } => None,
133        }
134    }
135
136    pub(super) fn text(&self) -> String {
137        self.text_by_kind(BlockTextKind::All)
138    }
139
140    /// The selected text within this block, in `format`.
141    ///
142    /// [`SelectionFormat::Source`] reconstructs the Markdown source of the
143    /// selection instead of the rendered text.
144    pub(super) fn selected_text(&self, format: SelectionFormat) -> String {
145        self.text_by_kind(match format {
146            SelectionFormat::Plain => BlockTextKind::Selected,
147            SelectionFormat::Source => BlockTextKind::SelectedSource,
148        })
149    }
150
151    fn text_by_kind(&self, kind: BlockTextKind) -> String {
152        let mut text = String::new();
153        match self {
154            BlockNode::Root { children, .. } => {
155                let block_text = Self::children_text(children, kind);
156                if !block_text.is_empty() {
157                    text.push_str(&block_text);
158                    text.push('\n');
159                }
160            }
161            BlockNode::Paragraph(paragraph) => {
162                let block_text = match kind {
163                    BlockTextKind::All => paragraph.text(),
164                    BlockTextKind::Selected => paragraph.selected_text(),
165                    BlockTextKind::SelectedSource => paragraph.selected_source(),
166                };
167                if !block_text.is_empty() {
168                    text.push_str(&block_text);
169                    text.push('\n');
170                }
171            }
172            BlockNode::Heading {
173                level, children, ..
174            } => {
175                let block_text = match kind {
176                    BlockTextKind::All => children.text(),
177                    BlockTextKind::Selected => children.selected_text(),
178                    BlockTextKind::SelectedSource => children.selected_source(),
179                };
180                if !block_text.is_empty() {
181                    // In source mode, prefix the heading marker so a selected
182                    // heading round-trips as Markdown (e.g. `## Title`).
183                    if matches!(kind, BlockTextKind::SelectedSource) {
184                        text.push_str(&"#".repeat(*level as usize));
185                        text.push(' ');
186                    }
187                    text.push_str(&block_text);
188                    text.push('\n');
189                }
190            }
191            BlockNode::List {
192                children, ordered, ..
193            } => {
194                if matches!(kind, BlockTextKind::SelectedSource) {
195                    // Reconstruct the list source, indenting nested lists and
196                    // restoring list markers and task-list checkboxes.
197                    text.push_str(&list_selected_source(children, *ordered, ""));
198                } else {
199                    text.push_str(&Self::children_text(children, kind));
200                }
201            }
202            BlockNode::ListItem { children, .. } => {
203                text.push_str(&Self::children_text(children, kind));
204            }
205            BlockNode::Blockquote { children, .. } => {
206                let block_text = Self::children_text(children, kind);
207
208                if !block_text.is_empty() {
209                    if matches!(kind, BlockTextKind::SelectedSource) {
210                        // Prefix every line with `> ` so a selected blockquote
211                        // round-trips as Markdown.
212                        let quoted = block_text
213                            .trim_end_matches('\n')
214                            .lines()
215                            .map(|line| {
216                                if line.is_empty() {
217                                    ">".to_string()
218                                } else {
219                                    format!("> {}", line)
220                                }
221                            })
222                            .collect::<Vec<_>>()
223                            .join("\n");
224                        text.push_str(&quoted);
225                    } else {
226                        text.push_str(&block_text);
227                    }
228                    text.push('\n');
229                }
230            }
231            BlockNode::Table(table) => {
232                if matches!(kind, BlockTextKind::SelectedSource) {
233                    let block_text = table_selected_source(table);
234                    if !block_text.is_empty() {
235                        text.push_str(&block_text);
236                        text.push('\n');
237                    }
238                } else {
239                    let mut block_text = String::new();
240                    for row in table.children.iter() {
241                        let mut row_texts = vec![];
242                        for cell in row.children.iter() {
243                            row_texts.push(match kind {
244                                BlockTextKind::All => cell.children.text(),
245                                // Source is handled above; only Selected reaches here.
246                                _ => cell.children.selected_text(),
247                            });
248                        }
249                        if !row_texts.is_empty() {
250                            block_text.push_str(&row_texts.join(" "));
251                            block_text.push('\n');
252                        }
253                    }
254
255                    if !block_text.is_empty() {
256                        text.push_str(&block_text);
257                        text.push('\n');
258                    }
259                }
260            }
261            BlockNode::CodeBlock(code_block) => {
262                let block_text = match kind {
263                    BlockTextKind::All => code_block.text(),
264                    BlockTextKind::Selected => code_block.selected_text(),
265                    BlockTextKind::SelectedSource => code_block.selected_source(),
266                };
267                if !block_text.is_empty() {
268                    text.push_str(&block_text);
269                    text.push('\n');
270                }
271            }
272            BlockNode::Custom(node) => {
273                if let BlockTextKind::All = kind {
274                    let content = node.as_text();
275                    if !content.is_empty() {
276                        text.push_str(content);
277                        text.push('\n');
278                    }
279                }
280            }
281            BlockNode::Definition { .. }
282            | BlockNode::Break { .. }
283            | BlockNode::HorizontalRule { .. }
284            | BlockNode::Unknown { .. } => {}
285        }
286
287        text
288    }
289
290    fn children_text(children: &[BlockNode], kind: BlockTextKind) -> String {
291        let mut text = String::new();
292        for child in children.iter() {
293            text.push_str(&child.text_by_kind(kind));
294        }
295
296        text
297    }
298
299    /// Synchronously clear the selection stored in every inline state.
300    ///
301    /// Mirrors the [`selected_text`](Self::selected_text) traversal so the
302    /// selection can be cleared without relying on a repaint.
303    /// Whether this block carries a selection, even an empty one.
304    ///
305    /// A block only learns its selection when it is painted, so this doubles as
306    /// "this block was on screen while the selection was made". An empty
307    /// selection is the caret left by the press that started the drag, which is
308    /// why it counts (see [`ParsedDocument::selected_text`]).
309    pub(super) fn has_selection(&self) -> bool {
310        match self {
311            BlockNode::Root { children, .. }
312            | BlockNode::Blockquote { children, .. }
313            | BlockNode::List { children, .. }
314            | BlockNode::ListItem { children, .. } => {
315                children.iter().any(|child| child.has_selection())
316            }
317            BlockNode::Paragraph(paragraph) => paragraph.has_selection(),
318            BlockNode::Heading { children, .. } => children.has_selection(),
319            BlockNode::Table(table) => table.children.iter().any(|row| {
320                row.children
321                    .iter()
322                    .any(|cell| cell.children.has_selection())
323            }),
324            BlockNode::CodeBlock(code_block) => code_block.has_selection(),
325            BlockNode::Custom { .. }
326            | BlockNode::Definition { .. }
327            | BlockNode::Break { .. }
328            | BlockNode::HorizontalRule { .. }
329            | BlockNode::Unknown { .. } => false,
330        }
331    }
332
333    pub(super) fn clear_selection(&self) {
334        match self {
335            BlockNode::Root { children, .. }
336            | BlockNode::Blockquote { children, .. }
337            | BlockNode::List { children, .. }
338            | BlockNode::ListItem { children, .. } => {
339                for child in children.iter() {
340                    child.clear_selection();
341                }
342            }
343            BlockNode::Paragraph(paragraph) => paragraph.clear_selection(),
344            BlockNode::Heading { children, .. } => children.clear_selection(),
345            BlockNode::Table(table) => {
346                for row in table.children.iter() {
347                    for cell in row.children.iter() {
348                        cell.children.clear_selection();
349                    }
350                }
351            }
352            BlockNode::CodeBlock(code_block) => code_block.clear_selection(),
353            BlockNode::Custom { .. }
354            | BlockNode::Definition { .. }
355            | BlockNode::Break { .. }
356            | BlockNode::HorizontalRule { .. }
357            | BlockNode::Unknown { .. } => {}
358        }
359    }
360}
361
362#[allow(unused)]
363#[derive(Debug, Default, Clone, PartialEq)]
364pub struct LinkMark {
365    pub url: SharedString,
366    /// Optional identifier for footnotes.
367    pub identifier: Option<SharedString>,
368    pub title: Option<SharedString>,
369}
370
371#[derive(Debug, Default, Clone, PartialEq)]
372pub struct TextMark {
373    pub bold: bool,
374    pub italic: bool,
375    pub strikethrough: bool,
376    pub underline: bool,
377    pub code: bool,
378    /// Highlight (`<mark>`) the text with this background color.
379    ///
380    /// `None` means the text is not highlighted.
381    pub highlight: Option<Hsla>,
382    pub link: Option<LinkMark>,
383}
384
385impl TextMark {
386    pub fn bold(mut self) -> Self {
387        self.bold = true;
388        self
389    }
390
391    pub fn italic(mut self) -> Self {
392        self.italic = true;
393        self
394    }
395
396    pub fn strikethrough(mut self) -> Self {
397        self.strikethrough = true;
398        self
399    }
400
401    pub fn underline(mut self) -> Self {
402        self.underline = true;
403        self
404    }
405
406    pub fn code(mut self) -> Self {
407        self.code = true;
408        self
409    }
410
411    /// Mark the text as highlighted (`<mark>`) with the given background color.
412    pub fn highlight(mut self, color: Hsla) -> Self {
413        self.highlight = Some(color);
414        self
415    }
416
417    pub fn link(mut self, link: impl Into<LinkMark>) -> Self {
418        self.link = Some(link.into());
419        self
420    }
421
422    pub fn merge(&mut self, other: TextMark) {
423        self.bold |= other.bold;
424        self.italic |= other.italic;
425        self.strikethrough |= other.strikethrough;
426        self.underline |= other.underline;
427        self.code |= other.code;
428        if other.highlight.is_some() {
429            self.highlight = other.highlight;
430        }
431        if let Some(link) = other.link {
432            self.link = Some(link);
433        }
434    }
435}
436
437/// The bytes
438#[derive(Debug, Default, Copy, Clone, PartialEq)]
439pub struct Span {
440    pub start: usize,
441    pub end: usize,
442}
443
444impl From<Span> for ElementId {
445    fn from(value: Span) -> Self {
446        ElementId::Name(format!("md-{}:{}", value.start, value.end).into())
447    }
448}
449
450#[allow(unused)]
451#[derive(Debug, Default, Clone)]
452pub struct ImageNode {
453    pub url: SharedUri,
454    pub link: Option<LinkMark>,
455    pub title: Option<SharedString>,
456    pub alt: Option<SharedString>,
457    pub width: Option<DefiniteLength>,
458    pub height: Option<DefiniteLength>,
459}
460
461impl ImageNode {
462    pub fn title(&self) -> String {
463        self.title
464            .clone()
465            .unwrap_or_else(|| self.alt.clone().unwrap_or_default())
466            .to_string()
467    }
468}
469
470impl PartialEq for ImageNode {
471    fn eq(&self, other: &Self) -> bool {
472        self.url == other.url
473            && self.link == other.link
474            && self.title == other.title
475            && self.alt == other.alt
476            && self.width == other.width
477            && self.height == other.height
478    }
479}
480
481#[derive(Default, Clone, Debug)]
482pub(crate) struct InlineNode {
483    /// The text content.
484    pub(crate) text: SharedString,
485    pub(crate) image: Option<ImageNode>,
486    /// The text styles, each tuple contains the range of the text and the style.
487    pub(crate) marks: Vec<(Range<usize>, TextMark)>,
488
489    state: Arc<Mutex<InlineState>>,
490}
491
492impl PartialEq for InlineNode {
493    fn eq(&self, other: &Self) -> bool {
494        self.text == other.text && self.image == other.image && self.marks == other.marks
495    }
496}
497
498/// Wrap `text` with the Markdown syntax implied by `mark`.
499///
500/// This mirrors the per-mark formatting in [`Paragraph::to_markdown`] but
501/// operates on an already-sliced run, so it can reconstruct the Markdown
502/// source for a *partial* text selection. Applied inside-out (innermost markup
503/// first) so nested emphasis like `**_x_**` round-trips.
504pub(crate) fn wrap_with_mark(text: &str, mark: &TextMark) -> String {
505    if text.is_empty() {
506        return String::new();
507    }
508
509    let mut out = text.to_string();
510    if mark.code {
511        out = format!("`{}`", out);
512    }
513    if mark.italic {
514        out = format!("*{}*", out);
515    }
516    if mark.bold {
517        out = format!("**{}**", out);
518    }
519    if mark.strikethrough {
520        out = format!("~~{}~~", out);
521    }
522    if mark.underline {
523        // Markdown has no underline syntax, and `__` reads as bold to most
524        // parsers, so fall back to the inline HTML `<u>` parses from.
525        out = format!("<u>{}</u>", out);
526    }
527    if mark.highlight.is_some() {
528        out = format!("=={}==", out);
529    }
530    if let Some(link) = &mark.link {
531        out = match &link.title {
532            Some(title) => format!("[{}]({} \"{}\")", out, link.url, title),
533            None => format!("[{}]({})", out, link.url),
534        };
535    }
536    out
537}
538
539/// How a selection covers one rendered run, so the caller can tell whether it
540/// continues into an adjacent inline image.
541#[derive(Default)]
542struct RunSelection {
543    emitted: bool,
544    at_start: bool,
545    at_end: bool,
546}
547
548/// Emit the selected part of one rendered run, preceded by the images the
549/// selection has run into. `run` holds the run's children with their offset
550/// into the run's concatenated text.
551fn emit_run(
552    state: &Arc<Mutex<InlineState>>,
553    run: &[(usize, &InlineNode)],
554    pending_images: &mut Vec<String>,
555    out: &mut String,
556) -> RunSelection {
557    let mut selected = RunSelection::default();
558    let Ok(state) = state.lock() else {
559        return selected;
560    };
561    let Some(selection) = &state.selection else {
562        return selected;
563    };
564    if selection.start >= selection.end {
565        return selected;
566    }
567
568    selected.at_start = selection.start == 0;
569    selected.at_end = selection.end >= state.text.len();
570
571    for (start, child) in run {
572        let end = start + child.text.len();
573        let lo = selection.start.max(*start);
574        let hi = selection.end.min(end);
575        if lo >= hi {
576            continue;
577        }
578
579        if !selected.emitted {
580            if selected.at_start {
581                out.push_str(&pending_images.join(""));
582            }
583            pending_images.clear();
584        }
585        selected.emitted = true;
586
587        out.push_str(&reconstruct_markdown(
588            &child.text,
589            &child.marks,
590            (lo - start)..(hi - start),
591        ));
592    }
593
594    selected
595}
596
597/// The Markdown source for an inline image, e.g. `![alt](url "title")`.
598fn image_markdown(image: &ImageNode) -> String {
599    let alt = image.alt.clone().unwrap_or_default();
600    let title = image
601        .title
602        .clone()
603        .map_or(String::new(), |title| format!(" \"{}\"", title));
604    format!("![{}]({}{})", alt, image.url, title)
605}
606
607/// Reconstruct the Markdown source for the `selection` sub-range of a text run
608/// carrying `marks`.
609///
610/// `selection` is a byte range into `text`. For each mark that overlaps the
611/// selection, the overlapping slice is wrapped in the mark's Markdown syntax
612/// (see [`wrap_with_mark`]); slices not covered by any mark are emitted
613/// verbatim. This lets a rendered-offset selection be copied back as Markdown
614/// source (e.g. selecting inside a `**bold**` run yields `**bold**`).
615pub(crate) fn reconstruct_markdown(
616    text: &str,
617    marks: &[(Range<usize>, TextMark)],
618    selection: Range<usize>,
619) -> String {
620    let start = selection.start.min(text.len());
621    let end = selection.end.min(text.len());
622    if start >= end {
623        return String::new();
624    }
625
626    let mut out = String::new();
627    let mut cursor = start;
628    // Marks are stored in ascending, non-overlapping order by the parser.
629    for (range, mark) in marks.iter() {
630        let seg_start = range.start.max(start);
631        let seg_end = range.end.min(end);
632        if seg_start >= seg_end {
633            continue;
634        }
635        // Emit any unmarked text before this mark verbatim.
636        if cursor < seg_start {
637            out.push_str(&text[cursor..seg_start]);
638        }
639        out.push_str(&wrap_with_mark(&text[seg_start..seg_end], mark));
640        cursor = seg_end;
641    }
642    // Trailing unmarked text.
643    if cursor < end {
644        out.push_str(&text[cursor..end]);
645    }
646    out
647}
648
649/// Reconstruct the Markdown source of the selected cells of `table`.
650///
651/// Cells emit their own selected source; rows are piped (`| a | b |`) and the
652/// delimiter/alignment row is inserted after the first row, so a selected
653/// table round-trips as a Markdown table. Returns an empty string when no cell
654/// is selected.
655fn table_selected_source(table: &Table) -> String {
656    let cell_source = |cell: &TableCell| cell.children.selected_source().replace('\n', " ");
657
658    let any_selected = table.children.iter().any(|row| {
659        row.children
660            .iter()
661            .any(|cell| !cell_source(cell).trim().is_empty())
662    });
663    if !any_selected {
664        return String::new();
665    }
666
667    let mut lines: Vec<String> = Vec::new();
668    for (row_ix, row) in table.children.iter().enumerate() {
669        let cells: Vec<String> = row
670            .children
671            .iter()
672            .map(|cell| cell_source(cell).trim().to_string())
673            .collect();
674        lines.push(format!("| {} |", cells.join(" | ")));
675
676        // The Markdown delimiter row carries the column alignments and must
677        // follow the header row.
678        if row_ix == 0 {
679            let aligns: Vec<String> = (0..row.children.len())
680                .map(|ix| {
681                    match table.column_align(ix) {
682                        ColumnumnAlign::Left => ":--",
683                        ColumnumnAlign::Center => ":-:",
684                        ColumnumnAlign::Right => "--:",
685                    }
686                    .to_string()
687                })
688                .collect();
689            lines.push(format!("| {} |", aligns.join(" | ")));
690        }
691    }
692
693    lines.join("\n")
694}
695
696/// Reconstruct the Markdown source of the selected items of a list.
697///
698/// Restores the list marker (`- ` / `N. `) and task-list checkbox (`[x] ` /
699/// `[ ] `) of each item, and recurses into nested lists with a deeper `indent`
700/// so nesting is preserved. `indent` is the leading whitespace for this level;
701/// nested levels are indented by the width of the parent marker so continuation
702/// and sub-list lines align under the item text. Items with no selected content
703/// are skipped but still consume an ordered number, so the remaining items keep
704/// their original numbering.
705fn list_selected_source(children: &[BlockNode], ordered: bool, indent: &str) -> String {
706    let mut out = String::new();
707    let mut item_ix = 0usize;
708
709    for child in children {
710        let BlockNode::ListItem {
711            children: item_children,
712            checked,
713            ..
714        } = child
715        else {
716            continue;
717        };
718
719        let marker = if ordered {
720            format!("{}. ", item_ix + 1)
721        } else {
722            "- ".to_string()
723        };
724        let checkbox = match checked {
725            Some(true) => "[x] ",
726            Some(false) => "[ ] ",
727            None => "",
728        };
729        let child_indent = format!("{}{}", indent, " ".repeat(marker.len()));
730
731        // Split the item into its own content and any nested lists, so the
732        // nested lists can be indented under the content.
733        let mut content = String::new();
734        let mut nested = String::new();
735        for sub in item_children {
736            if let BlockNode::List {
737                children: sub_children,
738                ordered: sub_ordered,
739                ..
740            } = sub
741            {
742                nested.push_str(&list_selected_source(
743                    sub_children,
744                    *sub_ordered,
745                    &child_indent,
746                ));
747            } else {
748                content.push_str(&sub.text_by_kind(BlockTextKind::SelectedSource));
749            }
750        }
751        let content = content.trim_end_matches('\n');
752
753        if content.is_empty() && nested.is_empty() {
754            item_ix += 1;
755            continue;
756        }
757
758        if content.is_empty() {
759            // An item whose only selected content is a nested list.
760            out.push_str(indent);
761            out.push_str(&marker);
762            out.push_str(checkbox.trim_end());
763            out.push('\n');
764        } else {
765            // The first line carries the marker and checkbox; continuation
766            // lines are indented to align under the item text.
767            let mut lines = content.lines();
768            if let Some(first) = lines.next() {
769                out.push_str(indent);
770                out.push_str(&marker);
771                out.push_str(checkbox);
772                out.push_str(first);
773                out.push('\n');
774            }
775            for line in lines {
776                out.push_str(&child_indent);
777                out.push_str(line);
778                out.push('\n');
779            }
780        }
781        out.push_str(&nested);
782        item_ix += 1;
783    }
784
785    out
786}
787
788impl InlineNode {
789    pub(crate) fn new(text: impl Into<SharedString>) -> Self {
790        Self {
791            text: text.into(),
792            image: None,
793            marks: vec![],
794            state: Arc::new(Mutex::new(InlineState::default())),
795        }
796    }
797
798    pub(crate) fn image(image: ImageNode) -> Self {
799        let mut this = Self::new("");
800        this.image = Some(image);
801        this
802    }
803
804    pub(crate) fn marks(mut self, marks: Vec<(Range<usize>, TextMark)>) -> Self {
805        self.marks = marks;
806        self
807    }
808}
809
810/// The paragraph element, contains multiple text nodes.
811///
812/// Unlike other Element, this is cloneable, because it is used in the Node AST.
813/// We are keep the selection state inside this AST Nodes.
814#[derive(Debug, Clone, Default)]
815pub(crate) struct Paragraph {
816    pub(super) span: Option<Span>,
817    pub(super) children: Vec<InlineNode>,
818    /// The link references in this paragraph, used for reference links.
819    ///
820    /// The key is the identifier, the value is the url.
821    pub(super) link_refs: HashMap<SharedString, SharedString>,
822
823    pub(crate) state: Arc<Mutex<InlineState>>,
824}
825
826impl PartialEq for Paragraph {
827    fn eq(&self, other: &Self) -> bool {
828        self.span == other.span
829            && self.children == other.children
830            && self.link_refs == other.link_refs
831    }
832}
833
834impl Paragraph {
835    pub(crate) fn new(text: String) -> Self {
836        Self {
837            span: None,
838            children: vec![InlineNode::new(&text)],
839            link_refs: HashMap::new(),
840            state: Arc::new(Mutex::new(InlineState::default())),
841        }
842    }
843
844    pub(super) fn selected_text(&self) -> String {
845        let mut text = String::new();
846
847        for c in self.children.iter() {
848            let Ok(state) = c.state.lock() else {
849                continue;
850            };
851            if let Some(selection) = &state.selection {
852                text.push_str(&state.text[selection.start..selection.end]);
853            }
854        }
855
856        if let Ok(state) = self.state.lock()
857            && let Some(selection) = &state.selection
858        {
859            text.push_str(&state.text[selection.start..selection.end]);
860        }
861
862        text
863    }
864
865    /// Reconstruct the Markdown source for the current selection.
866    ///
867    /// Mirrors [`selected_text`](Self::selected_text), but emits Markdown
868    /// instead of the rendered text, using each inline node's `marks` (see
869    /// [`reconstruct_markdown`]).
870    ///
871    /// Selection offsets index an `InlineState.text`, and one such state spans
872    /// *several* children: [`Paragraph::render`] concatenates children until it
873    /// hits an inline image, stores that run in the image child's state, then
874    /// starts over; whatever follows the last image is stored in `self.state`.
875    /// So walk the children in the same runs and map each selected byte back to
876    /// the child it was rendered from — mapping against a single child's text
877    /// would attribute the same offsets to children in other runs.
878    ///
879    /// An image has no selection of its own, so it is emitted when the
880    /// selection runs into it: reaching the end of the run before it, and
881    /// starting at the beginning of the run after it. A paragraph that begins
882    /// or ends with an image has no run on that side, which counts as reaching
883    /// it.
884    pub(super) fn selected_source(&self) -> String {
885        let mut source = String::new();
886        let mut pending_images: Vec<String> = Vec::new();
887        let mut run: Vec<(usize, &InlineNode)> = Vec::new();
888        let mut offset = 0;
889        let mut enters_image = true;
890
891        for child in self.children.iter() {
892            let Some(image) = &child.image else {
893                run.push((offset, child));
894                offset += child.text.len();
895                continue;
896            };
897
898            // The run before an image is stored in that image's own state.
899            let run_before = !run.is_empty();
900            let selected = emit_run(&child.state, &run, &mut pending_images, &mut source);
901            if run_before {
902                enters_image = selected.emitted && selected.at_end;
903            }
904            if enters_image {
905                pending_images.push(image_markdown(image));
906            } else {
907                pending_images.clear();
908            }
909
910            run.clear();
911            offset = 0;
912        }
913
914        let trailing = emit_run(&self.state, &run, &mut pending_images, &mut source);
915        // Trailing images have no run after them to flush them.
916        if !trailing.emitted && enters_image && !source.is_empty() {
917            source.push_str(&pending_images.join(""));
918        }
919
920        source
921    }
922
923    pub(super) fn text(&self) -> String {
924        let mut text = String::new();
925        for node in self.children.iter() {
926            text.push_str(&node.text);
927        }
928        text
929    }
930
931    /// Synchronously clear the selection stored in every inline state.
932    ///
933    /// Mirrors the [`selected_text`](Self::selected_text) traversal.
934    pub(super) fn has_selection(&self) -> bool {
935        self.children
936            .iter()
937            .any(|c| c.state.lock().is_ok_and(|state| state.selection.is_some()))
938            || self
939                .state
940                .lock()
941                .is_ok_and(|state| state.selection.is_some())
942    }
943
944    pub(super) fn clear_selection(&self) {
945        for c in self.children.iter() {
946            if let Ok(mut state) = c.state.lock() {
947                state.selection = None;
948            }
949        }
950
951        if let Ok(mut state) = self.state.lock() {
952            state.selection = None;
953        }
954    }
955}
956
957#[derive(Debug, Clone, Default, PartialEq)]
958pub(crate) struct Table {
959    pub(crate) children: Vec<TableRow>,
960    pub(crate) column_aligns: Vec<ColumnumnAlign>,
961    pub(crate) span: Option<Span>,
962}
963
964/// Plain snapshot of a rendered Markdown table, passed to the
965/// [`crate::text::TextView::table_actions`] hook.
966#[derive(Debug, Clone, Default, PartialEq)]
967pub struct TableData {
968    /// First table row (header cells) as plain text.
969    pub headers: Vec<String>,
970    /// Rows after the header as plain text cells. May be ragged while
971    /// a table is still streaming in.
972    pub rows: Vec<Vec<String>>,
973    /// The table serialized back to GFM pipe-table Markdown, alignments kept.
974    pub markdown: String,
975    /// Byte range of the table in the Markdown source, for callers that need
976    /// to map the table back to the document.
977    ///
978    /// Not needed to keep element ids apart: the actions row is wrapped in its
979    /// own identified element, so plain ids like `"copy"` are already scoped
980    /// per table.
981    pub span: Option<Range<usize>>,
982}
983
984impl Table {
985    pub(crate) fn column_align(&self, index: usize) -> ColumnumnAlign {
986        self.column_aligns.get(index).copied().unwrap_or_default()
987    }
988
989    /// Serialize the table back to GFM pipe-table Markdown (`| a | b |`),
990    /// preserving column alignments. Cell newlines collapse to spaces and
991    /// `|` is escaped so rows stay intact.
992    ///
993    /// Mirrors [`table_selected_source`], which does the same for the selected
994    /// cells only.
995    pub(crate) fn to_markdown(&self) -> String {
996        let mut lines: Vec<String> = Vec::with_capacity(self.children.len() + 1);
997
998        for (row_ix, row) in self.children.iter().enumerate() {
999            let cells: Vec<String> = row
1000                .children
1001                .iter()
1002                .map(|cell| {
1003                    cell.children
1004                        .to_markdown()
1005                        .trim()
1006                        .replace('\n', " ")
1007                        .replace('|', "\\|")
1008                })
1009                .collect();
1010            lines.push(format!("| {} |", cells.join(" | ")));
1011
1012            // The Markdown delimiter row carries the column alignments and must
1013            // follow the header row.
1014            if row_ix == 0 {
1015                let aligns: Vec<String> = (0..row.children.len())
1016                    .map(|ix| {
1017                        match self.column_align(ix) {
1018                            ColumnumnAlign::Left => ":--",
1019                            ColumnumnAlign::Center => ":-:",
1020                            ColumnumnAlign::Right => "--:",
1021                        }
1022                        .to_string()
1023                    })
1024                    .collect();
1025                lines.push(format!("| {} |", aligns.join(" | ")));
1026            }
1027        }
1028
1029        lines.join("\n")
1030    }
1031
1032    /// Snapshot of this table for the [`crate::text::TextView::table_actions`]
1033    /// hook.
1034    pub(crate) fn table_data(&self) -> TableData {
1035        let row_text = |row: &TableRow| {
1036            row.children
1037                .iter()
1038                .map(|cell| cell.children.text().trim().to_string())
1039                .collect::<Vec<_>>()
1040        };
1041
1042        TableData {
1043            headers: self.children.first().map(row_text).unwrap_or_default(),
1044            rows: self.children.iter().skip(1).map(row_text).collect(),
1045            markdown: self.to_markdown(),
1046            span: self.span.map(|span| span.start..span.end),
1047        }
1048    }
1049}
1050
1051#[derive(Debug, Default, Copy, Clone, PartialEq)]
1052pub(crate) enum ColumnumnAlign {
1053    #[default]
1054    Left,
1055    Center,
1056    Right,
1057}
1058
1059impl From<mdast::AlignKind> for ColumnumnAlign {
1060    fn from(value: mdast::AlignKind) -> Self {
1061        match value {
1062            mdast::AlignKind::None => ColumnumnAlign::Left,
1063            mdast::AlignKind::Left => ColumnumnAlign::Left,
1064            mdast::AlignKind::Center => ColumnumnAlign::Center,
1065            mdast::AlignKind::Right => ColumnumnAlign::Right,
1066        }
1067    }
1068}
1069
1070#[derive(Debug, Clone, Default, PartialEq)]
1071pub(crate) struct TableRow {
1072    pub children: Vec<TableCell>,
1073}
1074
1075#[derive(Debug, Clone, Default, PartialEq)]
1076pub(crate) struct TableCell {
1077    pub children: Paragraph,
1078    pub width: Option<DefiniteLength>,
1079}
1080
1081impl Paragraph {
1082    pub(crate) fn take(&mut self) -> Paragraph {
1083        std::mem::replace(
1084            self,
1085            Paragraph {
1086                span: None,
1087                children: vec![],
1088                link_refs: Default::default(),
1089                state: Arc::new(Mutex::new(InlineState::default())),
1090            },
1091        )
1092    }
1093
1094    pub(crate) fn is_image(&self) -> bool {
1095        false
1096    }
1097
1098    pub(crate) fn set_span(&mut self, span: Span) {
1099        self.span = Some(span);
1100    }
1101
1102    pub(crate) fn push_str(&mut self, text: &str) {
1103        self.children.push(
1104            InlineNode::new(text.to_string()).marks(vec![(0..text.len(), TextMark::default())]),
1105        );
1106    }
1107
1108    pub(crate) fn push(&mut self, text: InlineNode) {
1109        self.children.push(text);
1110    }
1111
1112    pub(crate) fn push_image(&mut self, image: ImageNode) {
1113        self.children.push(InlineNode::image(image));
1114    }
1115
1116    pub(crate) fn is_empty(&self) -> bool {
1117        self.children.is_empty()
1118            || self
1119                .children
1120                .iter()
1121                .all(|node| node.text.is_empty() && node.image.is_none())
1122    }
1123
1124    /// Return length of children text.
1125    pub(crate) fn text_len(&self) -> usize {
1126        self.children
1127            .iter()
1128            .map(|node| node.text.len())
1129            .sum::<usize>()
1130    }
1131
1132    pub(crate) fn merge(&mut self, other: Self) {
1133        self.children.extend(other.children);
1134    }
1135}
1136
1137#[derive(Debug, Clone)]
1138struct CachedCodeBlockStyles {
1139    /// The active theme used to compute `styles`.
1140    highlight_theme: Arc<HighlightTheme>,
1141    styles: Vec<(Range<usize>, HighlightStyle)>,
1142}
1143
1144#[derive(Debug, Clone)]
1145pub struct CodeBlock {
1146    lang: Option<SharedString>,
1147    styles: Arc<Mutex<Option<CachedCodeBlockStyles>>>,
1148    state: Arc<Mutex<InlineState>>,
1149    pub span: Option<Span>,
1150}
1151
1152impl PartialEq for CodeBlock {
1153    fn eq(&self, other: &Self) -> bool {
1154        self.lang == other.lang && self.code() == other.code() && self.span == other.span
1155    }
1156}
1157
1158impl CodeBlock {
1159    /// Get the language of the code block.
1160    pub fn lang(&self) -> Option<SharedString> {
1161        self.lang.clone()
1162    }
1163
1164    /// Get the code content of the code block.
1165    pub fn code(&self) -> SharedString {
1166        self.state
1167            .lock()
1168            .map(|state| state.text.clone())
1169            .unwrap_or_default()
1170    }
1171
1172    pub(crate) fn new(
1173        code: SharedString,
1174        lang: Option<SharedString>,
1175        span: Option<impl Into<Span>>,
1176    ) -> Self {
1177        let state = Arc::new(Mutex::new(InlineState::default()));
1178        if let Ok(mut state) = state.lock() {
1179            state.set_text(code);
1180        }
1181
1182        Self {
1183            lang,
1184            styles: Arc::new(Mutex::new(None)),
1185            state,
1186            span: span.map(|s| s.into()),
1187        }
1188    }
1189
1190    pub(crate) fn styles(
1191        &self,
1192        highlight_theme: &Arc<HighlightTheme>,
1193    ) -> Vec<(Range<usize>, HighlightStyle)> {
1194        let Some(lang) = &self.lang else {
1195            return Vec::new();
1196        };
1197
1198        let Ok(mut styles) = self.styles.lock() else {
1199            return Vec::new();
1200        };
1201
1202        // Pointer identity is the common render-path fast check. If an
1203        // equivalent theme is reallocated, adopt its Arc while preserving the
1204        // computed styles so subsequent renders also use the fast path.
1205        if let Some(cached) = styles.as_mut() {
1206            if Arc::ptr_eq(&cached.highlight_theme, highlight_theme) {
1207                return cached.styles.clone();
1208            }
1209
1210            if cached.highlight_theme.as_ref() == highlight_theme.as_ref() {
1211                cached.highlight_theme = highlight_theme.clone();
1212                return cached.styles.clone();
1213            }
1214        }
1215
1216        let code = self.code();
1217        let computed_styles = CODE_BLOCK_HIGHLIGHTERS.with(|cache| {
1218            let mut cache = cache.borrow_mut();
1219            let highlighter = cache
1220                .entry(lang.clone())
1221                .or_insert_with(|| SyntaxHighlighter::new(lang));
1222
1223            if let Some(config) = LanguageRegistry::singleton().language(lang)
1224                && highlighter.language() != &config.name
1225            {
1226                *highlighter = SyntaxHighlighter::new(lang);
1227            }
1228
1229            let old_end_byte = highlighter.text().len();
1230            let old_end_position = highlighter.text().offset_to_point(old_end_byte);
1231            let code_rope = Rope::from_str(code.as_str());
1232
1233            let edit = InputEdit {
1234                start_byte: 0,
1235                old_end_byte,
1236                new_end_byte: code.len(),
1237                start_position: Point::new(0, 0),
1238                old_end_position,
1239                new_end_position: code_rope.offset_to_point(code.len()),
1240            };
1241
1242            #[cfg(feature = "tree-sitter")]
1243            highlighter.update_input(Some(edit), &code_rope, None);
1244            #[cfg(not(feature = "tree-sitter"))]
1245            highlighter.update(Some(edit), &code_rope, None);
1246            highlighter.styles(&(0..code.len()), highlight_theme.as_ref())
1247        });
1248        *styles = Some(CachedCodeBlockStyles {
1249            highlight_theme: highlight_theme.clone(),
1250            styles: computed_styles.clone(),
1251        });
1252        computed_styles
1253    }
1254
1255    pub(super) fn selected_text(&self) -> String {
1256        let mut text = String::new();
1257        if let Ok(state) = self.state.lock()
1258            && let Some(selection) = &state.selection
1259        {
1260            text.push_str(&state.text[selection.start..selection.end]);
1261        }
1262        text
1263    }
1264
1265    /// Markdown source for the current selection.
1266    ///
1267    /// The selected code is wrapped in a fenced code block carrying the block's
1268    /// language, so a selected code block round-trips as Markdown (e.g.
1269    /// ```` ```rust\n…\n``` ````) instead of pasting as bare, unfenced text.
1270    /// A partial selection is still emitted as a valid fenced block.
1271    pub(super) fn selected_source(&self) -> String {
1272        let code = self.selected_text();
1273        if code.is_empty() {
1274            return String::new();
1275        }
1276        let lang = self.lang.clone().unwrap_or_default();
1277        // Trim trailing newlines so the closing fence sits on its own line
1278        // directly after the last code line (no blank line before it).
1279        let code = code.trim_end_matches('\n');
1280        format!("```{}\n{}\n```", lang, code)
1281    }
1282
1283    pub(super) fn text(&self) -> String {
1284        self.state
1285            .lock()
1286            .map(|state| state.text.to_string())
1287            .unwrap_or_default()
1288    }
1289
1290    /// Synchronously clear the selection stored in the inline state.
1291    ///
1292    /// Mirrors the [`selected_text`](Self::selected_text) traversal.
1293    pub(super) fn has_selection(&self) -> bool {
1294        self.state
1295            .lock()
1296            .is_ok_and(|state| state.selection.is_some())
1297    }
1298
1299    pub(super) fn clear_selection(&self) {
1300        if let Ok(mut state) = self.state.lock() {
1301            state.selection = None;
1302        }
1303    }
1304
1305    fn render(
1306        &self,
1307        options: &NodeRenderOptions,
1308        node_cx: &NodeContext,
1309        window: &mut Window,
1310        cx: &mut App,
1311    ) -> AnyElement {
1312        let style = &node_cx.style;
1313
1314        div()
1315            .w_full()
1316            .min_w_0()
1317            .when(!options.is_last, |this| this.pb(style.paragraph_gap))
1318            .child(
1319                div()
1320                    .id(("codeblock", options.ix))
1321                    .w_full()
1322                    .min_w_0()
1323                    .p_3()
1324                    .rounded(cx.theme().radius)
1325                    .bg(cx.theme().tokens.muted)
1326                    .font_family(cx.theme().mono_font_family.clone())
1327                    .text_size(cx.theme().mono_font_size)
1328                    .relative()
1329                    .refine_style(&style.code_block)
1330                    .child(Inline::new(
1331                        "code",
1332                        self.state.clone(),
1333                        vec![],
1334                        self.styles(&cx.theme().highlight_theme),
1335                        node_cx.link_click_handler.clone(),
1336                    ))
1337                    .when_some(node_cx.code_block_actions.clone(), |this, actions| {
1338                        this.child(
1339                            div()
1340                                .id("actions")
1341                                .absolute()
1342                                .top_2()
1343                                .right_2()
1344                                .bg(cx.theme().tokens.muted)
1345                                .rounded(cx.theme().radius)
1346                                .child(actions(&self, window, cx)),
1347                        )
1348                    }),
1349            )
1350            .into_any_element()
1351    }
1352}
1353
1354/// A context for rendering nodes, contains link references.
1355#[derive(Default, Clone)]
1356pub(crate) struct NodeContext {
1357    /// The byte offset of the node in the original markdown text.
1358    /// Used for incremental updates.
1359    pub(crate) offset: usize,
1360    pub(crate) link_refs: HashMap<SharedString, LinkMark>,
1361    pub(crate) style: TextViewStyle,
1362    pub(crate) code_block_actions: Option<Arc<CodeBlockActionsFn>>,
1363    pub(crate) table_actions: Option<Arc<TableActionsFn>>,
1364    pub(crate) link_click_handler: Option<Arc<LinkClickHandlerFn>>,
1365    pub(crate) markdown_extensions: Arc<MarkdownExtensions>,
1366}
1367
1368impl NodeContext {
1369    pub(super) fn add_ref(&mut self, identifier: SharedString, link: LinkMark) {
1370        self.link_refs.insert(identifier, link);
1371    }
1372}
1373
1374impl PartialEq for NodeContext {
1375    fn eq(&self, other: &Self) -> bool {
1376        self.link_refs == other.link_refs && self.style == other.style
1377        // Note: code_block_actions, table_actions and markdown_extensions are
1378        // intentionally not compared (closures can't be compared)
1379    }
1380}
1381
1382impl Paragraph {
1383    fn render(&self, node_cx: &NodeContext, _window: &mut Window, cx: &mut App) -> AnyElement {
1384        let span = self.span;
1385        let children = &self.children;
1386
1387        if self.should_render_inline_flow() {
1388            return InlineFlow::new(
1389                span.unwrap_or_default(),
1390                self.inline_flow_items(node_cx, cx),
1391                node_cx.link_click_handler.clone(),
1392            )
1393            .into_any_element();
1394        }
1395
1396        let mut child_nodes: Vec<AnyElement> = vec![];
1397
1398        let mut text = String::new();
1399        let mut highlights: Vec<(Range<usize>, HighlightStyle)> = vec![];
1400        let mut links: Vec<(Range<usize>, LinkMark)> = vec![];
1401        let mut offset = 0;
1402
1403        let mut ix = 0;
1404        for inline_node in children {
1405            let text_len = inline_node.text.len();
1406            text.push_str(&inline_node.text);
1407
1408            if let Some(image) = &inline_node.image {
1409                if text.len() > 0 {
1410                    if let Ok(mut state) = inline_node.state.lock() {
1411                        state.set_text(text.clone().into());
1412                    }
1413                    child_nodes.push(
1414                        Inline::new(
1415                            ix,
1416                            inline_node.state.clone(),
1417                            links.clone(),
1418                            highlights.clone(),
1419                            node_cx.link_click_handler.clone(),
1420                        )
1421                        .into_any_element(),
1422                    );
1423                }
1424                let link_click_handler = node_cx.link_click_handler.clone();
1425                child_nodes.push(
1426                    img(image_source(&image.url))
1427                        .id(ix)
1428                        .object_fit(ObjectFit::Contain)
1429                        .max_w(relative(1.))
1430                        .when_some(image.width, |this, width| this.w(width))
1431                        .when_some(image.link.clone(), |this, link| {
1432                            let title = image.title();
1433                            let link_click_handler = link_click_handler.clone();
1434                            let aux_link = link.clone();
1435                            let aux_link_click_handler = link_click_handler.clone();
1436                            this.cursor_pointer()
1437                                .tooltip(move |window, cx| {
1438                                    Tooltip::new(title.clone()).build(window, cx)
1439                                })
1440                                .on_click(move |event, window, cx| {
1441                                    gpui_base::TextSelection::end(window, cx);
1442                                    cx.stop_propagation();
1443                                    handle_link_click(
1444                                        &link_click_handler,
1445                                        link.url.clone(),
1446                                        event.clone(),
1447                                        window,
1448                                        cx,
1449                                    );
1450                                })
1451                                .on_aux_click(move |event, window, cx| {
1452                                    gpui_base::TextSelection::end(window, cx);
1453                                    cx.stop_propagation();
1454                                    handle_link_click(
1455                                        &aux_link_click_handler,
1456                                        aux_link.url.clone(),
1457                                        event.clone(),
1458                                        window,
1459                                        cx,
1460                                    );
1461                                })
1462                        })
1463                        .into_any_element(),
1464                );
1465
1466                text.clear();
1467                links.clear();
1468                highlights.clear();
1469                offset = 0;
1470            } else {
1471                let mut node_highlights = vec![];
1472                for (range, style) in &inline_node.marks {
1473                    let inner_range = (offset + range.start)..(offset + range.end);
1474
1475                    let mut highlight = HighlightStyle::default();
1476                    if style.bold {
1477                        highlight.font_weight = Some(FontWeight::BOLD);
1478                    }
1479                    if style.italic {
1480                        highlight.font_style = Some(FontStyle::Italic);
1481                    }
1482                    if style.strikethrough {
1483                        highlight.strikethrough = Some(gpui::StrikethroughStyle {
1484                            thickness: gpui::px(1.),
1485                            ..Default::default()
1486                        });
1487                    }
1488                    if style.underline {
1489                        highlight.underline = Some(gpui::UnderlineStyle {
1490                            thickness: gpui::px(1.),
1491                            ..Default::default()
1492                        });
1493                    }
1494                    if style.code {
1495                        highlight = highlight.highlight(node_cx.style.inline_code_highlight(cx));
1496                    }
1497                    if let Some(color) = style.highlight {
1498                        highlight.background_color = Some(color);
1499                    }
1500
1501                    if let Some(mut link_mark) = style.link.clone() {
1502                        highlight.color = Some(cx.theme().link);
1503                        highlight.underline = Some(gpui::UnderlineStyle {
1504                            thickness: gpui::px(1.),
1505                            ..Default::default()
1506                        });
1507
1508                        // convert link references, replace link
1509                        if let Some(identifier) = link_mark.identifier.as_ref() {
1510                            if let Some(mark) = node_cx.link_refs.get(identifier) {
1511                                link_mark = mark.clone();
1512                            }
1513                        }
1514
1515                        links.push((inner_range.clone(), link_mark));
1516                    }
1517
1518                    node_highlights.push((inner_range, highlight));
1519                }
1520
1521                highlights = gpui::combine_highlights(highlights, node_highlights).collect();
1522                offset += text_len;
1523            }
1524            ix += 1;
1525        }
1526
1527        // Add the last text node
1528        if text.len() > 0 {
1529            if let Ok(mut state) = self.state.lock() {
1530                state.set_text(text.into());
1531            }
1532            child_nodes.push(
1533                Inline::new(
1534                    ix,
1535                    self.state.clone(),
1536                    links,
1537                    highlights,
1538                    node_cx.link_click_handler.clone(),
1539                )
1540                .into_any_element(),
1541            );
1542        }
1543
1544        div()
1545            .id(span.unwrap_or_default())
1546            .children(child_nodes)
1547            .into_any_element()
1548    }
1549
1550    fn should_render_inline_flow(&self) -> bool {
1551        let has_image = self.children.iter().any(|child| child.image.is_some());
1552        let has_text = self.children.iter().any(|child| !child.text.is_empty());
1553        has_image && has_text
1554    }
1555
1556    fn inline_flow_items(&self, node_cx: &NodeContext, cx: &mut App) -> Vec<InlineFlowItem> {
1557        let mut items = Vec::new();
1558        let mut text = String::new();
1559        let mut highlights: Vec<(Range<usize>, HighlightStyle)> = vec![];
1560        let mut links: Vec<(Range<usize>, LinkMark)> = vec![];
1561        let mut offset = 0;
1562
1563        for inline_node in &self.children {
1564            let text_len = inline_node.text.len();
1565            text.push_str(&inline_node.text);
1566
1567            if let Some(image) = &inline_node.image {
1568                if !text.is_empty() {
1569                    if let Ok(mut state) = inline_node.state.lock() {
1570                        state.set_text(text.clone().into());
1571                    }
1572                    items.push(InlineFlowItem::Text {
1573                        state: inline_node.state.clone(),
1574                        text: text.clone().into(),
1575                        links: links.clone(),
1576                        highlights: highlights.clone(),
1577                    });
1578                }
1579
1580                items.push(InlineFlowItem::Image {
1581                    url: image.url.clone(),
1582                    link: image.link.clone(),
1583                    title: image.title(),
1584                    width: image.width,
1585                    height: image.height,
1586                });
1587
1588                text.clear();
1589                links.clear();
1590                highlights.clear();
1591                offset = 0;
1592            } else {
1593                let mut node_highlights = vec![];
1594                for (range, style) in &inline_node.marks {
1595                    let inner_range = (offset + range.start)..(offset + range.end);
1596
1597                    let mut highlight = HighlightStyle::default();
1598                    if style.bold {
1599                        highlight.font_weight = Some(FontWeight::BOLD);
1600                    }
1601                    if style.italic {
1602                        highlight.font_style = Some(FontStyle::Italic);
1603                    }
1604                    if style.strikethrough {
1605                        highlight.strikethrough = Some(gpui::StrikethroughStyle {
1606                            thickness: gpui::px(1.),
1607                            ..Default::default()
1608                        });
1609                    }
1610                    if style.underline {
1611                        highlight.underline = Some(gpui::UnderlineStyle {
1612                            thickness: gpui::px(1.),
1613                            ..Default::default()
1614                        });
1615                    }
1616                    if style.code {
1617                        highlight = highlight.highlight(node_cx.style.inline_code_highlight(cx));
1618                    }
1619                    if let Some(color) = style.highlight {
1620                        highlight.background_color = Some(color);
1621                    }
1622
1623                    if let Some(mut link_mark) = style.link.clone() {
1624                        highlight.color = Some(cx.theme().link);
1625                        highlight.underline = Some(gpui::UnderlineStyle {
1626                            thickness: gpui::px(1.),
1627                            ..Default::default()
1628                        });
1629
1630                        if let Some(identifier) = link_mark.identifier.as_ref()
1631                            && let Some(mark) = node_cx.link_refs.get(identifier)
1632                        {
1633                            link_mark = mark.clone();
1634                        }
1635
1636                        links.push((inner_range.clone(), link_mark));
1637                    }
1638
1639                    node_highlights.push((inner_range, highlight));
1640                }
1641
1642                highlights = gpui::combine_highlights(highlights, node_highlights).collect();
1643                offset += text_len;
1644            }
1645        }
1646
1647        if !text.is_empty() {
1648            if let Ok(mut state) = self.state.lock() {
1649                state.set_text(text.clone().into());
1650            }
1651            items.push(InlineFlowItem::Text {
1652                state: self.state.clone(),
1653                text: text.into(),
1654                links,
1655                highlights,
1656            });
1657        }
1658
1659        items
1660    }
1661}
1662
1663impl Paragraph {
1664    fn to_markdown(&self) -> String {
1665        let mut text = self
1666            .children
1667            .iter()
1668            .map(|text_node| {
1669                let mut text = text_node.text.to_string();
1670                for (range, style) in &text_node.marks {
1671                    if style.bold {
1672                        text = format!("**{}**", &text_node.text[range.clone()]);
1673                    }
1674                    if style.italic {
1675                        text = format!("*{}*", &text_node.text[range.clone()]);
1676                    }
1677                    if style.strikethrough {
1678                        text = format!("~~{}~~", &text_node.text[range.clone()]);
1679                    }
1680                    if style.code {
1681                        text = format!("`{}`", &text_node.text[range.clone()]);
1682                    }
1683                    if style.highlight.is_some() {
1684                        text = format!("=={}==", &text_node.text[range.clone()]);
1685                    }
1686                    if let Some(link) = &style.link {
1687                        text = format!("[{}]({})", &text_node.text[range.clone()], link.url);
1688                    }
1689                }
1690
1691                if let Some(image) = &text_node.image {
1692                    let alt = image.alt.clone().unwrap_or_default();
1693                    let title = image
1694                        .title
1695                        .clone()
1696                        .map_or(String::new(), |t| format!(" \"{}\"", t));
1697                    text.push_str(&format!("![{}]({}{})", alt, image.url, title))
1698                }
1699
1700                text
1701            })
1702            .collect::<Vec<_>>()
1703            .join("");
1704
1705        text.push_str("\n\n");
1706        text
1707    }
1708}
1709
1710impl BlockNode {
1711    /// Converts the node to markdown format.
1712    ///
1713    /// This is used to generate markdown for test.
1714    #[allow(dead_code)]
1715    pub(crate) fn to_markdown(&self) -> String {
1716        match self {
1717            BlockNode::Root { children, .. } => children
1718                .iter()
1719                .map(|child| child.to_markdown())
1720                .collect::<Vec<_>>()
1721                .join("\n\n"),
1722            BlockNode::Paragraph(paragraph) => paragraph.to_markdown(),
1723            BlockNode::Heading {
1724                level, children, ..
1725            } => {
1726                let hashes = "#".repeat(*level as usize);
1727                format!("{} {}", hashes, children.to_markdown())
1728            }
1729            BlockNode::Blockquote { children, .. } => {
1730                let content = children
1731                    .iter()
1732                    .map(|child| child.to_markdown())
1733                    .collect::<Vec<_>>()
1734                    .join("\n\n");
1735
1736                content
1737                    .lines()
1738                    .map(|line| format!("> {}", line))
1739                    .collect::<Vec<_>>()
1740                    .join("\n")
1741            }
1742            BlockNode::List {
1743                children, ordered, ..
1744            } => children
1745                .iter()
1746                .enumerate()
1747                .map(|(i, child)| {
1748                    let prefix = if *ordered {
1749                        format!("{}. ", i + 1)
1750                    } else {
1751                        "- ".to_string()
1752                    };
1753                    format!("{}{}", prefix, child.to_markdown())
1754                })
1755                .collect::<Vec<_>>()
1756                .join("\n"),
1757            BlockNode::ListItem {
1758                children, checked, ..
1759            } => {
1760                let checkbox = if let Some(checked) = checked {
1761                    if *checked { "[x] " } else { "[ ] " }
1762                } else {
1763                    ""
1764                };
1765                format!(
1766                    "{}{}",
1767                    checkbox,
1768                    children
1769                        .iter()
1770                        .map(|child| child.to_markdown())
1771                        .collect::<Vec<_>>()
1772                        .join("\n")
1773                )
1774            }
1775            BlockNode::CodeBlock(code_block) => {
1776                format!(
1777                    "```{}\n{}\n```",
1778                    code_block.lang.clone().unwrap_or_default(),
1779                    code_block.code()
1780                )
1781            }
1782            BlockNode::Table(table) => table.to_markdown(),
1783            BlockNode::Break { html, .. } => {
1784                if *html {
1785                    "<br>".to_string()
1786                } else {
1787                    "\n".to_string()
1788                }
1789            }
1790            BlockNode::HorizontalRule { .. } => "---".to_string(),
1791            BlockNode::Custom(node) => node.to_markdown(),
1792            BlockNode::Definition {
1793                identifier,
1794                url,
1795                title,
1796                ..
1797            } => {
1798                if let Some(title) = title {
1799                    format!("[{}]: {} \"{}\"", identifier, url, title)
1800                } else {
1801                    format!("[{}]: {}", identifier, url)
1802                }
1803            }
1804            BlockNode::Unknown { .. } => "".to_string(),
1805        }
1806        .trim()
1807        .to_string()
1808    }
1809}
1810
1811impl BlockNode {
1812    fn render_list_item_row(
1813        content: AnyElement,
1814        ix: usize,
1815        options: NodeRenderOptions,
1816        checked: Option<bool>,
1817        cx: &mut App,
1818    ) -> Div {
1819        h_flex()
1820            .w_full()
1821            .flex_1()
1822            .min_w_0()
1823            .relative()
1824            .items_start()
1825            .content_start()
1826            .when(!options.todo && checked.is_none(), |this| {
1827                this.child(list_item_prefix(ix, options.ordered, options.depth))
1828            })
1829            .when_some(checked, |this, checked| {
1830                // Todo list checkbox
1831                this.child(
1832                    div()
1833                        .flex()
1834                        .mt(rems(0.4))
1835                        .mr_1p5()
1836                        .size(rems(0.875))
1837                        .items_center()
1838                        .justify_center()
1839                        .rounded(cx.theme().radius.half())
1840                        .border_1()
1841                        .border_color(cx.theme().primary)
1842                        .text_color(cx.theme().primary_foreground)
1843                        .when(checked, |this| {
1844                            this.bg(cx.theme().tokens.primary)
1845                                .child(Icon::new(IconName::Check).size_2().text_xs())
1846                        }),
1847                )
1848            })
1849            .child(div().flex_1().min_w_0().overflow_hidden().child(content))
1850    }
1851
1852    fn render_list_item(
1853        item: &BlockNode,
1854        ix: usize,
1855        options: NodeRenderOptions,
1856        node_cx: &NodeContext,
1857        window: &mut Window,
1858        cx: &mut App,
1859    ) -> AnyElement {
1860        match item {
1861            BlockNode::ListItem {
1862                children,
1863                spread,
1864                checked,
1865                ..
1866            } => v_flex()
1867                .id(("li", options.ix))
1868                .w_full()
1869                .min_w_0()
1870                .when(*spread, |this| this.child(div()))
1871                .children({
1872                    let mut items: Vec<Div> = Vec::with_capacity(children.len());
1873
1874                    for (child_ix, child) in children.iter().enumerate() {
1875                        match child {
1876                            BlockNode::Paragraph { .. } => {
1877                                let last_not_list = child_ix > 0
1878                                    && !matches!(children[child_ix - 1], BlockNode::List { .. });
1879
1880                                let text = child.render_block(
1881                                    NodeRenderOptions {
1882                                        depth: options.depth + 1,
1883                                        todo: checked.is_some(),
1884                                        is_last: true,
1885                                        ..options
1886                                    },
1887                                    node_cx,
1888                                    window,
1889                                    cx,
1890                                );
1891
1892                                // Continuation paragraph — stack vertically below
1893                                // the previous row, indented to align with the text
1894                                // column (past bullet/number prefix).
1895                                if last_not_list {
1896                                    if let Some(preceding_row) = items.pop() {
1897                                        items.push(
1898                                            v_flex().child(preceding_row).child(
1899                                                div()
1900                                                    .w_full()
1901                                                    .pl(rems(1.))
1902                                                    .overflow_hidden()
1903                                                    .child(text),
1904                                            ),
1905                                        );
1906                                        continue;
1907                                    }
1908                                }
1909
1910                                items.push(Self::render_list_item_row(
1911                                    text, ix, options, *checked, cx,
1912                                ));
1913                            }
1914                            BlockNode::List { .. } => {
1915                                items.push(div().ml(rems(1.)).child(child.render_block(
1916                                    NodeRenderOptions {
1917                                        depth: options.depth + 1,
1918                                        todo: checked.is_some(),
1919                                        is_last: true,
1920                                        ..options
1921                                    },
1922                                    node_cx,
1923                                    window,
1924                                    cx,
1925                                )));
1926                            }
1927                            BlockNode::Root { .. }
1928                            | BlockNode::Heading { .. }
1929                            | BlockNode::Blockquote { .. }
1930                            | BlockNode::CodeBlock(_)
1931                            | BlockNode::Custom(_)
1932                            | BlockNode::Table(_)
1933                            | BlockNode::HorizontalRule { .. } => {
1934                                let block = child.render_block(
1935                                    NodeRenderOptions {
1936                                        depth: options.depth + 1,
1937                                        todo: checked.is_some(),
1938                                        is_last: true,
1939                                        ..options
1940                                    },
1941                                    node_cx,
1942                                    window,
1943                                    cx,
1944                                );
1945
1946                                if child_ix == 0 {
1947                                    items.push(Self::render_list_item_row(
1948                                        block, ix, options, *checked, cx,
1949                                    ));
1950                                } else {
1951                                    // Indent continuation blocks to align with a
1952                                    // nested sub-list (`ml(rems(1.))`) and with
1953                                    // continuation paragraphs.
1954                                    items.push(
1955                                        div()
1956                                            .w_full()
1957                                            .min_w_0()
1958                                            .pl(rems(1.))
1959                                            .overflow_hidden()
1960                                            .child(block),
1961                                    );
1962                                }
1963                            }
1964                            BlockNode::ListItem { .. }
1965                            | BlockNode::Break { .. }
1966                            | BlockNode::Definition { .. }
1967                            | BlockNode::Unknown => {}
1968                        }
1969                    }
1970                    items
1971                })
1972                .into_any_element(),
1973            _ => div().into_any_element(),
1974        }
1975    }
1976
1977    /// Render a Markdown table. Dispatches to a horizontally scrollable layout
1978    /// when `style.table` opts in with overflow-x: scroll, otherwise to the
1979    /// default layout that fits the container width and wraps cell content.
1980    fn render_table(
1981        item: &BlockNode,
1982        options: &NodeRenderOptions,
1983        node_cx: &NodeContext,
1984        window: &mut Window,
1985        cx: &mut App,
1986    ) -> impl IntoElement {
1987        const DEFAULT_LENGTH: usize = 5;
1988
1989        let table = match item {
1990            BlockNode::Table(table) => table,
1991            _ => return div().into_any_element(),
1992        };
1993
1994        // Per-column max text length (in chars), used to proportion the columns
1995        // in the default (wrap) layout.
1996        let mut col_lens: Vec<usize> = vec![];
1997        for row in table.children.iter() {
1998            for (ix, cell) in row.children.iter().enumerate() {
1999                if col_lens.len() <= ix {
2000                    col_lens.push(DEFAULT_LENGTH);
2001                }
2002                col_lens[ix] = col_lens[ix].max(cell.children.text_len());
2003            }
2004        }
2005
2006        // Scroll mode is opted in via `style.table` overflow-x: scroll.
2007        if matches!(node_cx.style.table.overflow.x, Some(Overflow::Scroll)) {
2008            Self::render_scroll_table(table, col_lens.len(), options, node_cx, window, cx)
2009        } else {
2010            Self::render_wrap_table(table, &col_lens, options, node_cx, window, cx)
2011        }
2012    }
2013
2014    /// Horizontally scrollable table layout (opt-in via `style.table`
2015    /// overflow-x: scroll).
2016    ///
2017    /// Column widths come from the **measured** shaped text of each cell (the
2018    /// widest per column across all rows), so columns line up and fit their
2019    /// content exactly — char-count heuristics are inaccurate on proportional
2020    /// fonts. The layout adapts to the frame like CSS auto table layout:
2021    ///
2022    /// - Wider than the content: cells `flex_grow` proportionally to fill.
2023    /// - Narrower: columns shrink and their text wraps, but not below a
2024    ///   per-column floor.
2025    /// - Narrower than the floors: the table keeps the floor widths and
2026    ///   scrolls horizontally, so no content ever becomes unreachable.
2027    ///
2028    /// `white_space: nowrap` on `style.table_cell` composes like in CSS: the
2029    /// refinement keeps cell text on a single line, and the floors are raised
2030    /// to the full content widths so the single-line columns never shrink —
2031    /// the table scrolls as soon as the content is wider than the frame.
2032    fn render_scroll_table(
2033        table: &Table,
2034        col_count: usize,
2035        options: &NodeRenderOptions,
2036        node_cx: &NodeContext,
2037        window: &mut Window,
2038        cx: &mut App,
2039    ) -> AnyElement {
2040        const CELL_PAD_PX: f32 = 16.0; // px_2 horizontal padding
2041        const CELL_MIN_PX: f32 = 48.0;
2042        // Shrinking columns stop (and the table starts to scroll) at a floor
2043        // scaled to their content: roughly the width at which the text wraps
2044        // to `CELL_WRAP_MAX_LINES` lines, clamped between the two bounds so
2045        // moderate columns can still wrap meaningfully while one huge column
2046        // cannot push the scroll threshold arbitrarily high.
2047        const CELL_WRAP_MAX_LINES: f32 = 2.0;
2048        const CELL_WRAP_MIN_PX: f32 = 160.0;
2049        const CELL_WRAP_MAX_PX: f32 = 480.0;
2050        const CELL_BORDER_PX: f32 = 1.0; // border_r_1 drawn by every column but the last
2051        const TABLE_BORDER_PX: f32 = 2.0; // the track's border_1, left + right
2052
2053        // Measure the widest text per column (max-content width). Never
2054        // capped: a cap would clip overflowing text *and* leave it outside
2055        // the scrollable width, making it unreachable.
2056        let text_style = window.text_style();
2057        let font_size = text_style.font_size.to_pixels(window.rem_size());
2058        let mut col_w = vec![CELL_MIN_PX; col_count];
2059        for row in table.children.iter() {
2060            for (ix, cell) in row.children.iter().enumerate() {
2061                let Some(slot) = col_w.get_mut(ix) else {
2062                    continue;
2063                };
2064                let mut w = 0.0_f32;
2065                for line in cell.children.text().split('\n') {
2066                    let line = line.trim();
2067                    if line.is_empty() {
2068                        continue;
2069                    }
2070                    let run = text_style.to_run(line.len());
2071                    let line_w = window
2072                        .text_system()
2073                        .layout_line(line, font_size, &[run], None)
2074                        .width;
2075                    w = w.max(f32::from(line_w));
2076                }
2077                // Border-box widths, so the padding and border the cell draws
2078                // must leave the measured text its full width.
2079                let border = if ix + 1 < col_count {
2080                    CELL_BORDER_PX
2081                } else {
2082                    0.
2083                };
2084                *slot = slot.max(w + CELL_PAD_PX + border);
2085            }
2086        }
2087        let style = &node_cx.style;
2088        // Nowrap cells (via the `table_cell` refinement, which cascades to
2089        // the cell text) must never shrink below their single-line content,
2090        // so their floor is the content width itself.
2091        let nowrap = style.table_cell.text.white_space == Some(WhiteSpace::Nowrap);
2092        let col_min_w: Vec<f32> = if nowrap {
2093            col_w.clone()
2094        } else {
2095            col_w
2096                .iter()
2097                .map(|w| {
2098                    (w / CELL_WRAP_MAX_LINES)
2099                        .clamp(CELL_WRAP_MIN_PX, CELL_WRAP_MAX_PX)
2100                        .min(*w)
2101                })
2102                .collect()
2103        };
2104        let min_total_w: f32 = col_min_w.iter().sum::<f32>() + TABLE_BORDER_PX;
2105
2106        let table_scroll_key = if let Some(span) = table.span {
2107            SharedString::from(format!(
2108                "{}-table-scroll-{}:{}",
2109                window.current_view(),
2110                span.start,
2111                span.end
2112            ))
2113        } else {
2114            SharedString::from(format!(
2115                "{}-table-scroll-{}",
2116                window.current_view(),
2117                options.ix
2118            ))
2119        };
2120        let scroll_handle = window
2121            .use_keyed_state(table_scroll_key, cx, |_, _| ScrollHandle::default())
2122            .read(cx)
2123            .clone();
2124        let row_count = table.children.len();
2125        let mut rows = Vec::with_capacity(row_count);
2126        for (row_ix, row) in table.children.iter().enumerate() {
2127            let mut cells = Vec::with_capacity(row.children.len());
2128            for (ix, cell) in row.children.iter().enumerate() {
2129                let align = table.column_align(ix);
2130                let is_last_col = ix == row.children.len() - 1;
2131                let width = col_w.get(ix).copied().unwrap_or(CELL_MIN_PX);
2132                let min_width = col_min_w.get(ix).copied().unwrap_or(CELL_MIN_PX);
2133                cells.push(
2134                    div()
2135                        .id(("cell", ix))
2136                        // Measured max-content width is the flex-basis;
2137                        // `flex_grow` (proportional to it) distributes extra
2138                        // space so a narrow table still fills the frame, while
2139                        // shrinking is clamped at `min_w` — the flex engine
2140                        // squeezes columns (their text wraps) down to the
2141                        // floors before the track starts to scroll.
2142                        .flex_basis(px(width))
2143                        .flex_grow(width)
2144                        .flex_shrink(1.)
2145                        .min_w(px(min_width))
2146                        .overflow_hidden()
2147                        .when(align == ColumnumnAlign::Center, |this| this.text_center())
2148                        .when(align == ColumnumnAlign::Right, |this| this.text_right())
2149                        .px_2()
2150                        .py_1()
2151                        .when(!is_last_col, |this| {
2152                            this.border_r_1().border_color(cx.theme().table_row_border)
2153                        })
2154                        .refine_style(&style.table_cell)
2155                        .child(cell.children.render(node_cx, window, cx)),
2156                );
2157            }
2158            rows.push(
2159                div()
2160                    .id("row")
2161                    .w_full()
2162                    .when(row_ix < row_count - 1, |this| this.border_b_1())
2163                    .border_color(cx.theme().table_row_border)
2164                    .flex()
2165                    .flex_row()
2166                    // The first row is the header, as everywhere else that
2167                    // reads a table (`table_data`, `to_markdown`). The
2168                    // refinement comes last so it can override the defaults.
2169                    .when(row_ix == 0, |this| {
2170                        this.bg(cx.theme().tokens.table_head)
2171                            .text_color(cx.theme().table_head_foreground)
2172                            .refine_style(&style.table_head)
2173                    })
2174                    .children(cells),
2175            );
2176        }
2177
2178        div()
2179            .pb(rems(1.))
2180            .w_full()
2181            .child(
2182                // Scroll viewport: clips and scrolls horizontally (overflow-x
2183                // is handled by `ScrollableMask`, so vertical wheel events keep
2184                // bubbling to the parent TextView). No border — the frame is on
2185                // the inner track so it wraps the table tightly.
2186                horizontal_scroll_area(
2187                    ("table", options.ix),
2188                    &scroll_handle,
2189                    &style.table,
2190                    // Bordered track sized to `max(viewport, column floors)`:
2191                    // `min_w_full` fills the frame while the columns can still
2192                    // shrink-to-fit (their text wrapping), the definite
2193                    // `w(min_total_w)` keeps the floors once they are reached,
2194                    // letting the track exceed the viewport and scroll.
2195                    div()
2196                        .min_w_full()
2197                        .w(px(min_total_w))
2198                        .bg(cx.theme().tokens.table)
2199                        .border_1()
2200                        .border_color(cx.theme().border)
2201                        .rounded(cx.theme().radius)
2202                        .children(rows),
2203                ),
2204            )
2205            // Custom actions row (e.g. copy / download) rendered below the
2206            // table. The hook's element spans full width; alignment is up to
2207            // the caller (e.g. `h_flex().justify_end()`). The gap keeps hover
2208            // backgrounds of the action buttons off the table border, and the
2209            // id scopes the caller's element ids per table, so plain ids like
2210            // `"copy"` don't collide across tables (same as code blocks).
2211            .children(node_cx.table_actions.clone().map(|f| {
2212                div().id(("table-actions", options.ix)).mt_1().child(f(
2213                    &table.table_data(),
2214                    window,
2215                    cx,
2216                ))
2217            }))
2218            .into_any_element()
2219    }
2220
2221    /// Default table layout: a flex grid whose columns are proportioned by
2222    /// content length and shrink to fit the container width (cell text wraps).
2223    fn render_wrap_table(
2224        table: &Table,
2225        col_lens: &[usize],
2226        options: &NodeRenderOptions,
2227        node_cx: &NodeContext,
2228        window: &mut Window,
2229        cx: &mut App,
2230    ) -> AnyElement {
2231        const MAX_LENGTH: usize = 150;
2232
2233        let style = &node_cx.style;
2234        let row_count = table.children.len();
2235        let mut rows = Vec::with_capacity(row_count);
2236        for (row_ix, row) in table.children.iter().enumerate() {
2237            let mut cells = Vec::with_capacity(row.children.len());
2238            for (ix, cell) in row.children.iter().enumerate() {
2239                let align = table.column_align(ix);
2240                let is_last_col = ix == row.children.len() - 1;
2241                let len = col_lens
2242                    .get(ix)
2243                    .copied()
2244                    .unwrap_or(MAX_LENGTH)
2245                    .min(MAX_LENGTH);
2246
2247                cells.push(
2248                    div()
2249                        .id(("cell", ix))
2250                        .overflow_hidden()
2251                        .when(align == ColumnumnAlign::Center, |this| this.text_center())
2252                        .when(align == ColumnumnAlign::Right, |this| this.text_right())
2253                        .min_w_16()
2254                        .w(Length::Definite(relative(len as f32)))
2255                        .px_2()
2256                        .py_1()
2257                        .when(!is_last_col, |this| {
2258                            this.border_r_1().border_color(cx.theme().table_row_border)
2259                        })
2260                        .refine_style(&style.table_cell)
2261                        .child(cell.children.render(node_cx, window, cx)),
2262                );
2263            }
2264
2265            rows.push(
2266                div()
2267                    .id("row")
2268                    .w_full()
2269                    .when(row_ix < row_count - 1, |this| this.border_b_1())
2270                    .border_color(cx.theme().table_row_border)
2271                    .flex()
2272                    .flex_row()
2273                    // The first row is the header, as everywhere else that
2274                    // reads a table (`table_data`, `to_markdown`). The
2275                    // refinement comes last so it can override the defaults.
2276                    .when(row_ix == 0, |this| {
2277                        this.bg(cx.theme().tokens.table_head)
2278                            .text_color(cx.theme().table_head_foreground)
2279                            .refine_style(&style.table_head)
2280                    })
2281                    .children(cells),
2282            );
2283        }
2284
2285        div()
2286            .pb(rems(1.))
2287            .w_full()
2288            .child(
2289                div()
2290                    .id(("table", options.ix))
2291                    .w_full()
2292                    .bg(cx.theme().tokens.table)
2293                    .border_1()
2294                    .border_color(cx.theme().border)
2295                    .rounded(cx.theme().radius)
2296                    .overflow_hidden()
2297                    .children(rows)
2298                    .refine_style(&style.table),
2299            )
2300            // Custom actions row (e.g. copy / download) rendered below the
2301            // table. The hook's element spans full width; alignment is up to
2302            // the caller (e.g. `h_flex().justify_end()`). The gap keeps hover
2303            // backgrounds of the action buttons off the table border, and the
2304            // id scopes the caller's element ids per table, so plain ids like
2305            // `"copy"` don't collide across tables (same as code blocks).
2306            .children(node_cx.table_actions.clone().map(|f| {
2307                div().id(("table-actions", options.ix)).mt_1().child(f(
2308                    &table.table_data(),
2309                    window,
2310                    cx,
2311                ))
2312            }))
2313            .into_any_element()
2314    }
2315
2316    pub(crate) fn render_block(
2317        &self,
2318        options: NodeRenderOptions,
2319        node_cx: &NodeContext,
2320        window: &mut Window,
2321        cx: &mut App,
2322    ) -> AnyElement {
2323        let ix = options.ix;
2324        let mb = if options.in_list || options.is_last {
2325            rems(0.)
2326        } else {
2327            node_cx.style.paragraph_gap
2328        };
2329
2330        match self {
2331            BlockNode::Root { children, .. } => div()
2332                .id(("div", ix))
2333                .children(children.into_iter().enumerate().map(move |(ix, node)| {
2334                    node.render_block(NodeRenderOptions { ix, ..options }, node_cx, window, cx)
2335                }))
2336                .into_any_element(),
2337            BlockNode::Paragraph(paragraph) => div()
2338                .id(("p", ix))
2339                .pb(mb)
2340                .child(paragraph.render(node_cx, window, cx))
2341                .into_any_element(),
2342            BlockNode::Heading {
2343                level, children, ..
2344            } => {
2345                let (text_size, font_weight) = match level {
2346                    1 => (rems(2.), FontWeight::BOLD),
2347                    2 => (rems(1.5), FontWeight::SEMIBOLD),
2348                    3 => (rems(1.25), FontWeight::SEMIBOLD),
2349                    4 => (rems(1.125), FontWeight::SEMIBOLD),
2350                    5 => (rems(1.), FontWeight::SEMIBOLD),
2351                    6 => (rems(1.), FontWeight::MEDIUM),
2352                    _ => (rems(1.), FontWeight::NORMAL),
2353                };
2354
2355                let mut text_size = text_size.to_pixels(node_cx.style.heading_base_font_size);
2356                if let Some(f) = node_cx.style.heading_font_size.as_ref() {
2357                    text_size = (f)(*level, node_cx.style.heading_base_font_size);
2358                }
2359
2360                div()
2361                    .id(SharedString::from(format!("h{}-{}", level, ix)))
2362                    .pb(rems(0.3))
2363                    .whitespace_normal()
2364                    .text_size(text_size)
2365                    .font_weight(font_weight)
2366                    .child(children.render(node_cx, window, cx))
2367                    .into_any_element()
2368            }
2369            BlockNode::Blockquote { children, .. } => div()
2370                .w_full()
2371                .pb(mb)
2372                .child(
2373                    div()
2374                        .id(("blockquote", ix))
2375                        .w_full()
2376                        .text_color(cx.theme().muted_foreground)
2377                        .border_l_3()
2378                        .border_color(cx.theme().secondary_active)
2379                        .px_4()
2380                        .children({
2381                            let children_len = children.len();
2382                            children.into_iter().enumerate().map(move |(index, c)| {
2383                                let is_last = index == children_len - 1;
2384                                c.render_block(options.is_last(is_last), node_cx, window, cx)
2385                            })
2386                        }),
2387                )
2388                .into_any_element(),
2389            BlockNode::List {
2390                children, ordered, ..
2391            } => v_flex()
2392                .id((if *ordered { "ol" } else { "ul" }, ix))
2393                .w_full()
2394                .min_w_0()
2395                .pb(mb)
2396                .children({
2397                    let mut items = Vec::with_capacity(children.len());
2398                    let mut item_index = 0;
2399                    for (ix, item) in children.into_iter().enumerate() {
2400                        let is_item = item.is_list_item();
2401
2402                        items.push(Self::render_list_item(
2403                            item,
2404                            item_index,
2405                            NodeRenderOptions {
2406                                ix,
2407                                ordered: *ordered,
2408                                ..options
2409                            },
2410                            node_cx,
2411                            window,
2412                            cx,
2413                        ));
2414
2415                        if is_item {
2416                            item_index += 1;
2417                        }
2418                    }
2419                    items
2420                })
2421                .into_any_element(),
2422            BlockNode::CodeBlock(code_block) => code_block.render(&options, node_cx, window, cx),
2423            BlockNode::Custom(node) => {
2424                let inner = match node_cx.markdown_extensions.render_block(node, window, cx) {
2425                    Some(rendered) => rendered,
2426                    None => div().child(node.as_text().to_string()).into_any_element(),
2427                };
2428
2429                div().pb(mb).child(inner).into_any_element()
2430            }
2431            BlockNode::Table { .. } => {
2432                Self::render_table(self, &options, node_cx, window, cx).into_any_element()
2433            }
2434            BlockNode::HorizontalRule { .. } => div()
2435                .pb(mb)
2436                .child(div().id("horizontal-rule").bg(cx.theme().border).h(px(2.)))
2437                .into_any_element(),
2438            BlockNode::Break { .. } => div().id("break").into_any_element(),
2439            BlockNode::Unknown { .. } | BlockNode::Definition { .. } => div().into_any_element(),
2440            _ => {
2441                if cfg!(debug_assertions) {
2442                    tracing::warn!("unknown implementation: {:?}", self);
2443                }
2444
2445                div().into_any_element()
2446            }
2447        }
2448    }
2449}
2450
2451#[cfg(test)]
2452mod tests {
2453    use super::*;
2454
2455    #[test]
2456    fn reconstruct_markdown_wraps_marked_runs() {
2457        // "bold" fully covered by a bold mark.
2458        let marks = vec![(0..4, TextMark::default().bold())];
2459        assert_eq!(reconstruct_markdown("bold", &marks, 0..4), "**bold**");
2460        // Partial selection inside the bold run still wraps the slice.
2461        assert_eq!(reconstruct_markdown("bold", &marks, 1..3), "**ol**");
2462    }
2463
2464    #[test]
2465    fn reconstruct_markdown_emits_unmarked_text_verbatim() {
2466        // "a b c": plain, code, plain across three runs concatenated.
2467        let text = "a b c";
2468        let marks = vec![(2..3, TextMark::default().code())];
2469        assert_eq!(reconstruct_markdown(text, &marks, 0..5), "a `b` c");
2470        // Selecting only the plain tail.
2471        assert_eq!(reconstruct_markdown(text, &marks, 3..5), " c");
2472    }
2473
2474    #[test]
2475    fn reconstruct_markdown_handles_code_italic_strike_link() {
2476        assert_eq!(
2477            reconstruct_markdown("x", &[(0..1, TextMark::default().code())], 0..1),
2478            "`x`"
2479        );
2480        assert_eq!(
2481            reconstruct_markdown("x", &[(0..1, TextMark::default().italic())], 0..1),
2482            "*x*"
2483        );
2484        assert_eq!(
2485            reconstruct_markdown("x", &[(0..1, TextMark::default().strikethrough())], 0..1),
2486            "~~x~~"
2487        );
2488        let link = TextMark::default().link(LinkMark {
2489            url: "https://example.com".into(),
2490            ..Default::default()
2491        });
2492        assert_eq!(
2493            reconstruct_markdown("x", &[(0..1, link)], 0..1),
2494            "[x](https://example.com)"
2495        );
2496    }
2497
2498    #[test]
2499    fn reconstruct_markdown_nested_bold_italic() {
2500        // A single run marked both bold and italic (as produced by `**_x_**`).
2501        let mark = TextMark::default().bold().italic();
2502        // Inner (italic) is applied first, then bold: `***x***`.
2503        assert_eq!(reconstruct_markdown("x", &[(0..1, mark)], 0..1), "***x***");
2504    }
2505
2506    /// Build a paragraph whose combined `state.text` is the concatenation of
2507    /// its children (mirroring `Paragraph::render`), then set the paragraph
2508    /// selection so `selected_source` can be exercised without a real paint.
2509    fn paragraph_with_children(children: Vec<InlineNode>) -> Paragraph {
2510        let combined: String = children.iter().map(|c| c.text.to_string()).collect();
2511        let paragraph = Paragraph {
2512            span: None,
2513            children,
2514            link_refs: HashMap::new(),
2515            state: Arc::new(Mutex::new(InlineState::default())),
2516        };
2517        if let Ok(mut state) = paragraph.state.lock() {
2518            state.set_text(combined.into());
2519        }
2520        paragraph
2521    }
2522
2523    fn set_paragraph_selection(paragraph: &Paragraph, range: Range<usize>) {
2524        if let Ok(mut state) = paragraph.state.lock() {
2525            state.selection = Some(range.into());
2526        }
2527    }
2528
2529    #[test]
2530    fn paragraph_selected_source_maps_partial_selection_across_runs() {
2531        // "This has **bold** text." rendered as ["This has ", "bold", " text."].
2532        let children = vec![
2533            InlineNode::new("This has ").marks(vec![(0..9, TextMark::default())]),
2534            InlineNode::new("bold").marks(vec![(0..4, TextMark::default().bold())]),
2535            InlineNode::new(" text.").marks(vec![(0..6, TextMark::default())]),
2536        ];
2537        let paragraph = paragraph_with_children(children);
2538
2539        // Select the whole paragraph: "This has bold text." -> source with **.
2540        set_paragraph_selection(&paragraph, 0..(9 + 4 + 6));
2541        assert_eq!(paragraph.selected_source(), "This has **bold** text.");
2542
2543        // Select only across the boundary "has **bold** te".
2544        // Rendered offsets: "has " starts at 5, "bold" at 9..13, " te" 13..16.
2545        set_paragraph_selection(&paragraph, 5..16);
2546        assert_eq!(paragraph.selected_source(), "has **bold** te");
2547
2548        // Select entirely inside the bold run -> still wrapped.
2549        set_paragraph_selection(&paragraph, 10..12);
2550        assert_eq!(paragraph.selected_source(), "**ol**");
2551    }
2552
2553    #[test]
2554    fn paragraph_selected_source_matches_text_when_no_marks() {
2555        let children =
2556            vec![InlineNode::new("plain words").marks(vec![(0..11, TextMark::default())])];
2557        let paragraph = paragraph_with_children(children);
2558        set_paragraph_selection(&paragraph, 0..11);
2559        assert_eq!(paragraph.selected_source(), "plain words");
2560        assert_eq!(paragraph.selected_text(), "plain words");
2561    }
2562
2563    fn selected_paragraph(text: &str) -> Paragraph {
2564        let len = text.len();
2565        let paragraph = paragraph_with_children(vec![
2566            InlineNode::new(text).marks(vec![(0..len, TextMark::default())]),
2567        ]);
2568        set_paragraph_selection(&paragraph, 0..len);
2569        paragraph
2570    }
2571
2572    #[test]
2573    fn heading_selected_source_prefixes_hashes() {
2574        let heading = BlockNode::Heading {
2575            level: 2,
2576            children: selected_paragraph("Title"),
2577            span: None,
2578        };
2579        assert_eq!(heading.selected_text(SelectionFormat::Source), "## Title\n");
2580        // Rendered text keeps no marker.
2581        assert_eq!(heading.selected_text(SelectionFormat::Plain), "Title\n");
2582    }
2583
2584    #[test]
2585    fn unordered_list_selected_source_prefixes_dash() {
2586        let list = BlockNode::List {
2587            ordered: false,
2588            span: None,
2589            children: vec![
2590                BlockNode::ListItem {
2591                    children: vec![BlockNode::Paragraph(selected_paragraph("one"))],
2592                    spread: false,
2593                    checked: None,
2594                    span: None,
2595                },
2596                BlockNode::ListItem {
2597                    children: vec![BlockNode::Paragraph(selected_paragraph("two"))],
2598                    spread: false,
2599                    checked: None,
2600                    span: None,
2601                },
2602            ],
2603        };
2604        assert_eq!(
2605            list.selected_text(SelectionFormat::Source),
2606            "- one\n- two\n"
2607        );
2608    }
2609
2610    #[test]
2611    fn ordered_list_selected_source_prefixes_numbers() {
2612        let list = BlockNode::List {
2613            ordered: true,
2614            span: None,
2615            children: vec![
2616                BlockNode::ListItem {
2617                    children: vec![BlockNode::Paragraph(selected_paragraph("first"))],
2618                    spread: false,
2619                    checked: None,
2620                    span: None,
2621                },
2622                BlockNode::ListItem {
2623                    children: vec![BlockNode::Paragraph(selected_paragraph("second"))],
2624                    spread: false,
2625                    checked: None,
2626                    span: None,
2627                },
2628            ],
2629        };
2630        assert_eq!(
2631            list.selected_text(SelectionFormat::Source),
2632            "1. first\n2. second\n"
2633        );
2634    }
2635
2636    #[test]
2637    fn nested_list_selected_source_indents_sublists() {
2638        // - one
2639        //   - nested
2640        // - two
2641        let nested = BlockNode::List {
2642            ordered: false,
2643            span: None,
2644            children: vec![BlockNode::ListItem {
2645                children: vec![BlockNode::Paragraph(selected_paragraph("nested"))],
2646                spread: false,
2647                checked: None,
2648                span: None,
2649            }],
2650        };
2651        let list = BlockNode::List {
2652            ordered: false,
2653            span: None,
2654            children: vec![
2655                BlockNode::ListItem {
2656                    children: vec![BlockNode::Paragraph(selected_paragraph("one")), nested],
2657                    spread: false,
2658                    checked: None,
2659                    span: None,
2660                },
2661                BlockNode::ListItem {
2662                    children: vec![BlockNode::Paragraph(selected_paragraph("two"))],
2663                    spread: false,
2664                    checked: None,
2665                    span: None,
2666                },
2667            ],
2668        };
2669        assert_eq!(
2670            list.selected_text(SelectionFormat::Source),
2671            "- one\n  - nested\n- two\n"
2672        );
2673    }
2674
2675    #[test]
2676    fn task_list_selected_source_restores_checkboxes() {
2677        let list = BlockNode::List {
2678            ordered: false,
2679            span: None,
2680            children: vec![
2681                BlockNode::ListItem {
2682                    children: vec![BlockNode::Paragraph(selected_paragraph("done"))],
2683                    spread: false,
2684                    checked: Some(true),
2685                    span: None,
2686                },
2687                BlockNode::ListItem {
2688                    children: vec![BlockNode::Paragraph(selected_paragraph("todo"))],
2689                    spread: false,
2690                    checked: Some(false),
2691                    span: None,
2692                },
2693            ],
2694        };
2695        assert_eq!(
2696            list.selected_text(SelectionFormat::Source),
2697            "- [x] done\n- [ ] todo\n"
2698        );
2699    }
2700
2701    #[test]
2702    fn blockquote_selected_source_prefixes_gt() {
2703        let quote = BlockNode::Blockquote {
2704            span: None,
2705            children: vec![BlockNode::Paragraph(selected_paragraph("quoted text"))],
2706        };
2707        assert_eq!(
2708            quote.selected_text(SelectionFormat::Source),
2709            "> quoted text\n"
2710        );
2711    }
2712
2713    #[test]
2714    fn table_selected_source_pipes_cells_with_alignment_row() {
2715        let cell = |text: &str| TableCell {
2716            children: selected_paragraph(text),
2717            width: None,
2718        };
2719        let table = Table {
2720            children: vec![
2721                TableRow {
2722                    children: vec![cell("Name"), cell("Age")],
2723                },
2724                TableRow {
2725                    children: vec![cell("Alice"), cell("30")],
2726                },
2727            ],
2728            column_aligns: vec![ColumnumnAlign::Left, ColumnumnAlign::Right],
2729            span: None,
2730        };
2731        let block = BlockNode::Table(table);
2732        assert_eq!(
2733            block.selected_text(SelectionFormat::Source),
2734            "| Name | Age |\n| :-- | --: |\n| Alice | 30 |\n"
2735        );
2736    }
2737
2738    /// A cell holding plain text, as `Table::to_markdown` and
2739    /// `Table::table_data` see it (neither needs a selection).
2740    fn plain_cell(text: &str) -> TableCell {
2741        TableCell {
2742            children: Paragraph::new(text.to_string()),
2743            width: None,
2744        }
2745    }
2746
2747    fn table_of(rows: Vec<Vec<TableCell>>, column_aligns: Vec<ColumnumnAlign>) -> Table {
2748        Table {
2749            children: rows
2750                .into_iter()
2751                .map(|children| TableRow { children })
2752                .collect(),
2753            column_aligns,
2754            span: None,
2755        }
2756    }
2757
2758    #[test]
2759    fn table_to_markdown_pipes_cells_with_alignment_row() {
2760        let table = table_of(
2761            vec![
2762                vec![plain_cell("Name"), plain_cell("Age"), plain_cell("Score")],
2763                vec![plain_cell("Alice"), plain_cell("30"), plain_cell("9.5")],
2764            ],
2765            vec![
2766                ColumnumnAlign::Left,
2767                ColumnumnAlign::Center,
2768                ColumnumnAlign::Right,
2769            ],
2770        );
2771
2772        assert_eq!(
2773            table.to_markdown(),
2774            "| Name | Age | Score |\n| :-- | :-: | --: |\n| Alice | 30 | 9.5 |"
2775        );
2776        // The block arm delegates to it.
2777        assert_eq!(
2778            BlockNode::Table(table.clone()).to_markdown(),
2779            table.to_markdown()
2780        );
2781    }
2782
2783    #[test]
2784    fn table_to_markdown_keeps_outer_pipes_for_a_single_column() {
2785        let table = table_of(
2786            vec![vec![plain_cell("Symbol")], vec![plain_cell("TSLA.US")]],
2787            vec![ColumnumnAlign::Left],
2788        );
2789
2790        assert_eq!(table.to_markdown(), "| Symbol |\n| :-- |\n| TSLA.US |");
2791    }
2792
2793    #[test]
2794    fn table_to_markdown_escapes_pipes_and_keeps_inline_marks() {
2795        let bold = TableCell {
2796            children: paragraph_with_children(vec![
2797                InlineNode::new("bold").marks(vec![(0..4, TextMark::default().bold())]),
2798            ]),
2799            width: None,
2800        };
2801        let table = table_of(
2802            vec![
2803                vec![plain_cell("a | b"), plain_cell("plain")],
2804                vec![plain_cell("c"), bold],
2805            ],
2806            vec![ColumnumnAlign::Left, ColumnumnAlign::Left],
2807        );
2808
2809        assert_eq!(
2810            table.to_markdown(),
2811            "| a \\| b | plain |\n| :-- | :-- |\n| c | **bold** |"
2812        );
2813    }
2814
2815    #[test]
2816    fn table_data_snapshots_plain_cells_and_markdown() {
2817        let mut table = table_of(
2818            vec![
2819                vec![plain_cell("  Name  "), plain_cell("Age")],
2820                vec![plain_cell("Alice"), plain_cell("30")],
2821            ],
2822            vec![ColumnumnAlign::Left, ColumnumnAlign::Right],
2823        );
2824        table.span = Some(Span { start: 4, end: 42 });
2825
2826        let data = table.table_data();
2827        assert_eq!(data.headers, vec!["Name", "Age"]);
2828        assert_eq!(data.rows, vec![vec!["Alice", "30"]]);
2829        assert_eq!(data.markdown, table.to_markdown());
2830        assert_eq!(data.span, Some(4..42));
2831    }
2832
2833    #[test]
2834    fn table_data_handles_tables_without_rows() {
2835        // Header only: still a valid table, with no data rows.
2836        let header_only = table_of(
2837            vec![vec![plain_cell("Name"), plain_cell("Age")]],
2838            vec![ColumnumnAlign::Left, ColumnumnAlign::Left],
2839        );
2840        let data = header_only.table_data();
2841        assert_eq!(data.headers, vec!["Name", "Age"]);
2842        assert!(data.rows.is_empty());
2843        assert_eq!(data.markdown, "| Name | Age |\n| :-- | :-- |");
2844
2845        // No rows at all (a table still streaming in): an empty snapshot.
2846        assert_eq!(Table::default().table_data(), TableData::default());
2847    }
2848
2849    fn image_paragraph(alt: &str, url: &str) -> Paragraph {
2850        let image = ImageNode {
2851            url: url.into(),
2852            alt: Some(alt.into()),
2853            ..Default::default()
2854        };
2855        Paragraph {
2856            span: None,
2857            children: vec![InlineNode::image(image)],
2858            link_refs: HashMap::new(),
2859            state: Arc::new(Mutex::new(InlineState::default())),
2860        }
2861    }
2862
2863    /// Every mark round-trips, including the two Markdown has no plain syntax
2864    /// for.
2865    #[test]
2866    fn marks_round_trip_through_reconstruction() {
2867        let wrap = |mark: TextMark| reconstruct_markdown("x", &[(0..1, mark)], 0..1);
2868
2869        assert_eq!(wrap(TextMark::default().bold()), "**x**");
2870        assert_eq!(wrap(TextMark::default().italic()), "*x*");
2871        assert_eq!(wrap(TextMark::default().code()), "`x`");
2872        assert_eq!(wrap(TextMark::default().strikethrough()), "~~x~~");
2873        assert_eq!(
2874            wrap(TextMark::default().highlight(crate::yellow(200))),
2875            "==x=="
2876        );
2877        // No Markdown syntax for underline, so it keeps the tag it came from.
2878        assert_eq!(wrap(TextMark::default().underline()), "<u>x</u>");
2879
2880        // A link keeps its title, which Markdown carries after the URL.
2881        assert_eq!(
2882            wrap(TextMark::default().link(LinkMark {
2883                url: "https://example.com".into(),
2884                title: Some("Tip".into()),
2885                ..Default::default()
2886            })),
2887            "[x](https://example.com \"Tip\")"
2888        );
2889    }
2890
2891    /// A block the selection covers whole comes straight from the source, so it
2892    /// keeps what the author wrote instead of a normalized reconstruction.
2893    #[test]
2894    fn document_selected_source_slices_covered_blocks_from_the_source() {
2895        use crate::text::document::ParsedDocument;
2896
2897        // `_italic_`, the `3.` start and the column padding all survive only
2898        // because the block is copied, not rebuilt.
2899        let source = "start\n\n3. _one_\n4. two\n\n---\n\nend";
2900        let list = "3. _one_\n4. two";
2901        let list_start = source.find(list).unwrap();
2902        let rule_start = source.find("---").unwrap();
2903
2904        let document = ParsedDocument {
2905            source: source.into(),
2906            blocks: vec![
2907                BlockNode::Paragraph(selected_paragraph("start")),
2908                BlockNode::List {
2909                    ordered: true,
2910                    children: vec![],
2911                    span: Some(Span {
2912                        start: list_start,
2913                        end: list_start + list.len(),
2914                    }),
2915                },
2916                BlockNode::HorizontalRule {
2917                    span: Some(Span {
2918                        start: rule_start,
2919                        end: rule_start + 3,
2920                    }),
2921                },
2922                BlockNode::Paragraph(selected_paragraph("end")),
2923            ]
2924            .into(),
2925        };
2926
2927        assert_eq!(
2928            document.selected_text(SelectionFormat::Source, None),
2929            "start\n\n3. _one_\n4. two\n\n---\n\nend"
2930        );
2931    }
2932
2933    #[test]
2934    fn document_selected_source_includes_enclosed_image() {
2935        use crate::text::document::ParsedDocument;
2936
2937        // A standalone image between two selected paragraphs is covered by the
2938        // selection, so it is copied whole even though it holds no selection of
2939        // its own — straight out of the source the parser located it in.
2940        let source = "before\n\n![alt](https://example.com/i.png)\n\nafter";
2941        let image_markdown = "![alt](https://example.com/i.png)";
2942        let start = source.find(image_markdown).unwrap();
2943        let mut image = image_paragraph("alt", "https://example.com/i.png");
2944        image.span = Some(Span {
2945            start,
2946            end: start + image_markdown.len(),
2947        });
2948
2949        let document = ParsedDocument {
2950            source: source.into(),
2951            blocks: vec![
2952                BlockNode::Paragraph(selected_paragraph("before")),
2953                BlockNode::Paragraph(image),
2954                BlockNode::Paragraph(selected_paragraph("after")),
2955            ]
2956            .into(),
2957        };
2958        assert_eq!(
2959            document.selected_text(SelectionFormat::Source, None),
2960            "before\n\n![alt](https://example.com/i.png)\n\nafter"
2961        );
2962    }
2963
2964    #[test]
2965    fn document_selected_source_drops_unenclosed_image() {
2966        use crate::text::document::ParsedDocument;
2967
2968        // An image after the only selected block, with nothing selected after
2969        // it, is not enclosed and is dropped.
2970        let document = ParsedDocument {
2971            source: String::new().into(),
2972            blocks: vec![
2973                BlockNode::Paragraph(selected_paragraph("before")),
2974                BlockNode::Paragraph(image_paragraph("alt", "u")),
2975            ]
2976            .into(),
2977        };
2978        assert_eq!(
2979            document.selected_text(SelectionFormat::Source, None),
2980            "before"
2981        );
2982    }
2983
2984    fn selected_code_block(code: &str, lang: Option<&str>) -> BlockNode {
2985        let block = CodeBlock::new(
2986            code.to_string().into(),
2987            lang.map(|l| l.to_string().into()),
2988            None::<Span>,
2989        );
2990        if let Ok(mut state) = block.state.lock() {
2991            let len = state.text.len();
2992            state.selection = Some((0..len).into());
2993        }
2994        BlockNode::CodeBlock(block)
2995    }
2996
2997    #[test]
2998    fn code_block_selected_source_wraps_in_fence_with_lang() {
2999        let block = selected_code_block("let x = 1;\n", Some("rust"));
3000        let code = block.selected_text(SelectionFormat::Plain);
3001        let code_trimmed = code.trim_end_matches('\n');
3002        // The source wraps the (trailing-newline-trimmed) selected code in a
3003        // fenced block carrying the language; the block arm adds one trailing
3004        // newline.
3005        assert_eq!(
3006            block.selected_text(SelectionFormat::Source),
3007            format!("```rust\n{}\n```\n", code_trimmed)
3008        );
3009        assert!(
3010            block
3011                .selected_text(SelectionFormat::Source)
3012                .starts_with("```rust\n")
3013        );
3014        assert!(
3015            block
3016                .selected_text(SelectionFormat::Source)
3017                .trim_end()
3018                .ends_with("\n```")
3019        );
3020    }
3021
3022    #[test]
3023    fn code_block_selected_source_without_lang() {
3024        let block = selected_code_block("plain\n", None);
3025        let code_trimmed = block.selected_text(SelectionFormat::Plain);
3026        let code_trimmed = code_trimmed.trim_end_matches('\n');
3027        assert_eq!(
3028            block.selected_text(SelectionFormat::Source),
3029            format!("```\n{}\n```\n", code_trimmed)
3030        );
3031    }
3032
3033    #[test]
3034    fn document_selected_source_joins_blocks_with_blank_line() {
3035        use crate::text::document::ParsedDocument;
3036
3037        // A heading, a paragraph, and a two-item ordered list, each fully
3038        // selected. Top-level blocks must be separated by a blank line so the
3039        // copied Markdown re-renders with the same structure.
3040        let document = ParsedDocument {
3041            source: String::new().into(),
3042            blocks: vec![
3043                BlockNode::Heading {
3044                    level: 1,
3045                    children: selected_paragraph("Title"),
3046                    span: None,
3047                },
3048                BlockNode::Paragraph(selected_paragraph("A paragraph.")),
3049                selected_code_block("let x = 1;\n", Some("rust")),
3050                BlockNode::List {
3051                    ordered: true,
3052                    span: None,
3053                    children: vec![
3054                        BlockNode::ListItem {
3055                            children: vec![BlockNode::Paragraph(selected_paragraph("one"))],
3056                            spread: false,
3057                            checked: None,
3058                            span: None,
3059                        },
3060                        BlockNode::ListItem {
3061                            children: vec![BlockNode::Paragraph(selected_paragraph("two"))],
3062                            spread: false,
3063                            checked: None,
3064                            span: None,
3065                        },
3066                    ],
3067                },
3068            ]
3069            .into(),
3070        };
3071
3072        assert_eq!(
3073            document.selected_text(SelectionFormat::Source, None),
3074            "# Title\n\nA paragraph.\n\n```rust\nlet x = 1;\n```\n\n1. one\n2. two"
3075        );
3076    }
3077
3078    #[cfg(feature = "tree-sitter")]
3079    use crate::{
3080        Theme, ThemeMode,
3081        text::{TextView, TextViewState},
3082    };
3083    #[cfg(feature = "tree-sitter")]
3084    use gpui::{AppContext as _, Context, Entity, Render, TestAppContext, VisualTestContext};
3085
3086    #[cfg(feature = "tree-sitter")]
3087    fn cached_highlight_theme(block: &CodeBlock) -> Option<Arc<HighlightTheme>> {
3088        block
3089            .styles
3090            .lock()
3091            .ok()
3092            .and_then(|styles| styles.as_ref().map(|styles| styles.highlight_theme.clone()))
3093    }
3094
3095    #[test]
3096    fn code_block_equality_includes_code_content() {
3097        let first = CodeBlock::new("let value = 1;".into(), Some("rust".into()), None::<Span>);
3098        let second = CodeBlock::new("let value = 2;".into(), Some("rust".into()), None::<Span>);
3099
3100        assert_ne!(first, second);
3101    }
3102
3103    #[cfg(feature = "tree-sitter")]
3104    #[test]
3105    fn code_block_highlighter_cache_refreshes_after_language_registration() {
3106        let lang = SharedString::from("json-cache-test");
3107        let theme = HighlightTheme::default_light();
3108
3109        CODE_BLOCK_HIGHLIGHTERS.with(|cache| {
3110            cache.borrow_mut().remove(&lang);
3111        });
3112
3113        let unknown_block =
3114            CodeBlock::new("{\"value\": 1}".into(), Some(lang.clone()), None::<Span>);
3115        _ = unknown_block.styles(&theme);
3116
3117        let cached_language = CODE_BLOCK_HIGHLIGHTERS.with(|cache| {
3118            cache
3119                .borrow()
3120                .get(&lang)
3121                .map(|highlighter| highlighter.language().clone())
3122        });
3123        assert_eq!(cached_language.as_deref(), Some("text"));
3124
3125        LanguageRegistry::singleton().register(
3126            lang.as_ref(),
3127            &crate::highlighter::LanguageConfig::new(
3128                lang.clone(),
3129                tree_sitter_json::LANGUAGE.into(),
3130                vec![],
3131                r#"
3132                    (string) @string
3133                    (number) @number
3134                    (pair key: (string) @property)
3135                "#,
3136                "",
3137                "",
3138            ),
3139        );
3140
3141        let registered_block =
3142            CodeBlock::new("{\"value\": 2}".into(), Some(lang.clone()), None::<Span>);
3143        _ = registered_block.styles(&theme);
3144
3145        let cached_language = CODE_BLOCK_HIGHLIGHTERS.with(|cache| {
3146            cache
3147                .borrow()
3148                .get(&lang)
3149                .map(|highlighter| highlighter.language().clone())
3150        });
3151        assert_eq!(cached_language.as_deref(), Some(lang.as_ref()));
3152    }
3153
3154    #[cfg(feature = "tree-sitter")]
3155    #[test]
3156    fn code_block_styles_follow_the_current_highlight_theme() {
3157        let lang = SharedString::from("json-theme-cache-test");
3158        let light_theme = HighlightTheme::default_light();
3159        let dark_theme = HighlightTheme::default_dark();
3160        let code = SharedString::from(r#"{"value": 42}"#);
3161        let number_range = code.find("42").unwrap()..code.find("42").unwrap() + 2;
3162
3163        let light_number = light_theme.style("number").and_then(|style| style.color);
3164        let dark_number = dark_theme.style("number").and_then(|style| style.color);
3165        assert_ne!(
3166            light_number, dark_number,
3167            "the test themes must use different number colors"
3168        );
3169
3170        CODE_BLOCK_HIGHLIGHTERS.with(|cache| {
3171            cache.borrow_mut().remove(&lang);
3172        });
3173        LanguageRegistry::singleton().register(
3174            lang.as_ref(),
3175            &crate::highlighter::LanguageConfig::new(
3176                lang.clone(),
3177                tree_sitter_json::LANGUAGE.into(),
3178                vec![],
3179                "(number) @number",
3180                "",
3181                "",
3182            ),
3183        );
3184
3185        let block = CodeBlock::new(code.clone(), Some(lang), None::<Span>);
3186        let light_styles = block.styles(&light_theme);
3187        let cached_light_theme = cached_highlight_theme(&block).unwrap();
3188        assert!(Arc::ptr_eq(&cached_light_theme, &light_theme));
3189
3190        let equivalent_light_theme = Arc::new(light_theme.as_ref().clone());
3191        let repeated_light_styles = block.styles(&equivalent_light_theme);
3192        assert_eq!(repeated_light_styles, light_styles);
3193        assert!(
3194            Arc::ptr_eq(
3195                &cached_highlight_theme(&block).unwrap(),
3196                &equivalent_light_theme
3197            ),
3198            "an equivalent replacement should become the cache identity"
3199        );
3200        assert_eq!(block.styles(&equivalent_light_theme), light_styles);
3201
3202        let dark_styles = block.styles(&dark_theme);
3203        assert_eq!(
3204            cached_highlight_theme(&block).as_deref(),
3205            Some(dark_theme.as_ref())
3206        );
3207
3208        let color_for_number = |styles: &[(Range<usize>, HighlightStyle)]| -> Option<Hsla> {
3209            styles
3210                .iter()
3211                .find(|(range, _)| {
3212                    range.start <= number_range.start && range.end >= number_range.end
3213                })
3214                .and_then(|(_, style)| style.color)
3215        };
3216
3217        assert_eq!(color_for_number(&light_styles), light_number);
3218        assert_eq!(
3219            color_for_number(&dark_styles),
3220            dark_number,
3221            "a theme change must not reuse syntax styles from the previous theme"
3222        );
3223    }
3224
3225    #[cfg(feature = "tree-sitter")]
3226    #[gpui::test]
3227    fn rendered_markdown_code_block_follows_theme_without_reparsing(cx: &mut TestAppContext) {
3228        struct CodeBlockThemeRoot {
3229            text_view: Entity<TextViewState>,
3230        }
3231
3232        impl Render for CodeBlockThemeRoot {
3233            fn render(
3234                &mut self,
3235                _window: &mut Window,
3236                _cx: &mut Context<Self>,
3237            ) -> impl IntoElement {
3238                div().w(px(480.)).child(TextView::new(&self.text_view))
3239            }
3240        }
3241
3242        let lang = SharedString::from("json-theme-render-test");
3243        LanguageRegistry::singleton().register(
3244            lang.as_ref(),
3245            &crate::highlighter::LanguageConfig::new(
3246                lang.clone(),
3247                tree_sitter_json::LANGUAGE.into(),
3248                vec![],
3249                "(number) @number",
3250                "",
3251                "",
3252            ),
3253        );
3254
3255        cx.update(crate::init);
3256        let markdown = format!("```{lang}\n{{\"value\": 42}}\n```");
3257        let (view, cx) = cx.add_window_view(|_, cx| CodeBlockThemeRoot {
3258            text_view: cx.new(|cx| TextViewState::markdown(&markdown, cx)),
3259        });
3260        let cx: &mut VisualTestContext = cx;
3261
3262        cx.run_until_parked();
3263        cx.update(|window, cx| {
3264            let _ = window.draw(cx);
3265        });
3266
3267        let light_theme = cx.update(|_, cx| cx.theme().highlight_theme.clone());
3268        let light_block = view.read_with(cx, |root, cx| {
3269            let state = root.text_view.read(cx);
3270            let BlockNode::CodeBlock(block) = &state.parsed_content.document.blocks[0] else {
3271                panic!("expected a code block");
3272            };
3273
3274            block.clone()
3275        });
3276        let cached_light_theme = cached_highlight_theme(&light_block)
3277            .expect("initial render should populate the highlight cache");
3278        assert_eq!(cached_light_theme.as_ref(), light_theme.as_ref());
3279
3280        cx.update(|window, cx| {
3281            Theme::change(ThemeMode::Dark, Some(&mut *window), cx);
3282            let _ = window.draw(cx);
3283        });
3284
3285        let dark_theme = cx.update(|_, cx| cx.theme().highlight_theme.clone());
3286        let dark_block = view.read_with(cx, |root, cx| {
3287            let state = root.text_view.read(cx);
3288            let BlockNode::CodeBlock(block) = &state.parsed_content.document.blocks[0] else {
3289                panic!("expected a code block");
3290            };
3291
3292            block.clone()
3293        });
3294        let cached_dark_theme = cached_highlight_theme(&dark_block)
3295            .expect("theme-change render should refresh the highlight cache");
3296
3297        assert_ne!(
3298            light_theme.as_ref(),
3299            dark_theme.as_ref(),
3300            "the test themes must have distinct highlight palettes"
3301        );
3302        assert!(
3303            Arc::ptr_eq(&dark_block.styles, &light_block.styles),
3304            "changing the theme must not require reparsing the Markdown document"
3305        );
3306        assert_eq!(cached_dark_theme.as_ref(), dark_theme.as_ref());
3307    }
3308}