Skip to main content

gpui_base/text/
state.rs

1use futures::Stream as _;
2#[cfg(not(target_family = "wasm"))]
3use std::time::Instant;
4use std::{
5    ops::{Range, RangeInclusive},
6    pin::Pin,
7    rc::Rc,
8    sync::{Arc, Mutex, OnceLock},
9    task::Poll,
10    time::Duration,
11};
12#[cfg(target_family = "wasm")]
13use web_time::Instant;
14
15use gpui::{
16    App, AppContext as _, Bounds, Context, CursorStyle, EntityId, FocusHandle, IntoElement,
17    KeyBinding, ListState, ParentElement as _, Pixels, Point, Render, SharedString, Styled as _,
18    Task, Window, prelude::FluentBuilder as _, px,
19};
20
21use crate::{
22    AutoScroll, ElementExt, TextSelection,
23    async_util::{Receiver, Sender, unbounded},
24    input::{self, SelectAll, a11y_text::A11yTextRuns},
25    text::{
26        CodeBlockActionsFn, CodeBlockHighlighterFn, LinkClickHandlerFn, LinkFn, MarkdownExtensions,
27        RangeHighlight, RangeHighlightError, RenderedText, TableActionsFn, TaskToggleHandlerFn,
28        TextViewStyle,
29        document::ParsedDocument,
30        format,
31        node::{self, NodeContext},
32        range_highlight::{
33            LeafRemap, PendingReveal, RangeHighlightFrame, RenderedIndex, RevealRequest,
34        },
35        selection_adapter::TextViewSelectionAdapter,
36        stream_fade::{StreamFadeTracker, TextViewMotion},
37    },
38    touch_selection::caret_line_box,
39    v_flex,
40};
41
42const CONTEXT: &'static str = "TextView";
43// Keep coalescing bounded so sustained streams still render intermediate updates.
44const MAX_COALESCED_UPDATES_PER_PARSE: usize = 64;
45// Preserve exact first-layout height for small documents while bounding the
46// amount of source parsed synchronously on the UI thread.
47const MAX_SYNC_FULL_REPLACE_BYTES: usize = 4 * 1024;
48// Repaint a streamed fade at about 30 fps, not at the display refresh rate.
49const STREAM_FADE_TICK: Duration = Duration::from_millis(33);
50
51pub(crate) fn init(cx: &mut App) {
52    cx.bind_keys(vec![
53        #[cfg(target_os = "macos")]
54        KeyBinding::new("cmd-c", input::Copy, Some(CONTEXT)),
55        #[cfg(not(target_os = "macos"))]
56        KeyBinding::new("ctrl-c", input::Copy, Some(CONTEXT)),
57        #[cfg(target_os = "macos")]
58        KeyBinding::new("cmd-a", input::SelectAll, Some(CONTEXT)),
59        #[cfg(not(target_os = "macos"))]
60        KeyBinding::new("ctrl-a", input::SelectAll, Some(CONTEXT)),
61    ]);
62}
63
64/// The content format of the text view.
65#[derive(Clone, Copy, PartialEq, Eq)]
66pub(super) enum TextViewFormat {
67    /// Markdown view
68    Markdown,
69    /// HTML view
70    Html,
71}
72
73/// The format of the text returned by
74/// [`TextViewState::selected_text`], which is also what copy writes to the
75/// clipboard.
76#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
77pub enum SelectionFormat {
78    /// The rendered text, without any markup.
79    #[default]
80    Plain,
81    /// The source of the selection.
82    ///
83    /// Select-all returns the original source verbatim, a partial selection is
84    /// reconstructed as Markdown from the parsed nodes (e.g. selecting inside
85    /// a `**bold**` run yields `**bold**`).
86    Source,
87    /// The rendered text while the selection stays within one style, the
88    /// source as soon as it takes in several.
89    ///
90    /// A style is everything the source would spell out around the selected
91    /// text: the marks of an inline run (emphasis, code, a link's URL) and the
92    /// block it sits in (a heading's `#`, a list marker, a code fence). So
93    /// selecting inside a `**bold**` run, a link or a code block yields the
94    /// text alone, also when the selection reaches exactly up to the run's
95    /// boundaries, while a selection across that boundary, into a second
96    /// block, or over an inline object copies like [`Self::Source`]. Two blocks
97    /// count as two styles even when their marks match, since the source of
98    /// either spells out where one ends. Select-all copies the source verbatim.
99    SourceAcrossStyles,
100}
101
102/// One text element's laid-out vertical extent, reported by `Inline` during
103/// prepaint so `TextView` can snap its `max_lines` clip to a whole-line
104/// boundary.
105#[derive(Clone, Copy)]
106pub(super) struct LineSpan {
107    pub(super) top: Pixels,
108    pub(super) bottom: Pixels,
109    pub(super) line_height: Pixels,
110}
111
112/// The state of a TextView.
113pub struct TextViewState {
114    entity_id: EntityId,
115    pub(super) focus_handle: FocusHandle,
116    pub(super) list_state: ListState,
117
118    /// The bounds of the text view
119    bounds: Bounds<Pixels>,
120
121    pub(super) selectable: bool,
122    /// The cursor set on the [`super::TextView`] itself; when set, it replaces
123    /// the I-beam over selectable text except mid-drag.
124    pub(super) hover_cursor: Option<CursorStyle>,
125    pub(super) selection_format: SelectionFormat,
126    pub(super) scrollable: bool,
127    pub(super) max_lines: Option<usize>,
128    /// Line spans reported by `Inline` during prepaint (collected only while
129    /// [`Self::max_lines`] is set); cleared by `TextView` at each frame start.
130    pub(super) line_spans: Arc<Mutex<Vec<LineSpan>>>,
131    /// Whether the last painted frame clipped content due to `max_lines`.
132    pub(super) clamped: bool,
133    pub(super) text_view_style: Arc<TextViewStyle>,
134    pub(super) code_block_actions: Option<std::sync::Arc<CodeBlockActionsFn>>,
135    pub(super) code_block_highlighter: Option<std::sync::Arc<CodeBlockHighlighterFn>>,
136    pub(super) table_actions: Option<std::sync::Arc<TableActionsFn>>,
137    pub(super) image_source: Option<std::sync::Arc<super::text_view::ImageSourceFn>>,
138    pub(super) link_click_handler: Option<std::sync::Arc<LinkClickHandlerFn>>,
139    pub(super) link_hook: Option<std::sync::Arc<LinkFn>>,
140    pub(super) link_tooltip: Option<std::sync::Arc<super::text_view::LinkTooltipFn>>,
141    pub(super) hovered_link_tooltip: Option<(SharedString, gpui::AnyView)>,
142    /// The link under the pointer and the rendering it is in. Two renderings
143    /// of one document share a paragraph's state, so its key alone does not
144    /// tell them apart; their bounds do.
145    pub(super) link_tooltip_target: Option<((usize, Bounds<gpui::Pixels>), SharedString)>,
146    pub(super) task_toggle_handler: Option<std::sync::Arc<TaskToggleHandlerFn>>,
147    pub(super) markdown_extensions: Arc<MarkdownExtensions>,
148
149    pub(super) is_selecting: bool,
150    /// Logical ranges retained across compatible resource or presentation reflow.
151    pub(super) preserve_inline_selection: bool,
152    multi_click_selection: Option<TextViewMultiClickSelection>,
153    selected_text_override: Option<String>,
154    select_all: bool,
155    /// The last text runs built for the accessibility tree, with the
156    /// (revision, select-all, scale) they were built for.
157    a11y_text_runs: Option<((usize, bool, f32), Rc<A11yTextRuns>)>,
158    pub(super) auto_scroll: AutoScroll,
159    pub(super) selection_adapter: TextViewSelectionAdapter,
160
161    pub(super) parsed_content: ParsedContent,
162    pub(super) stream_fade: StreamFadeTracker,
163    fade_tick: Option<Task<()>>,
164    /// Content format (markdown / html), used for bounded synchronous parsing
165    /// of small full-replace updates.
166    format: TextViewFormat,
167    text: String,
168    /// The text a `TextView` element last handed over, to recognize the same
169    /// string next frame without comparing its bytes.
170    element_text: Option<SharedString>,
171    revision: usize,
172    /// The revision of the update `parsed_content` was committed from.
173    committed_revision: usize,
174    /// The revision of the last update that replaced the text rather than
175    /// appending to it.
176    full_update_revision: usize,
177    /// The rendered text of `parsed_content`, built when first read.
178    rendered_index: Arc<OnceLock<RenderedIndex>>,
179    range_highlights: Option<Arc<RangeHighlightFrame>>,
180    pub(super) pending_reveal: Option<PendingReveal>,
181    pub(super) selection_revision: usize,
182    compatible_layout_update: bool,
183    layout_text_style: Option<(gpui::TextStyle, Pixels)>,
184    parsed_error: Option<SharedString>,
185    tx: Sender<UpdateOptions>,
186    _parse_task: Task<()>,
187    _receive_task: Task<()>,
188}
189
190impl TextViewState {
191    /// Create a Markdown TextViewState.
192    pub fn markdown(text: &str, cx: &mut Context<Self>) -> Self {
193        Self::new(TextViewFormat::Markdown, text, cx)
194    }
195
196    /// Create a HTML TextViewState.
197    pub fn html(text: &str, cx: &mut Context<Self>) -> Self {
198        Self::new(TextViewFormat::Html, text, cx)
199    }
200
201    /// Create a new TextViewState.
202    fn new(format: TextViewFormat, text: &str, cx: &mut Context<Self>) -> Self {
203        let focus_handle = cx.focus_handle();
204        let selection_adapter = TextViewSelectionAdapter::new(cx.entity().downgrade(), cx);
205
206        let (tx, rx) = unbounded::<UpdateOptions>();
207        let (tx_result, rx_result) = unbounded::<ParsedUpdate>();
208        let _receive_task = cx.spawn({
209            async move |weak_self, cx| {
210                while let Ok(parsed_update) = rx_result.recv().await {
211                    // A result that commits nothing — the background parser
212                    // acknowledging a synchronous parse — leaves the state
213                    // alone: updating it would tell GPUI Fast's retained
214                    // views that read it that it changed.
215                    let Ok(commits) =
216                        weak_self.read_with(cx, |state, _| state.commits(&parsed_update))
217                    else {
218                        break;
219                    };
220                    if !commits {
221                        continue;
222                    }
223                    _ = weak_self.update(cx, |state, cx| {
224                        state.commit_parsed_update(parsed_update, cx);
225                    });
226                }
227            }
228        });
229
230        let _parse_task = cx.background_spawn(UpdateFuture::new(format, rx, tx_result));
231
232        let mut this = Self {
233            entity_id: cx.entity_id(),
234            focus_handle,
235            bounds: Bounds::default(),
236            multi_click_selection: None,
237            selected_text_override: None,
238            select_all: false,
239            a11y_text_runs: None,
240            selectable: false,
241            hover_cursor: None,
242            selection_format: SelectionFormat::default(),
243            scrollable: false,
244            max_lines: None,
245            line_spans: Arc::default(),
246            clamped: false,
247            // Measure all blocks (not just visible ones) so the scrollbar
248            // thumb size stays stable. Without this, off-screen blocks count
249            // as zero height until scrolled into view, which makes the
250            // scrollbar jitter as more blocks get measured during scrolling.
251            list_state: ListState::new(0, gpui::ListAlignment::Top, px(1000.)).measure_all(),
252            text_view_style: Arc::default(),
253            code_block_actions: None,
254            code_block_highlighter: None,
255            table_actions: None,
256            link_click_handler: None,
257            link_hook: None,
258            link_tooltip: None,
259            hovered_link_tooltip: None,
260            link_tooltip_target: None,
261            task_toggle_handler: None,
262            image_source: None,
263            markdown_extensions: Arc::default(),
264            is_selecting: false,
265            preserve_inline_selection: false,
266            auto_scroll: AutoScroll::default(),
267            selection_adapter,
268            parsed_content: Default::default(),
269            stream_fade: StreamFadeTracker::default(),
270            fade_tick: None,
271            format,
272            parsed_error: None,
273            text: text.to_string(),
274            element_text: None,
275            revision: 0,
276            committed_revision: 0,
277            full_update_revision: 0,
278            rendered_index: Arc::default(),
279            range_highlights: None,
280            pending_reveal: None,
281            selection_revision: 0,
282            compatible_layout_update: false,
283            layout_text_style: None,
284            tx,
285            _parse_task,
286            _receive_task,
287        };
288        this.increment_update(&text, false, cx);
289        this
290    }
291
292    /// Get the text content.
293    pub(crate) fn source(&self) -> SharedString {
294        self.parsed_content.document.source.clone()
295    }
296
297    /// Set whether the text is selectable, default false.
298    pub fn selectable(mut self, selectable: bool) -> Self {
299        self.selectable = selectable;
300        self
301    }
302
303    /// Set whether the text is selectable, default false.
304    pub fn set_selectable(&mut self, selectable: bool, cx: &mut Context<Self>) {
305        self.selectable = selectable;
306        cx.notify();
307    }
308
309    /// Set the [`SelectionFormat`], default is [`SelectionFormat::Plain`].
310    pub fn selection_format(mut self, selection_format: SelectionFormat) -> Self {
311        self.selection_format = selection_format;
312        self
313    }
314
315    /// Set the [`SelectionFormat`], default is [`SelectionFormat::Plain`].
316    pub fn set_selection_format(
317        &mut self,
318        selection_format: SelectionFormat,
319        cx: &mut Context<Self>,
320    ) {
321        self.selection_format = selection_format;
322        cx.notify();
323    }
324
325    /// Set whether the text view scrolls internally, default false.
326    pub fn scrollable(mut self, scrollable: bool) -> Self {
327        self.scrollable = scrollable;
328        self
329    }
330
331    /// Set whether the text view scrolls internally, default false.
332    pub fn set_scrollable(&mut self, scrollable: bool, cx: &mut Context<Self>) {
333        if !scrollable {
334            self.reset_selection_and_adapter(cx);
335        }
336        self.scrollable = scrollable;
337        cx.notify();
338    }
339
340    /// Whether the last painted frame clipped content because of
341    /// [`TextView::max_lines`](crate::text::TextView::max_lines).
342    pub fn is_clamped(&self) -> bool {
343        self.clamped
344    }
345
346    /// Set the text content.
347    ///
348    /// Markdown that extends the current non-empty text is appended like
349    /// [`Self::push_str`], keeping the selection; any other text replaces it.
350    /// With a streamed fade-in enabled, extended text fades in; a replacement
351    /// shows at once.
352    pub fn set_text(&mut self, text: &str, cx: &mut Context<Self>) {
353        if self.text.as_str() == text {
354            return;
355        }
356        // HTML blocks carry no spans, so an append would parse the delta as a
357        // standalone document. After a failed parse the background parser's
358        // document lacks that text, so only a full parse resynchronizes it.
359        if self.format == TextViewFormat::Markdown
360            && self.parsed_error.is_none()
361            && !self.text.is_empty()
362            && let Some(delta) = text.strip_prefix(self.text.as_str())
363        {
364            self.push_str(delta, cx);
365            return;
366        }
367        self.stream_fade.note_replace();
368
369        self.text.clear();
370        self.text.push_str(text);
371        self.parsed_error = None;
372        self.increment_update(text, false, cx);
373    }
374
375    /// [`Self::set_text`] for the text a `TextView` element hands over every
376    /// frame: the string it handed over last time (the same allocation, not
377    /// merely equal bytes) is recognized without a comparison, as long as the
378    /// state still holds a text of its length.
379    pub(super) fn set_element_text(&mut self, text: &SharedString, cx: &mut Context<Self>) {
380        let same_string = self.element_text.as_ref().is_some_and(|current| {
381            current.as_ptr() == text.as_ptr() && current.len() == text.len()
382        });
383        if same_string && self.text.len() == text.len() {
384            return;
385        }
386        self.element_text = Some(text.clone());
387        self.set_text(text, cx);
388    }
389
390    /// Append partial text content to the existing text.
391    pub fn push_str(&mut self, new_text: &str, cx: &mut Context<Self>) {
392        if new_text.is_empty() {
393            return;
394        }
395        self.stream_fade.note_extend(self.text.len());
396        self.text.push_str(new_text);
397        self.increment_update(new_text, true, cx);
398    }
399
400    /// Set the motion policy; see [`TextViewMotion`].
401    pub fn motion(mut self, motion: TextViewMotion) -> Self {
402        self.set_motion(motion);
403        self
404    }
405
406    /// Set the motion policy; see [`TextViewMotion`].
407    pub fn set_motion(&mut self, motion: TextViewMotion) {
408        self.stream_fade.set_motion(motion);
409    }
410
411    pub(crate) fn set_markdown_extensions(
412        &mut self,
413        markdown_extensions: Arc<MarkdownExtensions>,
414        cx: &mut Context<Self>,
415    ) {
416        if self.markdown_extensions.revision() == markdown_extensions.revision() {
417            return;
418        }
419
420        let parser_configuration_changed = !self
421            .markdown_extensions
422            .has_same_parser_configuration(&markdown_extensions);
423        self.markdown_extensions = markdown_extensions;
424        if parser_configuration_changed && self.format == TextViewFormat::Markdown {
425            let text = self.text.clone();
426            self.increment_update(&text, false, cx);
427        }
428    }
429
430    /// Return the selected text, in the view's [`SelectionFormat`].
431    pub fn selected_text(&self) -> String {
432        self.selected_text_in(None)
433    }
434
435    /// Return the original Markdown source byte range corresponding to the
436    /// rendered selection.
437    ///
438    /// The range addresses the source passed to this Markdown TextView. It is
439    /// derived from parser positions retained by the rendered inline nodes, so
440    /// identical rendered text maps to the occurrence that was actually
441    /// selected. The result is one contiguous source range, so it includes any
442    /// Markdown delimiters between the selected rendered endpoints. HTML views
443    /// and selections without an exact source mapping return `None`. Select-all
444    /// in a Markdown view returns the full source range.
445    pub fn selected_source_range(&self) -> Option<Range<usize>> {
446        if self.format != TextViewFormat::Markdown {
447            return None;
448        }
449        if self.select_all {
450            return Some(0..self.source().len());
451        }
452        self.parsed_content.document.selected_source_range()
453    }
454
455    /// The format to copy in, which is [`SelectionFormat::Plain`] whenever the
456    /// requested one cannot be produced.
457    ///
458    /// Only a Markdown view can return source. Reconstructing HTML would mean
459    /// spelling every attribute back out — a mark's color, an image's
460    /// dimensions, a cell's alignment — with a new way to lose one at each
461    /// step, and html5ever records no source offsets to fall back on (it
462    /// reports only line numbers), so there is no original text to copy from
463    /// either.
464    fn effective_format(&self) -> SelectionFormat {
465        match self.format {
466            TextViewFormat::Markdown => self.selection_format,
467            TextViewFormat::Html => SelectionFormat::Plain,
468        }
469    }
470
471    /// A pending full replacement leaves the previous document on screen, but
472    /// that document must no longer supply clipboard content.
473    pub(super) fn has_current_copy_document(&self) -> bool {
474        self.committed_revision >= self.full_update_revision
475    }
476
477    /// Return the selected text, with `blocks` bounding which top-level blocks
478    /// the selection covers.
479    ///
480    /// The range comes from the selection endpoints, which know their block
481    /// even after it scrolls out of view; see
482    /// [`ParsedDocument::selected_text`](crate::text::document::ParsedDocument).
483    pub(super) fn selected_text_in(&self, blocks: Option<RangeInclusive<usize>>) -> String {
484        let format = self.effective_format();
485
486        if self.select_all {
487            if format != SelectionFormat::Plain {
488                return self.source().to_string();
489            }
490
491            return self.parsed_content.document.text();
492        }
493
494        // A multi-click stores the plain text it selected, which is a shortcut
495        // past the block walk. Source mode cannot take it: the word it stored
496        // has lost its markup. The click also set the inline selection it came
497        // from, so the walk reconstructs the same range with the markup intact.
498        if format == SelectionFormat::Plain
499            && let Some(text) = &self.selected_text_override
500        {
501            return text.clone();
502        }
503
504        self.parsed_content.document.selected_text(format, blocks)
505    }
506
507    /// Force a full re-measure of the block list after the document has been
508    /// replaced.
509    ///
510    /// `Document::render_root` only calls `ListState::reset` when the block
511    /// *count* changes, and the full-measure pass enabled by `measure_all` is
512    /// a one-shot latch that only `reset`, `remeasure_items`, or a width
513    /// change re-arms. Replacing a document with one that happens to have the
514    /// same number of blocks therefore leaves every cached height belonging to
515    /// the *previous* document. The list summary height stays wrong, and since
516    /// the wheel clamps against that summary, the blocks past the false bottom
517    /// can never scroll into view to be re-measured -- the clamp seals itself.
518    ///
519    /// `remeasure_items` re-arms the latch and marks the items unmeasured
520    /// while keeping their old sizes as hints, so the scrollbar does not
521    /// collapse in the frame before the next layout measures the real heights.
522    fn invalidate_measured_heights(&self) {
523        let count = self.list_state.item_count();
524        if count > 0 {
525            self.list_state.remeasure_items(0..count);
526        }
527    }
528
529    /// Remeasure inline resources after their prepared content or metrics change.
530    ///
531    /// Call from the resource owner's completion handler, through a weak entity
532    /// when the task can outlive this view. This does not reparse the document.
533    /// Existing logical selection is retained until the next selection gesture.
534    pub fn invalidate_inline_layout(&mut self, cx: &mut Context<Self>) {
535        self.preserve_selection_for_reflow();
536        cx.notify();
537    }
538
539    pub(super) fn preserve_selection_for_reflow(&mut self) {
540        self.preserve_inline_selection = true;
541        self.compatible_layout_update = true;
542        self.invalidate_measured_heights();
543    }
544
545    fn increment_update(&mut self, text: &str, append: bool, cx: &mut Context<Self>) {
546        self.revision += 1;
547        if !append {
548            self.full_update_revision = self.revision;
549            self.selection_revision = self.selection_revision.wrapping_add(1);
550            // Old native layouts must not project a still-active gesture back
551            // into replaced content, including while a large parse is pending.
552            self.selection_adapter.clear_copy_projections(cx);
553            self.parsed_content.document.clear_selection();
554        }
555        let parse_synchronously = !append && text.len() <= MAX_SYNC_FULL_REPLACE_BYTES;
556        let update_options = UpdateOptions {
557            revision: self.revision,
558            append,
559            mode: if append {
560                ParseMode::Compatible
561            } else if parse_synchronously {
562                ParseMode::BaselineAck
563            } else {
564                ParseMode::Replace
565            },
566            pending_text: text.to_string(),
567            markdown_extensions: self.markdown_extensions.clone(),
568        };
569
570        // Keep small full replacements synchronous so their first layout has
571        // the exact content height. Larger replacements use the existing
572        // background parser, bounding synchronous parser input on the UI thread.
573        if parse_synchronously {
574            match parse_content(self.format, ParsedContent::default(), &update_options) {
575                Ok(content) => {
576                    self.reconcile_range_highlights(&content.document, self.revision, false);
577                    self.stream_fade.record(
578                        &self.parsed_content.document,
579                        &content.document,
580                        Instant::now(),
581                    );
582                    self.parsed_content = content;
583                    self.parsed_error = None;
584                    self.invalidate_measured_heights();
585                    if !self.is_selecting {
586                        self.reset_selection_and_adapter(cx);
587                    }
588                }
589                Err(err) => {
590                    self.stream_fade.discard_pending();
591                    self.parsed_error = Some(err);
592                }
593            }
594            // Keep the background parser's accumulated document in sync so a
595            // later append extends this baseline instead of parsing the delta
596            // as a standalone document.
597            _ = self.tx.try_send(update_options);
598            cx.notify();
599            return;
600        }
601
602        _ = self.tx.try_send(update_options);
603    }
604
605    /// Whether [`Self::commit_parsed_update`] commits `parsed_update`: it is
606    /// not older than what is committed or than the last replacement, nor
607    /// the background parser acknowledging a synchronous parse.
608    fn commits(&self, parsed_update: &ParsedUpdate) -> bool {
609        if parsed_update.revision < self.full_update_revision
610            || parsed_update.revision <= self.committed_revision
611        {
612            return false;
613        }
614        debug_assert!(!parsed_update.baseline_ack || parsed_update.full_parse);
615        !parsed_update.baseline_ack
616    }
617
618    /// Commit a result of the background parser.
619    ///
620    /// A stream that appends faster than a parse completes has always moved
621    /// past the revision the result was parsed from, so only discarding
622    /// results of an older revision would show nothing until the stream
623    /// stops. A result parsed since the text was last replaced is a prefix of
624    /// the current text and is committed; one from before that replacement,
625    /// or older than what is already committed, is discarded.
626    fn commit_parsed_update(&mut self, parsed_update: ParsedUpdate, cx: &mut Context<Self>) {
627        if !self.commits(&parsed_update) {
628            return;
629        }
630
631        match parsed_update.result {
632            Ok(content) => {
633                let append = parsed_update.selection_compatible && !parsed_update.full_parse;
634                if append && self.full_update_revision <= self.committed_revision {
635                    self.splice_appended_blocks(&content.document);
636                }
637                self.reconcile_range_highlights(&content.document, parsed_update.revision, append);
638                self.stream_fade.record(
639                    &self.parsed_content.document,
640                    &content.document,
641                    Instant::now(),
642                );
643                // This result may cover only part of the queued appends.
644                // Keep the uncommitted tail pending from this document's end,
645                // rather than consuming its fade with the earlier chunk.
646                if parsed_update.revision < self.revision {
647                    self.stream_fade.note_extend(content.document.source.len());
648                }
649                self.parsed_content = content;
650                self.parsed_error = None;
651                self.compatible_layout_update = parsed_update.selection_compatible;
652                if parsed_update.full_parse {
653                    self.invalidate_measured_heights();
654                }
655            }
656            Err(err) => {
657                self.stream_fade.discard_pending();
658                self.parsed_error = Some(err);
659            }
660        }
661        // Don't interrupt an active drag-selection; the stored
662        // positions remain valid for append-only updates and will
663        // self-correct on the next mouse-move event.
664        if !parsed_update.selection_compatible && !self.is_selecting {
665            self.reset_selection_and_adapter(cx);
666        }
667        cx.notify();
668    }
669
670    /// The text this view renders, which [`RangeHighlight`] ranges index.
671    ///
672    /// This is the string plain copy produces, as of the last parse that
673    /// landed; text set since then is not in it until its parse lands.
674    pub fn rendered_text(&self) -> RenderedText {
675        RenderedText::new(
676            self.entity_id,
677            self.committed_revision,
678            self.parsed_content.document.clone(),
679            self.rendered_index.clone(),
680        )
681    }
682
683    /// The rendered text as AccessKit text runs, so a screen reader can read the body.
684    ///
685    /// The runs follow [`Self::rendered_text`], which tracks the document as its parses land,
686    /// so text set or streamed in reaches the tree with the frame that shows it. A select-all
687    /// is reported as the selection; any other selection is not mapped yet, so the view
688    /// reports none rather than a wrong one.
689    ///
690    /// The runs are kept until the text, the select-all or the scale changes, so a long
691    /// document is not split into characters again on every frame.
692    pub(super) fn accessibility_text_runs(&mut self, scale: f32) -> Option<Rc<A11yTextRuns>> {
693        let key = (self.committed_revision, self.select_all, scale);
694        if let Some((cached, runs)) = &self.a11y_text_runs
695            && *cached == key
696        {
697            return Some(runs.clone());
698        }
699        let text = self.rendered_text();
700        let text = text.as_str();
701        let selection = self.select_all.then_some((0, text.len()));
702        let runs = Rc::new(A11yTextRuns::capture(text, selection, scale, |_| None)?);
703        self.a11y_text_runs = Some((key, runs.clone()));
704        Some(runs)
705    }
706
707    /// Replace the range highlights, whose ranges index the current rendered text.
708    ///
709    /// Compute ranges from the current [`Self::rendered_text`] and set them in
710    /// the same update. Search the new text again after its content changes.
711    /// Ranges of the Markdown source, such as [`Self::selected_source_range`]
712    /// returns, convert with [`RenderedText::range_for_source`].
713    /// A range crossing blocks paints in both, skipping their separator.
714    /// Text outside every block (separators, custom blocks, HTML blocks, and
715    /// inline objects) is left unpainted. Any invalid range rejects the set.
716    ///
717    /// Highlights follow unchanged text through updates. Text appended while
718    /// streaming keeps earlier highlights; after a table edit, cells in and
719    /// after the edited row lose theirs because cells are known by position.
720    /// Text backgrounds such as `<mark>` paint over a highlight; inline code
721    /// backgrounds paint under it.
722    pub fn set_range_highlights(
723        &mut self,
724        highlights: impl IntoIterator<Item = RangeHighlight>,
725        cx: &mut Context<Self>,
726    ) -> Result<(), RangeHighlightError> {
727        if self.format != TextViewFormat::Markdown {
728            return Err(RangeHighlightError::Unsupported);
729        }
730        let text = self.rendered_text();
731        self.range_highlights = RangeHighlightFrame::new(&text, highlights)?.map(Arc::new);
732        cx.notify();
733        Ok(())
734    }
735
736    /// Scroll the line `range` starts on into view, `range` indexing the
737    /// current rendered text, as with [`Self::set_range_highlights`].
738    ///
739    /// A [`Self::scrollable`] view scrolls itself. Otherwise the nearest
740    /// enclosing `gpui::list` scrolls, as long as the row holding the view is
741    /// laid out, so scroll to that row first when it may be off screen. Any
742    /// other scroll container scrolls through
743    /// [`TextView::on_reveal`](crate::text::TextView::on_reveal). An empty
744    /// range reveals the line of its position; a range in text that belongs
745    /// to no block's text, such as a custom block's, scrolls its whole block
746    /// into a scrollable view.
747    ///
748    /// Only the latest reveal is carried out. It follows the content as
749    /// [range highlights](Self::set_range_highlights) do, and it is dropped
750    /// when its text changes, when the view clamps its lines, or when it
751    /// cannot be shown within a second, so it never scrolls long after it
752    /// was asked for. A whole block taller than the view, scrolled to from
753    /// below, shows its end.
754    ///
755    /// Revealing is best effort: `Ok(())` means the range is valid for the
756    /// current text and the request was taken, not that the view has
757    /// scrolled. A dropped request is not reported.
758    pub fn reveal_range(
759        &mut self,
760        range: Range<usize>,
761        cx: &mut Context<Self>,
762    ) -> Result<(), RangeHighlightError> {
763        if self.format != TextViewFormat::Markdown {
764            return Err(RangeHighlightError::Unsupported);
765        }
766        let text = self.rendered_text();
767        if text.is_empty() && range == (0..0) {
768            // Nothing to reveal in an empty view.
769            self.pending_reveal = None;
770            return Ok(());
771        }
772        let now = cx.background_executor().now();
773        self.pending_reveal = Some(
774            PendingReveal::new(&text, &range, now).ok_or(RangeHighlightError::InvalidRange(0))?,
775        );
776        cx.notify();
777        Ok(())
778    }
779
780    /// Remove all range highlights.
781    pub fn clear_range_highlights(&mut self, cx: &mut Context<Self>) {
782        if self.range_highlights.take().is_some() {
783            cx.notify();
784        }
785    }
786
787    /// Carry the range highlights over to `new`, the document the update of
788    /// `revision` parsed, before it replaces the current one.
789    ///
790    /// `append` is whether that update parsed only appended text onto the
791    /// document before it. Only when no update has replaced the text since
792    /// the current document was committed was that document the current one,
793    /// so only then do the blocks before its last stay unchanged.
794    fn reconcile_range_highlights(&mut self, new: &ParsedDocument, revision: usize, append: bool) {
795        let tail_only = append && self.full_update_revision <= self.committed_revision;
796        self.committed_revision = revision;
797        self.rendered_index = Arc::default();
798        if self.range_highlights.is_some() || self.pending_reveal.is_some() {
799            let remap = LeafRemap::new(&self.parsed_content.document, new, tail_only);
800            self.range_highlights = self
801                .range_highlights
802                .take()
803                .and_then(|highlights| highlights.remap(&remap))
804                .map(Arc::new);
805            self.pending_reveal = self
806                .pending_reveal
807                .take()
808                .and_then(|reveal| reveal.remap(&remap));
809        }
810    }
811
812    /// Tell the scrollable list which blocks an append replaced, before `new`,
813    /// the appended document, replaces the current one.
814    ///
815    /// An append parses only the current document's last block again, so the
816    /// blocks before it keep their spans and their measured heights. Without
817    /// this, `render_root` resets the list whenever the block count changes,
818    /// which scrolled a streaming view back to the top and measured every
819    /// block again on each new block. Only a grown block count is handled
820    /// here; anything else is left to that reset.
821    fn splice_appended_blocks(&self, new: &ParsedDocument) {
822        let old = &self.parsed_content.document.blocks;
823        let (old_count, new_count) = (old.len(), new.blocks.len());
824        if old_count == 0 || new_count <= old_count || self.list_state.item_count() != old_count {
825            return;
826        }
827
828        // The last block is always measured again: it was parsed again, and
829        // it is no longer the last one.
830        let unchanged = old
831            .iter()
832            .zip(new.blocks.iter())
833            .take(old_count - 1)
834            .take_while(|(old_block, new_block)| {
835                old_block
836                    .span()
837                    .is_some_and(|span| new_block.span() == Some(span))
838            })
839            .count();
840        // Keeps the replaced blocks' heights as hints and the scroll offset
841        // inside them, and has the next layout measure only the blocks that
842        // are not measured.
843        self.list_state.remeasure_items(unchanged..old_count);
844        self.list_state
845            .splice(old_count..old_count, new_count - old_count);
846    }
847
848    /// Save bounds and unselect if bounds changed.
849    pub(super) fn update_bounds(&mut self, bounds: Bounds<Pixels>, _cx: &mut App) {
850        self.bounds = bounds;
851    }
852
853    /// The index of the top-level block at `content_y`, in this view's content
854    /// coordinates (the same space the base selection endpoint stores its point in).
855    ///
856    /// Only laid-out blocks can be located, which is enough for a selection
857    /// endpoint: the user can only put one where they can see it. Returns
858    /// `None` for a view that is not virtualized, where every block paints and
859    /// the range is not needed.
860    pub(super) fn block_ix_at(&self, content_y: Pixels) -> Option<usize> {
861        if !self.scrollable {
862            return None;
863        }
864
865        let origin = self.bounds.origin.y + self.scroll_offset().y;
866        let count = self.list_state.item_count();
867        let mut ix = self.list_state.logical_scroll_top().item_ix;
868        while ix < count {
869            let bounds = self.list_state.bounds_for_item(ix)?;
870            if content_y < bounds.bottom() - origin {
871                return Some(ix);
872            }
873            ix += 1;
874        }
875
876        count.checked_sub(1)
877    }
878
879    #[doc(hidden)]
880    pub fn bounds(&self) -> Bounds<Pixels> {
881        self.bounds
882    }
883
884    #[doc(hidden)]
885    pub fn list_state(&self) -> &ListState {
886        &self.list_state
887    }
888
889    #[doc(hidden)]
890    pub fn is_selecting(&self) -> bool {
891        self.is_selecting
892    }
893
894    #[doc(hidden)]
895    pub fn focus_handle(&self) -> &FocusHandle {
896        &self.focus_handle
897    }
898
899    /// Whether this view has a view-local selection (select-all, multi-click, or override),
900    /// independent of the window-level selection.
901    pub(super) fn has_view_selection(&self) -> bool {
902        self.select_all
903            || self.multi_click_selection.is_some()
904            || self.selected_text_override.is_some()
905    }
906
907    pub(super) fn stop_auto_scroll(&mut self) {
908        self.auto_scroll.stop();
909    }
910
911    pub(super) fn reset_selection(&mut self) {
912        self.preserve_inline_selection = false;
913        self.multi_click_selection = None;
914        self.selected_text_override = None;
915        self.select_all = false;
916        self.is_selecting = false;
917        self.auto_scroll.stop();
918        // Clear the inline selection state synchronously, so offscreen
919        // (virtualized) views that won't repaint don't leak stale selection
920        // text into a new cross-view copy.
921        self.parsed_content.document.clear_selection();
922    }
923
924    fn reset_selection_and_adapter(&mut self, cx: &mut App) {
925        self.reset_selection();
926        self.selection_adapter.set_local_selection(false, cx);
927    }
928
929    /// Clear the current text selection.
930    pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
931        self.reset_selection_and_adapter(cx);
932        cx.notify();
933    }
934
935    pub(super) fn scroll_offset(&self) -> Point<Pixels> {
936        if self.scrollable {
937            self.list_state.scroll_px_offset_for_scrollbar()
938        } else {
939            Point::default()
940        }
941    }
942
943    /// Select all rendered text in this view.
944    pub fn select_all(&mut self, cx: &mut Context<Self>) {
945        self.multi_click_selection = None;
946        self.selected_text_override = None;
947        self.select_all = true;
948        self.is_selecting = false;
949        self.auto_scroll.stop();
950        self.selection_adapter.set_local_selection(true, cx);
951        cx.notify();
952    }
953
954    /// Selects what a multi-click at `pos` selected, from the caret `start`
955    /// to the caret `end` in window coordinates. A drag from the click
956    /// extends it by the same unit.
957    pub(crate) fn set_multi_click_selection(
958        &mut self,
959        pos: Point<Pixels>,
960        kind: TextViewMultiClickKind,
961        selected_text: String,
962        (start, end): (Bounds<Pixels>, Bounds<Pixels>),
963        cx: &mut App,
964    ) {
965        self.preserve_inline_selection = false;
966        let scroll_offset = self.scroll_offset();
967        let pos = pos - self.bounds.origin - scroll_offset;
968        self.multi_click_selection = Some(TextViewMultiClickSelection {
969            pos,
970            kind,
971            line_bounds: None,
972        });
973        self.selected_text_override = Some(selected_text);
974        self.select_all = false;
975        self.is_selecting = false;
976        self.auto_scroll.stop();
977        self.selection_adapter.set_local_selection(true, cx);
978        let click_count = match kind {
979            TextViewMultiClickKind::Word => 2,
980            TextViewMultiClickKind::Paragraph | TextViewMultiClickKind::Line => 3,
981        };
982        self.selection_adapter
983            .hold_multi_click(start, end, click_count, cx);
984    }
985
986    /// Hands a multi-click selection over to the window selection, which a
987    /// drag from the click has taken beyond what the click selected.
988    pub(super) fn end_multi_click_selection(&mut self, cx: &mut App) {
989        if self.multi_click_selection.take().is_some() {
990            self.selected_text_override = None;
991            self.selection_adapter.set_local_selection(false, cx);
992        }
993    }
994
995    /// Selects every inline in `rows.bounds`, as a triple click on a
996    /// paragraph laid out as an inline flow does: from the start of its first
997    /// row to the end of its last row.
998    pub(crate) fn set_multi_click_line(&mut self, rows: ParagraphRows, cx: &mut App) {
999        let bounds = rows.bounds;
1000        self.set_multi_click_selection(
1001            bounds.center(),
1002            TextViewMultiClickKind::Line,
1003            String::new(),
1004            (
1005                caret_line_box(bounds.origin, rows.first_row_height),
1006                caret_line_box(
1007                    gpui::point(bounds.right(), bounds.bottom() - rows.last_row_height),
1008                    rows.last_row_height,
1009                ),
1010            ),
1011            cx,
1012        );
1013        self.selected_text_override = None;
1014        let offset = self.bounds.origin + self.scroll_offset();
1015        if let Some(selection) = self.multi_click_selection.as_mut() {
1016            selection.line_bounds = Some(Bounds::new(bounds.origin - offset, bounds.size));
1017        }
1018    }
1019
1020    pub(super) fn set_auto_scroll(&mut self, delta: Option<Pixels>, cx: &mut Context<Self>) {
1021        self.auto_scroll.set(delta, cx, |delta, state, cx| {
1022            state.list_state.scroll_by(delta);
1023            cx.notify();
1024        });
1025    }
1026
1027    /// Return the window selection (anchor, cursor) in window coordinates if
1028    /// this view participates in it.
1029    ///
1030    /// Single-view fast path: when both endpoints are anchored inside one
1031    /// TextView, only that view participates (identical to the previous
1032    /// per-view behavior).
1033    pub(crate) fn selection_points(&self, cx: &App) -> Option<(Point<Pixels>, Point<Pixels>)> {
1034        if !self.selectable {
1035            return None;
1036        }
1037        self.selection_adapter.selection_points(cx)
1038    }
1039
1040    /// [`Self::selection_points`] for the text that paints now: a drag that
1041    /// started in a table cell selects only in that cell. Call it only while
1042    /// painting, so the cell the text is in is known.
1043    pub(crate) fn painted_selection_points(
1044        &self,
1045        cx: &App,
1046    ) -> Option<(Point<Pixels>, Point<Pixels>)> {
1047        if !self.selectable {
1048            return None;
1049        }
1050        self.selection_adapter.painted_selection_points(cx)
1051    }
1052
1053    pub(crate) fn has_selection(&self, cx: &App) -> bool {
1054        self.has_view_selection() || self.selection_points(cx).is_some()
1055    }
1056
1057    pub(super) fn on_action_select_all(
1058        &mut self,
1059        _: &SelectAll,
1060        _: &mut Window,
1061        cx: &mut Context<Self>,
1062    ) {
1063        if !self.selectable {
1064            cx.propagate();
1065            return;
1066        }
1067
1068        self.select_all(cx);
1069    }
1070
1071    pub(crate) fn is_selectable(&self) -> bool {
1072        self.selectable
1073    }
1074
1075    /// Whether selectable text should show the I-beam now: always, unless the
1076    /// [`super::TextView`] sets its own cursor, then only mid-drag.
1077    pub(crate) fn shows_text_cursor(&self) -> bool {
1078        self.hover_cursor.is_none() || self.is_selecting
1079    }
1080
1081    pub(crate) fn is_all_selected(&self) -> bool {
1082        self.select_all
1083    }
1084
1085    pub(crate) fn multi_click_selection(&self) -> Option<TextViewMultiClickSelection> {
1086        let scroll_offset = self.scroll_offset();
1087        self.multi_click_selection.map(|selection| {
1088            let pos = selection.pos + scroll_offset + self.bounds.origin;
1089            let line_bounds = selection.line_bounds.map(|bounds| {
1090                Bounds::new(
1091                    bounds.origin + scroll_offset + self.bounds.origin,
1092                    bounds.size,
1093                )
1094            });
1095            TextViewMultiClickSelection {
1096                pos,
1097                line_bounds,
1098                ..selection
1099            }
1100        })
1101    }
1102}
1103
1104/// The rows a triple click selects as one paragraph: their union, and the
1105/// heights of the first and last rows for the selection's carets.
1106#[derive(Clone, Copy, Debug, PartialEq)]
1107pub(crate) struct ParagraphRows {
1108    pub(crate) bounds: Bounds<Pixels>,
1109    pub(crate) first_row_height: Pixels,
1110    pub(crate) last_row_height: Pixels,
1111}
1112
1113impl ParagraphRows {
1114    /// One row on its own.
1115    pub(crate) fn single(bounds: Bounds<Pixels>) -> Self {
1116        Self {
1117            bounds,
1118            first_row_height: bounds.size.height,
1119            last_row_height: bounds.size.height,
1120        }
1121    }
1122}
1123
1124#[derive(Clone, Copy, Debug, PartialEq)]
1125pub(crate) struct TextViewMultiClickSelection {
1126    pub(crate) pos: Point<Pixels>,
1127    pub(crate) kind: TextViewMultiClickKind,
1128    pub(crate) line_bounds: Option<Bounds<Pixels>>,
1129}
1130
1131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1132pub(crate) enum TextViewMultiClickKind {
1133    Word,
1134    Paragraph,
1135    Line,
1136}
1137
1138impl TextViewState {
1139    /// Starts a frame of the pending reveal: the line to hand to rendering,
1140    /// and the block a scrollable view has to scroll to first, because it is
1141    /// off screen or the reveal is of a whole block.
1142    fn reveal_frame(
1143        &mut self,
1144        now: Instant,
1145        window: &mut Window,
1146    ) -> (Option<RevealRequest>, Option<usize>) {
1147        if self.max_lines.is_some()
1148            || self
1149                .pending_reveal
1150                .as_ref()
1151                .is_some_and(|reveal| reveal.is_expired(now))
1152        {
1153            self.pending_reveal = None;
1154        }
1155        let Some(pending) = &self.pending_reveal else {
1156            return (None, None);
1157        };
1158
1159        let block_ix = pending.block_ix(&self.parsed_content.document);
1160        let block_off_screen = |ix: usize| {
1161            let viewport = self.list_state.viewport_bounds();
1162            self.list_state.bounds_for_item(ix).is_none_or(|item| {
1163                item.bottom() <= viewport.top() || item.top() >= viewport.bottom()
1164            })
1165        };
1166        let reveal_block = block_ix.filter(|ix| {
1167            self.scrollable
1168                && (pending.is_block() || !pending.was_laid_out())
1169                && block_off_screen(*ix)
1170        });
1171        let request = pending.request();
1172        if pending.is_block() {
1173            // A block has no line to wait for.
1174            self.pending_reveal = None;
1175        } else {
1176            window.request_animation_frame();
1177        }
1178        (request, reveal_block)
1179    }
1180}
1181
1182impl Render for TextViewState {
1183    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1184        let typography = (window.text_style(), window.rem_size());
1185        let body_font_size = typography.0.font_size.to_pixels(typography.1);
1186        if self
1187            .layout_text_style
1188            .as_ref()
1189            .is_some_and(|previous| previous != &typography)
1190        {
1191            // ListState invalidates its cached rows for width changes, but does
1192            // not know that an inherited font or rem change affects offscreen
1193            // inline metrics. Retain logical selections just as for resources.
1194            self.preserve_selection_for_reflow();
1195        }
1196        self.layout_text_style = Some(typography);
1197        let state = cx.entity();
1198        let stream_fade = self.stream_fade.frame(Instant::now(), cx.reduce_motion());
1199        if stream_fade.is_some() && self.fade_tick.is_none() {
1200            self.fade_tick = Some(cx.spawn(async move |this, cx| {
1201                cx.background_executor().timer(STREAM_FADE_TICK).await;
1202                _ = this.update(cx, |state, cx| {
1203                    state.fade_tick = None;
1204                    cx.notify();
1205                });
1206            }));
1207        }
1208        let (reveal, reveal_block) = self.reveal_frame(cx.background_executor().now(), window);
1209        // Built every frame, so everything in it is shared, not copied.
1210        let node_cx = NodeContext {
1211            offset: self.parsed_content.node_cx.offset,
1212            link_refs: self.parsed_content.node_cx.link_refs.clone(),
1213            style: self.text_view_style.clone(),
1214            code_block_actions: self.code_block_actions.clone(),
1215            code_block_highlighter: self.code_block_highlighter.clone(),
1216            table_actions: self.table_actions.clone(),
1217            link_click_handler: self.link_click_handler.clone(),
1218            link_hook: self.link_hook.clone(),
1219            task_toggle_handler: self.task_toggle_handler.clone(),
1220            image_source: self.image_source.clone(),
1221            markdown_extensions: self.markdown_extensions.clone(),
1222            stream_fade,
1223            range_highlights: self.range_highlights.clone(),
1224            foregrounds: Default::default(),
1225            reveal,
1226            body_font_size,
1227        };
1228
1229        let content = v_flex()
1230            .w_full()
1231            // Clamped content must keep its natural height: stretching it to
1232            // the capped box would hide the overflow the clamp has to measure.
1233            .when(self.max_lines.is_none(), |this| this.h_full())
1234            .map(|this| match &self.parsed_error {
1235                None => this.child(self.parsed_content.document.render_root(
1236                    if self.scrollable {
1237                        Some(self.list_state.clone())
1238                    } else {
1239                        None
1240                    },
1241                    &node_cx,
1242                    window,
1243                    cx,
1244                )),
1245                Some(err) => this.child(
1246                    v_flex()
1247                        .gap_1()
1248                        .child("Failed to parse content")
1249                        .child(err.to_string()),
1250                ),
1251            })
1252            .on_prepaint(move |bounds, window, cx| {
1253                let (
1254                    size_changed,
1255                    selection_involves_view,
1256                    has_selection_snapshot,
1257                    is_selecting,
1258                    compatible_layout_update,
1259                    preserve_width_selection,
1260                ) = {
1261                    let state = state.read(cx);
1262                    let has_selection_snapshot = state.selection_adapter.has_selection_snapshot(cx);
1263                    let preserve_width_selection = !state.is_selecting
1264                        && state.bounds().size.width != bounds.size.width
1265                        && (has_selection_snapshot || state.has_view_selection());
1266                    (
1267                        state.bounds().size != bounds.size,
1268                        state.selection_adapter.is_part_of_window_selection(cx),
1269                        has_selection_snapshot,
1270                        state.is_selecting,
1271                        // A measurement prepaint must not consume compatibility
1272                        // before the same entity's visible column prepaints.
1273                        state.compatible_layout_update
1274                            || preserve_width_selection
1275                            || state.preserve_inline_selection,
1276                        preserve_width_selection,
1277                    )
1278                };
1279                let mut revision_changed = false;
1280                state.update(cx, |state, cx| {
1281                    revision_changed = state
1282                        .selection_adapter
1283                        .update_layout_revision(state.selection_revision, state.is_selecting);
1284                    if preserve_width_selection {
1285                        // ListState already remeasures width changes. Arm logical
1286                        // retention before inline paint without invalidating rows again.
1287                        state.preserve_inline_selection = true;
1288                    }
1289                    state.update_bounds(bounds, cx);
1290                    state.compatible_layout_update = false;
1291                });
1292                if !is_selecting
1293                    && ((size_changed && selection_involves_view && !compatible_layout_update)
1294                        || (revision_changed && has_selection_snapshot))
1295                {
1296                    TextSelection::clear(window, cx);
1297                }
1298            });
1299        // After `render_root`, which resets the list when the block count
1300        // changed other than by an append, and with it the scroll position.
1301        if let Some(block_ix) = reveal_block {
1302            self.list_state.scroll_to_reveal_item(block_ix);
1303        }
1304        content
1305    }
1306}
1307
1308#[derive(Clone, PartialEq, Default)]
1309pub(crate) struct ParsedContent {
1310    pub(crate) document: ParsedDocument,
1311    pub(crate) node_cx: node::NodeContext,
1312}
1313
1314struct UpdateFuture {
1315    format: TextViewFormat,
1316    content: ParsedContent,
1317    rx: Pin<Box<Receiver<UpdateOptions>>>,
1318    tx_result: Sender<ParsedUpdate>,
1319}
1320
1321impl UpdateFuture {
1322    fn new(
1323        format: TextViewFormat,
1324        rx: Receiver<UpdateOptions>,
1325        tx_result: Sender<ParsedUpdate>,
1326    ) -> Self {
1327        Self {
1328            format,
1329            content: Default::default(),
1330            rx: Box::pin(rx),
1331            tx_result,
1332        }
1333    }
1334}
1335
1336impl Future for UpdateFuture {
1337    type Output = ();
1338
1339    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1340        loop {
1341            match self.rx.as_mut().poll_next(cx) {
1342                Poll::Ready(Some(mut options)) => {
1343                    let hit_coalesce_budget =
1344                        merge_pending_options(&mut options, self.rx.as_ref().get_ref());
1345
1346                    let res = parse_content(self.format, self.content.clone(), &options);
1347                    if let Ok(content) = &res {
1348                        self.content = content.clone();
1349                    }
1350                    _ = self.tx_result.try_send(ParsedUpdate {
1351                        revision: options.revision,
1352                        full_parse: !options.append,
1353                        selection_compatible: options.mode == ParseMode::Compatible,
1354                        baseline_ack: options.mode == ParseMode::BaselineAck,
1355                        result: res,
1356                    });
1357                    if hit_coalesce_budget {
1358                        cx.waker().wake_by_ref();
1359                        return Poll::Pending;
1360                    }
1361                    continue;
1362                }
1363                Poll::Ready(None) => return Poll::Ready(()),
1364                Poll::Pending => return Poll::Pending,
1365            }
1366        }
1367    }
1368}
1369
1370#[derive(Clone)]
1371struct UpdateOptions {
1372    revision: usize,
1373    pending_text: String,
1374    append: bool,
1375    mode: ParseMode,
1376    markdown_extensions: Arc<MarkdownExtensions>,
1377}
1378
1379impl UpdateOptions {
1380    fn merge(&mut self, next: UpdateOptions) {
1381        if next.append {
1382            self.pending_text.push_str(&next.pending_text);
1383            self.revision = next.revision;
1384            if self.mode != ParseMode::Replace {
1385                self.mode = ParseMode::Compatible;
1386            }
1387        } else {
1388            *self = next;
1389        }
1390    }
1391}
1392
1393struct ParsedUpdate {
1394    revision: usize,
1395    full_parse: bool,
1396    selection_compatible: bool,
1397    baseline_ack: bool,
1398    result: Result<ParsedContent, SharedString>,
1399}
1400
1401#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1402enum ParseMode {
1403    BaselineAck,
1404    Replace,
1405    Compatible,
1406}
1407
1408fn merge_pending_options(options: &mut UpdateOptions, rx: &Receiver<UpdateOptions>) -> bool {
1409    let mut update_count = 1;
1410
1411    while update_count < MAX_COALESCED_UPDATES_PER_PARSE {
1412        match rx.try_recv() {
1413            Ok(next_options) => {
1414                options.merge(next_options);
1415                update_count += 1;
1416            }
1417            Err(_) => return false,
1418        }
1419    }
1420
1421    true
1422}
1423
1424fn parse_content(
1425    format: TextViewFormat,
1426    mut content: ParsedContent,
1427    options: &UpdateOptions,
1428) -> Result<ParsedContent, SharedString> {
1429    let mut node_cx = NodeContext {
1430        markdown_extensions: options.markdown_extensions.clone(),
1431        ..NodeContext::default()
1432    };
1433
1434    // Re-parse the last block together with the appended text, so a block the
1435    // new text continues (an unclosed list, a fenced code block) is not split
1436    // in two. A block without a span cannot be located in `source` — the HTML
1437    // parser never records spans — so it is left in place and only the
1438    // appended text is parsed, positioned at the end of the current source.
1439    let last_span = options
1440        .append
1441        .then(|| {
1442            content
1443                .document
1444                .blocks
1445                .last()
1446                .and_then(|block| block.span())
1447        })
1448        .flatten();
1449
1450    let mut source = String::new();
1451    if let Some(span) = last_span {
1452        Arc::make_mut(&mut content.document.blocks).pop();
1453        node_cx.offset = span.start;
1454        source.push_str(&content.document.source[span.start..]);
1455        source.push_str(&options.pending_text);
1456    } else {
1457        if options.append {
1458            node_cx.offset = content.document.source.len();
1459        }
1460        source.push_str(&options.pending_text);
1461    }
1462
1463    let new_document = match format {
1464        TextViewFormat::Markdown => format::markdown::parse(&source, &mut node_cx),
1465        TextViewFormat::Html => format::html::parse(&source, &mut node_cx),
1466    }?;
1467
1468    if options.append {
1469        content.document.source =
1470            format!("{}{}", content.document.source, options.pending_text).into();
1471        Arc::make_mut(&mut content.document.blocks)
1472            .extend(Arc::unwrap_or_clone(new_document.blocks));
1473    } else {
1474        content.document = new_document;
1475    }
1476
1477    Ok(content)
1478}
1479
1480#[cfg(test)]
1481mod tests {
1482    use super::*;
1483    use crate::text::{
1484        MarkdownNode,
1485        node::{BlockNode, Span},
1486    };
1487    use gpui::{Entity, TestAppContext};
1488
1489    /// A view reading a text view state, inside a view notified on every
1490    /// frame, counting its renders.
1491    #[cfg(feature = "gpui-fast")]
1492    mod parse_ack {
1493        use std::{cell::Cell, rc::Rc};
1494
1495        use gpui::{
1496            AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
1497            TestAppContext, Window, div,
1498        };
1499
1500        use super::super::TextViewState;
1501
1502        struct Reader {
1503            state: Entity<TextViewState>,
1504            renders: Rc<Cell<usize>>,
1505        }
1506
1507        impl Render for Reader {
1508            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1509                self.renders.set(self.renders.get() + 1);
1510                div().child(self.state.read(cx).text.clone())
1511            }
1512        }
1513
1514        struct Holder {
1515            reader: Entity<Reader>,
1516        }
1517
1518        impl Render for Holder {
1519            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1520                div().child(self.reader.clone())
1521            }
1522        }
1523
1524        /// The background parser acknowledging a text parsed as it was set
1525        /// commits nothing, and leaves the state alone: a view that read it,
1526        /// in a view notified for something else, is not built again.
1527        #[gpui::test]
1528        fn acknowledging_a_parse_leaves_its_readers_retained(cx: &mut TestAppContext) {
1529            cx.update(crate::init);
1530            let renders = Rc::new(Cell::new(0));
1531            let (holder, cx) = cx.add_window_view(|_, cx| Holder {
1532                reader: cx.new(|cx| Reader {
1533                    state: cx.new(|cx| TextViewState::markdown("Some **text**.", cx)),
1534                    renders: renders.clone(),
1535                }),
1536            });
1537            cx.update(|window, cx| window.draw(cx).clear(cx));
1538            let before = renders.get();
1539            cx.run_until_parked();
1540            holder.update(cx, |_, cx| cx.notify());
1541            cx.update(|window, cx| window.draw(cx).clear(cx));
1542            assert_eq!(renders.get(), before, "the reader rendered again");
1543        }
1544    }
1545
1546    mod stream_fade {
1547        use std::{cell::Cell, ops::Range, rc::Rc, time::Duration};
1548
1549        use gpui::{Entity, TestAppContext};
1550
1551        use super::super::*;
1552        use crate::{motion::Easing, text::stream_fade::TextLeafKey};
1553
1554        /// Long enough that a debug test cannot outrun the fade before it
1555        /// samples the first frame.
1556        const FADE: Duration = Duration::from_secs(10);
1557
1558        fn fading_state(markdown: &str, cx: &mut TestAppContext) -> Entity<TextViewState> {
1559            cx.update(crate::init);
1560            let state = cx.update(|cx| {
1561                cx.new(|cx| {
1562                    TextViewState::markdown(markdown, cx).motion(
1563                        TextViewMotion::default()
1564                            .with_stream_fade(FADE)
1565                            .with_stream_fade_easing(Easing::Linear),
1566                    )
1567                })
1568            });
1569            cx.run_until_parked();
1570            state
1571        }
1572
1573        /// The fade ranges of `key` sampled right now, or `None` when the
1574        /// state has nothing fading.
1575        fn fades(
1576            state: &Entity<TextViewState>,
1577            key: TextLeafKey,
1578            cx: &mut TestAppContext,
1579        ) -> Option<Vec<Range<usize>>> {
1580            state.update(cx, |state, _| {
1581                let frame = state.stream_fade.frame(Instant::now(), false)?;
1582                let fades = frame.fades(key)?;
1583                assert!(
1584                    fades.iter().all(|(_, fade_out)| *fade_out > 0.9),
1585                    "a fade sampled right after it starts is still transparent: {fades:?}"
1586                );
1587                Some(fades.iter().map(|(range, _)| range.clone()).collect())
1588            })
1589        }
1590
1591        #[gpui::test]
1592        fn push_str_fades_only_the_appended_text(cx: &mut TestAppContext) {
1593            let state = fading_state("hello", cx);
1594            state.update(cx, |state, cx| state.push_str(" world", cx));
1595            cx.run_until_parked();
1596
1597            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..11]));
1598
1599            state.update(cx, |state, _| {
1600                let later = Instant::now() + FADE + Duration::from_secs(1);
1601                assert!(state.stream_fade.frame(later, false).is_none());
1602                assert!(state.stream_fade.frame(Instant::now(), false).is_none());
1603            });
1604        }
1605
1606        #[gpui::test]
1607        fn overtaken_parse_preserves_the_remaining_chunks_fade(cx: &mut TestAppContext) {
1608            let state = fading_state("hello", cx);
1609            let parsed = super::push_and_parse(&state, " one", cx);
1610            state.update(cx, |state, cx| {
1611                state.push_str(" two", cx);
1612                state.commit_parsed_update(parsed, cx);
1613            });
1614            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..9]));
1615
1616            cx.run_until_parked();
1617            assert_eq!(
1618                fades(&state, TextLeafKey::block(0), cx),
1619                Some(vec![5..9, 9..13])
1620            );
1621        }
1622
1623        #[gpui::test]
1624        fn overtaken_parse_preserves_a_remaining_blocks_fade(cx: &mut TestAppContext) {
1625            let state = fading_state("hello", cx);
1626            let parsed = super::push_and_parse(&state, " one", cx);
1627            state.update(cx, |state, cx| {
1628                state.push_str("\n\nsecond", cx);
1629                state.commit_parsed_update(parsed, cx);
1630            });
1631            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..9]));
1632
1633            // A third chunk arrives while the second is still uncommitted.
1634            state.update(cx, |state, cx| state.push_str(" third", cx));
1635            cx.run_until_parked();
1636            let ranges = fades(&state, TextLeafKey::block(11), cx).expect("new paragraph fades");
1637            assert_eq!(
1638                ranges.into_iter().flatten().collect::<Vec<_>>(),
1639                (0..12).collect::<Vec<_>>()
1640            );
1641        }
1642
1643        #[gpui::test]
1644        fn set_text_extending_the_text_fades_like_push_str(cx: &mut TestAppContext) {
1645            let state = fading_state("hello", cx);
1646            state.update(cx, |state, cx| state.set_text("hello world", cx));
1647            cx.run_until_parked();
1648
1649            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..11]));
1650        }
1651
1652        #[gpui::test]
1653        fn set_text_replacing_the_text_shows_it_at_once(cx: &mut TestAppContext) {
1654            let state = fading_state("hello", cx);
1655            state.update(cx, |state, cx| state.push_str(" world", cx));
1656            cx.run_until_parked();
1657            assert!(fades(&state, TextLeafKey::block(0), cx).is_some());
1658
1659            state.update(cx, |state, cx| state.set_text("other", cx));
1660            cx.run_until_parked();
1661
1662            assert_eq!(fades(&state, TextLeafKey::block(0), cx), None);
1663        }
1664
1665        #[gpui::test]
1666        fn completed_markup_refades_from_the_divergence(cx: &mut TestAppContext) {
1667            // The paragraph renders `text` (trailing space trimmed), then
1668            // `text **bo` literally.
1669            let state = fading_state("text ", cx);
1670            state.update(cx, |state, cx| state.push_str("**bo", cx));
1671            cx.run_until_parked();
1672            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![4..9]));
1673
1674            // `text **bold**` renders `text bold`: the space keeps its fade,
1675            // the glyphs from byte 5 on changed and fade again as one run.
1676            state.update(cx, |state, cx| state.push_str("ld**", cx));
1677            cx.run_until_parked();
1678            assert_eq!(
1679                fades(&state, TextLeafKey::block(0), cx),
1680                Some(vec![4..5, 5..9])
1681            );
1682        }
1683
1684        #[gpui::test]
1685        fn without_stagger_an_update_fades_as_one_chunk(cx: &mut TestAppContext) {
1686            let state = fading_state("hello", cx);
1687            state.update(cx, |state, cx| state.push_str(" one two three", cx));
1688            cx.run_until_parked();
1689
1690            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![5..19]));
1691        }
1692
1693        #[gpui::test]
1694        fn words_of_one_update_start_one_after_another(cx: &mut TestAppContext) {
1695            let stagger = Duration::from_millis(100);
1696            let state = fading_state("hello", cx);
1697            state.update(cx, |state, _| {
1698                state.set_motion(
1699                    TextViewMotion::default()
1700                        .with_stream_fade(FADE)
1701                        .with_stream_fade_stagger(stagger)
1702                        .with_stream_fade_easing(Easing::Linear),
1703                )
1704            });
1705            state.update(cx, |state, cx| state.push_str(" one two three", cx));
1706            cx.run_until_parked();
1707
1708            state.update(cx, |state, _| {
1709                let frame = state
1710                    .stream_fade
1711                    .frame(Instant::now() + stagger * 3, false)
1712                    .expect("words still fading");
1713                let fades = frame.fades(TextLeafKey::block(0)).expect("paragraph fades");
1714                let ranges: Vec<_> = fades.iter().map(|(range, _)| range.clone()).collect();
1715                assert_eq!(ranges, vec![5..10, 10..14, 14..19]);
1716                // A later word has faded less, so it is still more transparent.
1717                assert!(
1718                    fades[0].1 < fades[1].1 && fades[1].1 < fades[2].1,
1719                    "{fades:?}"
1720                );
1721            });
1722        }
1723
1724        #[gpui::test]
1725        fn a_new_paragraph_fades_as_a_whole(cx: &mut TestAppContext) {
1726            let state = fading_state("first", cx);
1727            state.update(cx, |state, cx| state.push_str("\n\nsecond", cx));
1728            cx.run_until_parked();
1729
1730            assert_eq!(fades(&state, TextLeafKey::block(0), cx), None);
1731            assert_eq!(fades(&state, TextLeafKey::block(7), cx), Some(vec![0..6]));
1732        }
1733
1734        #[gpui::test]
1735        fn code_block_text_fades_by_block(cx: &mut TestAppContext) {
1736            let state = fading_state("```rs\nlet", cx);
1737            state.update(cx, |state, cx| state.push_str(" x", cx));
1738            cx.run_until_parked();
1739
1740            assert_eq!(fades(&state, TextLeafKey::block(0), cx), Some(vec![3..5]));
1741        }
1742
1743        #[gpui::test]
1744        fn table_cells_fade_by_ordinal(cx: &mut TestAppContext) {
1745            let state = fading_state("| a | b |\n|---|---|\n| c | d", cx);
1746            state.update(cx, |state, cx| state.push_str("e |", cx));
1747            cx.run_until_parked();
1748
1749            assert_eq!(fades(&state, TextLeafKey::table_cell(0, 2), cx), None);
1750            assert_eq!(
1751                fades(&state, TextLeafKey::table_cell(0, 3), cx),
1752                Some(vec![1..2])
1753            );
1754        }
1755
1756        #[gpui::test]
1757        fn zero_duration_records_nothing(cx: &mut TestAppContext) {
1758            cx.update(crate::init);
1759            let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("hello", cx)));
1760            cx.run_until_parked();
1761            state.update(cx, |state, cx| state.push_str(" world", cx));
1762            cx.run_until_parked();
1763
1764            state.update(cx, |state, _| {
1765                assert!(state.stream_fade.frame(Instant::now(), false).is_none());
1766            });
1767        }
1768
1769        #[gpui::test]
1770        fn reduced_motion_drops_the_fade(cx: &mut TestAppContext) {
1771            let state = fading_state("hello", cx);
1772            state.update(cx, |state, cx| state.push_str(" world", cx));
1773            cx.run_until_parked();
1774
1775            state.update(cx, |state, _| {
1776                assert!(state.stream_fade.frame(Instant::now(), true).is_none());
1777                assert!(state.stream_fade.frame(Instant::now(), false).is_none());
1778            });
1779        }
1780
1781        #[gpui::test]
1782        fn a_fade_repaints_on_a_timer_until_nothing_fades(cx: &mut TestAppContext) {
1783            struct FadeRoot(Entity<TextViewState>);
1784            impl Render for FadeRoot {
1785                fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1786                    crate::text::TextView::new(&self.0)
1787                }
1788            }
1789
1790            let state = fading_state("hello", cx);
1791            let (_, cx) = cx.add_window_view(|_, _| FadeRoot(state.clone()));
1792            let notifies = Rc::new(Cell::new(0));
1793            let _subscription = cx.update(|_, cx| {
1794                let notifies = notifies.clone();
1795                cx.observe(&state, move |_, _| notifies.set(notifies.get() + 1))
1796            });
1797
1798            state.update(cx, |state, cx| state.push_str(" world", cx));
1799            cx.run_until_parked();
1800            cx.update(|window, cx| window.draw(cx).clear(cx));
1801            let before = notifies.get();
1802
1803            cx.executor().advance_clock(STREAM_FADE_TICK / 2);
1804            cx.run_until_parked();
1805            assert_eq!(notifies.get(), before);
1806
1807            // Each tick repaints once, and that frame schedules the next tick.
1808            for tick in 1..=3 {
1809                cx.executor().advance_clock(STREAM_FADE_TICK);
1810                cx.run_until_parked();
1811                assert_eq!(notifies.get(), before + tick);
1812            }
1813
1814            // Replacing the text drops the fade, so the ticks stop.
1815            state.update(cx, |state, cx| state.set_text("other", cx));
1816            cx.run_until_parked();
1817            cx.executor().advance_clock(STREAM_FADE_TICK);
1818            cx.run_until_parked();
1819            let after = notifies.get();
1820            cx.executor().advance_clock(STREAM_FADE_TICK * 10);
1821            cx.run_until_parked();
1822            assert_eq!(notifies.get(), after);
1823            assert!(state.read_with(cx, |state, _| state.fade_tick.is_none()));
1824        }
1825    }
1826
1827    #[gpui::test]
1828    fn small_full_replace_parses_before_background_executor_runs(cx: &mut TestAppContext) {
1829        cx.update(crate::init);
1830        let markdown = "# ready";
1831        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
1832
1833        state.read_with(cx, |state, _| {
1834            assert_eq!(state.source().as_str(), markdown);
1835            assert_eq!(state.parsed_content.document.blocks.len(), 1);
1836        });
1837    }
1838
1839    #[gpui::test]
1840    fn large_markdown_and_html_full_replacements_wait_for_background_executor(
1841        cx: &mut TestAppContext,
1842    ) {
1843        cx.update(crate::init);
1844        let markdown = "# x\n\n".repeat(MAX_SYNC_FULL_REPLACE_BYTES / 5 + 1);
1845        let html = format!("<p>{}</p>", "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1));
1846        assert!(markdown.len() > MAX_SYNC_FULL_REPLACE_BYTES);
1847        assert!(html.len() > MAX_SYNC_FULL_REPLACE_BYTES);
1848
1849        let (markdown_state, html_state) = cx.update(|cx| {
1850            (
1851                cx.new(|cx| TextViewState::markdown(&markdown, cx)),
1852                cx.new(|cx| TextViewState::html(&html, cx)),
1853            )
1854        });
1855
1856        markdown_state.read_with(cx, |state, _| {
1857            assert_eq!(state.text.as_str(), markdown.as_str());
1858            assert!(state.source().as_str().is_empty());
1859            assert!(state.parsed_content.document.blocks.is_empty());
1860        });
1861        html_state.read_with(cx, |state, _| {
1862            assert_eq!(state.text.as_str(), html.as_str());
1863            assert!(state.source().as_str().is_empty());
1864            assert!(state.parsed_content.document.blocks.is_empty());
1865        });
1866
1867        cx.run_until_parked();
1868
1869        markdown_state.read_with(cx, |state, _| {
1870            assert_eq!(state.source().as_str(), markdown.as_str());
1871            assert!(!state.parsed_content.document.blocks.is_empty());
1872        });
1873        html_state.read_with(cx, |state, _| {
1874            assert_eq!(state.source().as_str(), html.as_str());
1875            assert!(!state.parsed_content.document.blocks.is_empty());
1876        });
1877    }
1878
1879    #[gpui::test]
1880    fn inline_source_ranges_follow_streamed_tail_reparsing(cx: &mut TestAppContext) {
1881        cx.update(crate::init);
1882        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("中文 $a$\n\n尾 $x", cx)));
1883        state.update(cx, |state, cx| {
1884            let extensions = MarkdownExtensions::default().plugin(
1885                crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with(|node, _| {
1886                    let markdown::mdast::Node::InlineMath(math) = node else {
1887                        return None;
1888                    };
1889                    Some(super::super::MarkdownNode::new("formula", ()).text(math.value.clone()))
1890                }),
1891            );
1892            state.set_markdown_extensions(Arc::new(extensions), cx);
1893        });
1894        cx.run_until_parked();
1895        state.update(cx, |state, cx| state.push_str("^2$ 后", cx));
1896        cx.run_until_parked();
1897        state.read_with(cx, |state, _| {
1898            let source = "中文 $a$\n\n尾 $x^2$ 后";
1899            assert_eq!(state.source().as_str(), source);
1900            let objects: Vec<_> = state
1901                .parsed_content
1902                .document
1903                .blocks
1904                .iter()
1905                .flat_map(|block| {
1906                    let super::super::node::BlockNode::Paragraph(paragraph) = block else {
1907                        panic!()
1908                    };
1909                    paragraph
1910                        .children
1911                        .iter()
1912                        .filter_map(|node| node.custom.as_ref())
1913                })
1914                .collect();
1915            assert_eq!(objects.len(), 2);
1916            for (object, markdown) in objects.iter().zip(["$a$", "$x^2$"]) {
1917                let start = source.find(markdown).unwrap();
1918                assert_eq!(object.source_range(), Some(start..start + markdown.len()));
1919                assert_eq!(object.as_markdown(), markdown);
1920            }
1921        });
1922    }
1923
1924    #[gpui::test]
1925    fn async_full_replace_then_push_str_preserves_complete_source(cx: &mut TestAppContext) {
1926        cx.update(crate::init);
1927        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
1928        cx.run_until_parked();
1929
1930        let replacement = "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1);
1931        let expected = format!("{replacement} tail");
1932        state.update(cx, |state, cx| {
1933            state.set_text(&replacement, cx);
1934            state.push_str(" tail", cx);
1935        });
1936        cx.run_until_parked();
1937
1938        state.read_with(cx, |state, _| {
1939            assert_eq!(state.text.as_str(), expected.as_str());
1940            assert_eq!(state.source().as_str(), expected.as_str());
1941        });
1942    }
1943
1944    /// Push `chunk` and parse it the way the background parser would, without
1945    /// running the parser, returning the update it would send.
1946    fn push_and_parse(
1947        state: &Entity<TextViewState>,
1948        chunk: &str,
1949        cx: &mut TestAppContext,
1950    ) -> ParsedUpdate {
1951        let (revision, baseline) = state.update(cx, |state, cx| {
1952            state.push_str(chunk, cx);
1953            (state.revision, state.parsed_content.clone())
1954        });
1955        let options = UpdateOptions {
1956            revision,
1957            pending_text: chunk.to_string(),
1958            append: true,
1959            mode: ParseMode::Compatible,
1960            markdown_extensions: Arc::default(),
1961        };
1962        ParsedUpdate {
1963            revision,
1964            full_parse: false,
1965            selection_compatible: true,
1966            baseline_ack: false,
1967            result: parse_content(TextViewFormat::Markdown, baseline, &options),
1968        }
1969    }
1970
1971    #[gpui::test]
1972    fn stream_commits_a_parse_that_a_newer_chunk_overtook(cx: &mut TestAppContext) {
1973        cx.update(crate::init);
1974        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("# Answer\n\n", cx)));
1975        cx.run_until_parked();
1976
1977        // Chunks arriving faster than they parse always push the next chunk
1978        // before the previous parse lands.
1979        let parsed = push_and_parse(&state, "Streaming", cx);
1980        state.update(cx, |state, cx| {
1981            state.push_str(" tokens", cx);
1982            state.commit_parsed_update(parsed, cx);
1983            assert_eq!(state.source().as_str(), "# Answer\n\nStreaming");
1984        });
1985
1986        cx.run_until_parked();
1987        state.read_with(cx, |state, _| {
1988            assert_eq!(state.source().as_str(), "# Answer\n\nStreaming tokens");
1989        });
1990    }
1991
1992    #[gpui::test]
1993    fn a_parse_from_before_a_replacement_is_discarded(cx: &mut TestAppContext) {
1994        cx.update(crate::init);
1995        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
1996        cx.run_until_parked();
1997
1998        let parsed = push_and_parse(&state, " text", cx);
1999        // Large enough to parse in the background, so the replacement is not
2000        // committed yet when the older parse lands.
2001        let replacement = "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1);
2002        state.update(cx, |state, cx| {
2003            state.set_text(&replacement, cx);
2004            state.commit_parsed_update(parsed, cx);
2005            assert_eq!(state.source().as_str(), "old");
2006        });
2007
2008        cx.run_until_parked();
2009        state.read_with(cx, |state, _| {
2010            assert_eq!(state.source().as_str(), replacement.as_str());
2011        });
2012    }
2013
2014    #[gpui::test]
2015    fn html_push_str_keeps_earlier_blocks(cx: &mut TestAppContext) {
2016        cx.update(crate::init);
2017        let state = cx.update(|cx| cx.new(|cx| TextViewState::html("<p>first</p>", cx)));
2018        cx.run_until_parked();
2019
2020        state.update(cx, |state, cx| {
2021            state.push_str("<p>second</p>", cx);
2022        });
2023        cx.run_until_parked();
2024
2025        state.read_with(cx, |state, _| {
2026            assert_eq!(state.source().as_str(), "<p>first</p><p>second</p>");
2027            let text = state
2028                .parsed_content
2029                .document
2030                .blocks
2031                .iter()
2032                .map(|block| block.text())
2033                .collect::<String>();
2034            assert!(text.contains("first"), "lost the first block: {text:?}");
2035            assert!(text.contains("second"), "lost the appended block: {text:?}");
2036        });
2037    }
2038
2039    #[gpui::test]
2040    fn element_text_of_the_same_string_is_not_compared_again(cx: &mut TestAppContext) {
2041        cx.update(crate::init);
2042        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("", cx)));
2043        let revision = |cx: &mut TestAppContext| state.read_with(cx, |state, _| state.revision);
2044        let text = SharedString::from("hello");
2045
2046        state.update(cx, |state, cx| state.set_element_text(&text, cx));
2047        let parsed = revision(cx);
2048        assert!(parsed > 0);
2049
2050        // The same allocation again, and equal bytes in another allocation,
2051        // both leave the parsed text alone.
2052        state.update(cx, |state, cx| state.set_element_text(&text, cx));
2053        assert_eq!(revision(cx), parsed);
2054        let equal = SharedString::from("hello".to_string());
2055        state.update(cx, |state, cx| state.set_element_text(&equal, cx));
2056        assert_eq!(revision(cx), parsed);
2057
2058        // Once the state's text moved on, the element's string is set again.
2059        state.update(cx, |state, cx| {
2060            state.push_str(" world", cx);
2061            state.set_element_text(&equal, cx);
2062        });
2063        state.read_with(cx, |state, _| assert_eq!(state.text.as_str(), "hello"));
2064    }
2065
2066    #[gpui::test]
2067    fn set_text_then_push_str_appends_to_replaced_content(cx: &mut TestAppContext) {
2068        cx.update(crate::init);
2069        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
2070        cx.run_until_parked();
2071
2072        state.update(cx, |state, cx| {
2073            state.set_text("", cx);
2074            state.push_str("new", cx);
2075            state.push_str(" text", cx);
2076        });
2077        cx.run_until_parked();
2078
2079        state.read_with(cx, |state, _| {
2080            assert_eq!(state.text.as_str(), "new text");
2081            assert_eq!(state.source().as_str(), "new text");
2082        });
2083
2084        state.update(cx, |state, cx| {
2085            state.set_text("", cx);
2086        });
2087        cx.run_until_parked();
2088
2089        state.read_with(cx, |state, _| {
2090            assert_eq!(state.text.as_str(), "");
2091            assert_eq!(state.source().as_str(), "");
2092        });
2093    }
2094
2095    #[gpui::test]
2096    fn full_parse_coalesced_with_append_preserves_new_select_all(cx: &mut TestAppContext) {
2097        cx.update(crate::init);
2098        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
2099        cx.run_until_parked();
2100
2101        state.update(cx, |state, cx| {
2102            state.set_text("new", cx);
2103            state.push_str(" text", cx);
2104            state.select_all(cx);
2105        });
2106        cx.run_until_parked();
2107
2108        state.read_with(cx, |state, _| {
2109            assert!(state.select_all);
2110            assert_eq!(state.selected_text().trim(), "new text");
2111        });
2112    }
2113
2114    fn parsed_blocks(
2115        state: &Entity<TextViewState>,
2116        cx: &mut TestAppContext,
2117    ) -> Vec<(String, Option<Span>)> {
2118        state.read_with(cx, |state, _| {
2119            state
2120                .parsed_content
2121                .document
2122                .blocks
2123                .iter()
2124                .map(|block| (block.text(), block.span()))
2125                .collect()
2126        })
2127    }
2128
2129    #[gpui::test]
2130    fn set_text_extending_markdown_appends_and_keeps_selection(cx: &mut TestAppContext) {
2131        cx.update(crate::init);
2132        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("hello", cx)));
2133        cx.run_until_parked();
2134        let revisions =
2135            |state: &TextViewState| (state.selection_revision, state.full_update_revision);
2136        let initial = state.read_with(cx, |state, _| revisions(state));
2137
2138        state.update(cx, |state, cx| state.set_text("hello world", cx));
2139        cx.run_until_parked();
2140        state.read_with(cx, |state, _| {
2141            assert_eq!(state.source().as_str(), "hello world");
2142            assert_eq!(revisions(state), initial);
2143        });
2144
2145        state.update(cx, |state, cx| state.set_text("hello", cx));
2146        cx.run_until_parked();
2147        state.read_with(cx, |state, _| {
2148            assert_eq!(state.source().as_str(), "hello");
2149            assert_ne!(state.selection_revision, initial.0);
2150            assert_ne!(state.full_update_revision, initial.1);
2151        });
2152    }
2153
2154    #[gpui::test]
2155    fn set_text_streaming_markdown_matches_a_full_parse(cx: &mut TestAppContext) {
2156        cx.update(crate::init);
2157        let streamed = cx.update(|cx| cx.new(|cx| TextViewState::markdown("# Title", cx)));
2158        cx.run_until_parked();
2159
2160        // Chunks continue a heading, a paragraph, an inline code span, a list
2161        // and a fenced code block, and the text grows past the synchronous
2162        // parse limit.
2163        let filler = "word ".repeat(MAX_SYNC_FULL_REPLACE_BYTES / 5 + 1);
2164        let chunks = [
2165            "\n\nfirst para",
2166            "graph with `co",
2167            "de`\n\n- one\n",
2168            "- two\n\n```rust\nfn main() {",
2169            "}\n```\n\n",
2170            filler.as_str(),
2171            "\n\nlast",
2172        ];
2173        let full_update_revision = streamed.read_with(cx, |state, _| state.full_update_revision);
2174        let mut text = "# Title".to_string();
2175        for chunk in chunks {
2176            text.push_str(chunk);
2177            streamed.update(cx, |state, cx| state.set_text(&text, cx));
2178            cx.run_until_parked();
2179        }
2180        assert_eq!(
2181            streamed.read_with(cx, |state, _| state.full_update_revision),
2182            full_update_revision
2183        );
2184
2185        let parsed = cx.update(|cx| cx.new(|cx| TextViewState::markdown(&text, cx)));
2186        cx.run_until_parked();
2187
2188        assert_eq!(
2189            streamed.read_with(cx, |state, _| state.source()),
2190            parsed.read_with(cx, |state, _| state.source())
2191        );
2192        assert_eq!(parsed_blocks(&streamed, cx), parsed_blocks(&parsed, cx));
2193    }
2194
2195    #[gpui::test]
2196    fn set_text_extending_html_parses_it_again(cx: &mut TestAppContext) {
2197        cx.update(crate::init);
2198        let streamed = cx.update(|cx| cx.new(|cx| TextViewState::html("<ul><li>a</li>", cx)));
2199        cx.run_until_parked();
2200
2201        let text = "<ul><li>a</li><li>b</li></ul>";
2202        streamed.update(cx, |state, cx| state.set_text(text, cx));
2203        cx.run_until_parked();
2204        assert_ne!(
2205            streamed.read_with(cx, |state, _| state.full_update_revision),
2206            0
2207        );
2208
2209        let parsed = cx.update(|cx| cx.new(|cx| TextViewState::html(text, cx)));
2210        cx.run_until_parked();
2211        assert_eq!(parsed_blocks(&streamed, cx), parsed_blocks(&parsed, cx));
2212    }
2213
2214    #[gpui::test]
2215    fn set_text_extending_after_a_parse_error_parses_it_again(cx: &mut TestAppContext) {
2216        cx.update(crate::init);
2217        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("hello", cx)));
2218        cx.run_until_parked();
2219
2220        let full_update_revision = state.read_with(cx, |state, _| state.full_update_revision);
2221
2222        state.update(cx, |state, cx| {
2223            state.parsed_error = Some("failed".into());
2224            state.set_text("hello world", cx);
2225        });
2226        cx.run_until_parked();
2227
2228        state.read_with(cx, |state, _| {
2229            assert!(state.parsed_error.is_none());
2230            assert_ne!(state.full_update_revision, full_update_revision);
2231            assert_eq!(state.source().as_str(), "hello world");
2232        });
2233    }
2234
2235    #[test]
2236    fn update_options_merge_keeps_latest_full_text() {
2237        let mut options = UpdateOptions {
2238            revision: 1,
2239            pending_text: "old".to_string(),
2240            append: true,
2241            mode: ParseMode::Compatible,
2242            markdown_extensions: Arc::default(),
2243        };
2244
2245        options.merge(UpdateOptions {
2246            revision: 2,
2247            pending_text: "new".to_string(),
2248            append: false,
2249            mode: ParseMode::BaselineAck,
2250            markdown_extensions: Arc::default(),
2251        });
2252        options.merge(UpdateOptions {
2253            revision: 3,
2254            pending_text: " text".to_string(),
2255            append: true,
2256            mode: ParseMode::Compatible,
2257            markdown_extensions: Arc::default(),
2258        });
2259
2260        assert_eq!(options.revision, 3);
2261        assert_eq!(options.pending_text, "new text");
2262        assert!(!options.append);
2263    }
2264
2265    #[test]
2266    fn append_merged_into_async_replace_remains_a_replacement() {
2267        let mut options = UpdateOptions {
2268            revision: 1,
2269            pending_text: "new".to_string(),
2270            append: false,
2271            mode: ParseMode::Replace,
2272            markdown_extensions: Arc::default(),
2273        };
2274
2275        options.merge(UpdateOptions {
2276            revision: 2,
2277            pending_text: " text".to_string(),
2278            append: true,
2279            mode: ParseMode::Compatible,
2280            markdown_extensions: Arc::default(),
2281        });
2282
2283        assert_eq!(options.revision, 2);
2284        assert_eq!(options.pending_text, "new text");
2285        assert!(!options.append);
2286        assert_eq!(options.mode, ParseMode::Replace);
2287    }
2288
2289    #[test]
2290    fn update_future_yields_before_coalescing_all_queued_updates() {
2291        let (tx, rx) = unbounded::<UpdateOptions>();
2292        let (tx_result, rx_result) = unbounded::<ParsedUpdate>();
2293        let total_updates = 128;
2294
2295        for revision in 1..=total_updates {
2296            tx.try_send(UpdateOptions {
2297                revision,
2298                pending_text: format!("{revision}\n"),
2299                append: revision != 1,
2300                mode: if revision == 1 {
2301                    ParseMode::BaselineAck
2302                } else {
2303                    ParseMode::Compatible
2304                },
2305                markdown_extensions: Arc::default(),
2306            })
2307            .unwrap();
2308        }
2309
2310        let mut future = Box::pin(UpdateFuture::new(TextViewFormat::Markdown, rx, tx_result));
2311        let waker = futures::task::noop_waker();
2312        let mut task_cx = std::task::Context::from_waker(&waker);
2313
2314        assert!(matches!(
2315            std::future::Future::poll(future.as_mut(), &mut task_cx),
2316            Poll::Pending
2317        ));
2318        let parsed_update = rx_result.try_recv().expect("parse result");
2319
2320        assert!(
2321            parsed_update.revision < total_updates,
2322            "single poll coalesced every queued update through revision {}",
2323            parsed_update.revision
2324        );
2325
2326        assert!(matches!(
2327            std::future::Future::poll(future.as_mut(), &mut task_cx),
2328            Poll::Pending
2329        ));
2330        let parsed_update = rx_result.try_recv().expect("next parse result");
2331        assert_eq!(parsed_update.revision, total_updates);
2332    }
2333
2334    #[gpui::test]
2335    fn select_all_returns_rendered_text(cx: &mut TestAppContext) {
2336        cx.update(crate::init);
2337        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("**quick** value", cx)));
2338        cx.run_until_parked();
2339
2340        state.update(cx, |state, cx| {
2341            state.select_all(cx);
2342        });
2343
2344        state.read_with(cx, |state, _| {
2345            assert!(state.has_view_selection());
2346            assert_eq!(state.selected_text().trim(), "quick value");
2347        });
2348
2349        state.update(cx, |state, cx| {
2350            state.clear_selection(cx);
2351        });
2352
2353        state.read_with(cx, |state, _| {
2354            assert!(!state.has_view_selection());
2355            assert_eq!(state.selected_text(), "");
2356        });
2357    }
2358
2359    /// A screen reader reads the rendered body, not the Markdown source, and
2360    /// reads text set or streamed in once its parse lands.
2361    #[gpui::test]
2362    fn accessibility_text_follows_the_rendered_text(cx: &mut TestAppContext) {
2363        cx.update(crate::init);
2364        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("Hello **world**", cx)));
2365        cx.run_until_parked();
2366        let runs = |state: &Entity<TextViewState>, cx: &mut TestAppContext| {
2367            state.update(cx, |state, _| state.accessibility_text_runs(1.).unwrap())
2368        };
2369
2370        let first = runs(&state, cx);
2371        assert_eq!(first.text().trim_end(), "Hello world");
2372        assert_eq!(first.selection(), None);
2373        // An unchanged document reuses its runs.
2374        assert!(Rc::ptr_eq(&first, &runs(&state, cx)));
2375
2376        state.update(cx, |state, cx| state.push_str("\n\n- item", cx));
2377        cx.run_until_parked();
2378        assert_eq!(runs(&state, cx).text().trim_end(), "Hello world\nitem");
2379
2380        state.update(cx, |state, cx| state.set_text("Other", cx));
2381        cx.run_until_parked();
2382        assert_eq!(runs(&state, cx).text().trim_end(), "Other");
2383
2384        state.update(cx, |state, cx| state.select_all(cx));
2385        let selected = runs(&state, cx);
2386        assert_eq!(
2387            selected.selection(),
2388            Some((0, selected.text().chars().count()))
2389        );
2390    }
2391
2392    #[gpui::test]
2393    fn select_all_in_source_format_returns_source(cx: &mut TestAppContext) {
2394        cx.update(crate::init);
2395        let markdown = "**quick** value";
2396        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
2397        cx.run_until_parked();
2398
2399        state.update(cx, |state, cx| state.select_all(cx));
2400
2401        // The default (plain) mode strips the markup.
2402        state.read_with(cx, |state, _| {
2403            assert_eq!(state.selected_text().trim(), "quick value");
2404        });
2405
2406        state.update(cx, |state, cx| {
2407            state.set_selection_format(SelectionFormat::Source, cx)
2408        });
2409
2410        // Source mode yields the whole source verbatim.
2411        state.read_with(cx, |state, _| {
2412            assert_eq!(state.selected_text().trim(), markdown);
2413        });
2414    }
2415
2416    #[gpui::test]
2417    fn selected_source_range_returns_full_markdown_source_for_select_all(cx: &mut TestAppContext) {
2418        cx.update(crate::init);
2419        let markdown = "**quick** value";
2420        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
2421        cx.run_until_parked();
2422
2423        state.update(cx, |state, cx| state.select_all(cx));
2424
2425        state.read_with(cx, |state, _| {
2426            assert_eq!(state.selected_source_range(), Some(0..markdown.len()));
2427        });
2428    }
2429
2430    #[gpui::test]
2431    fn selected_source_range_returns_none_for_html(cx: &mut TestAppContext) {
2432        cx.update(crate::init);
2433        let state = cx.update(|cx| cx.new(|cx| TextViewState::html("<b>quick</b>", cx)));
2434        cx.run_until_parked();
2435
2436        state.update(cx, |state, cx| state.select_all(cx));
2437
2438        state.read_with(cx, |state, _| {
2439            assert_eq!(state.selected_source_range(), None);
2440        });
2441    }
2442
2443    #[test]
2444    fn selected_source_range_keeps_global_offsets_after_incremental_tail_parse() {
2445        let options = UpdateOptions {
2446            revision: 1,
2447            pending_text: "first\n\nsecond".to_string(),
2448            append: false,
2449            mode: ParseMode::Replace,
2450            markdown_extensions: Arc::default(),
2451        };
2452        let content = parse_content(TextViewFormat::Markdown, ParsedContent::default(), &options)
2453            .expect("initial parse");
2454        let content = parse_content(
2455            TextViewFormat::Markdown,
2456            content,
2457            &UpdateOptions {
2458                revision: 2,
2459                pending_text: "\n\n**écho**".to_string(),
2460                append: true,
2461                mode: ParseMode::Compatible,
2462                markdown_extensions: Arc::default(),
2463            },
2464        )
2465        .expect("incremental parse");
2466        let BlockNode::Paragraph(paragraph) = &content.document.blocks[2] else {
2467            panic!("expected appended paragraph");
2468        };
2469        let mut state = paragraph.state.lock().unwrap();
2470        state.set_text(paragraph.text().into());
2471        state.selection = Some((0.."écho".len()).into());
2472        drop(state);
2473
2474        assert_eq!(content.document.selected_source_range(), Some(17..22));
2475    }
2476
2477    #[test]
2478    fn streamed_ordered_list_continuation_preserves_start() {
2479        let initial = parse_content(
2480            TextViewFormat::Markdown,
2481            ParsedContent::default(),
2482            &UpdateOptions {
2483                revision: 1,
2484                pending_text: "3. three".to_string(),
2485                append: false,
2486                mode: ParseMode::Replace,
2487                markdown_extensions: Arc::default(),
2488            },
2489        )
2490        .expect("initial list parse");
2491        let continued = parse_content(
2492            TextViewFormat::Markdown,
2493            initial,
2494            &UpdateOptions {
2495                revision: 2,
2496                pending_text: "\n4. four".to_string(),
2497                append: true,
2498                mode: ParseMode::Compatible,
2499                markdown_extensions: Arc::default(),
2500            },
2501        )
2502        .expect("streamed list continuation parse");
2503
2504        let BlockNode::List {
2505            start, children, ..
2506        } = &continued.document.blocks[0]
2507        else {
2508            panic!("expected streamed ordered list");
2509        };
2510        assert_eq!(*start, Some(3));
2511        assert_eq!(children.len(), 2);
2512    }
2513
2514    #[gpui::test]
2515    fn parser_revision_reparses_same_name_inline_configuration(cx: &mut TestAppContext) {
2516        cx.update(crate::init);
2517        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("@member", cx)));
2518        for (revision, label) in [(1, "Alice"), (2, "Bob")] {
2519            let extensions = MarkdownExtensions::default()
2520                .parser_revision(revision)
2521                .plugin(
2522                    crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with(
2523                        move |node, _| {
2524                            matches!(node, markdown::mdast::Node::Text(_))
2525                                .then(|| MarkdownNode::new("mention", label).text(label))
2526                        },
2527                    ),
2528                );
2529            state.update(cx, |state, cx| {
2530                state.set_markdown_extensions(Arc::new(extensions), cx)
2531            });
2532            cx.run_until_parked();
2533            state.read_with(cx, |state, _| {
2534                let node::BlockNode::Paragraph(paragraph) =
2535                    &state.parsed_content.document.blocks[0]
2536                else {
2537                    panic!()
2538                };
2539                assert_eq!(
2540                    paragraph.children[0].custom.as_ref().unwrap().as_text(),
2541                    label
2542                );
2543            });
2544        }
2545    }
2546
2547    #[gpui::test]
2548    fn set_markdown_extensions_reparses_existing_text(cx: &mut TestAppContext) {
2549        cx.update(crate::init);
2550        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("$TSLA.US", cx)));
2551        cx.run_until_parked();
2552
2553        let extensions = MarkdownExtensions::default().block_parser(|node, cx| {
2554            let markdown::mdast::Node::Paragraph(paragraph) = node else {
2555                return None;
2556            };
2557            let [markdown::mdast::Node::Text(text)] = paragraph.children.as_slice() else {
2558                return None;
2559            };
2560            let symbol = text.value.strip_prefix('$')?.to_string();
2561            let node_text = format!("${symbol}");
2562
2563            Some(
2564                MarkdownNode::new("ticker", symbol)
2565                    .text(node_text)
2566                    .markdown(cx.node_source(node).unwrap_or_default()),
2567            )
2568        });
2569
2570        state.update(cx, |state, cx| {
2571            state.set_markdown_extensions(Arc::new(extensions), cx);
2572        });
2573        cx.run_until_parked();
2574
2575        state.read_with(cx, |state, _| {
2576            let node::BlockNode::Custom { node, .. } = &state.parsed_content.document.blocks[0]
2577            else {
2578                panic!("expected custom markdown node");
2579            };
2580            assert_eq!(node.name(), "ticker");
2581            assert_eq!(node.data::<String>().map(String::as_str), Some("TSLA.US"));
2582        });
2583    }
2584
2585    mod range_highlights {
2586        use std::ops::Range;
2587
2588        use gpui::{Entity, TestAppContext};
2589
2590        use super::super::*;
2591        use crate::text::stream_fade::TextLeafKey;
2592
2593        fn state(markdown: &str, cx: &mut TestAppContext) -> Entity<TextViewState> {
2594            cx.update(crate::init);
2595            let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
2596            cx.run_until_parked();
2597            state
2598        }
2599
2600        fn highlight(range: Range<usize>) -> RangeHighlight {
2601            RangeHighlight::new(range, gpui::hsla(0.15, 1., 0.5, 0.4))
2602        }
2603
2604        /// Highlights `ranges` of the current rendered text.
2605        fn set(
2606            state: &Entity<TextViewState>,
2607            ranges: impl IntoIterator<Item = Range<usize>>,
2608            cx: &mut TestAppContext,
2609        ) -> Result<(), RangeHighlightError> {
2610            state.update(cx, |state, cx| {
2611                state.set_range_highlights(ranges.into_iter().map(highlight), cx)
2612            })
2613        }
2614
2615        /// The ranges leaf `key` paints, in its own byte space.
2616        fn painted(
2617            state: &Entity<TextViewState>,
2618            key: TextLeafKey,
2619            cx: &mut TestAppContext,
2620        ) -> Vec<Range<usize>> {
2621            state.read_with(cx, |state, _| {
2622                state.range_highlights.as_ref().map_or(Vec::new(), |frame| {
2623                    frame
2624                        .backgrounds(key)
2625                        .iter()
2626                        .map(|(range, _)| range.clone())
2627                        .collect()
2628                })
2629            })
2630        }
2631
2632        fn has_highlights(state: &Entity<TextViewState>, cx: &mut TestAppContext) -> bool {
2633            state.read_with(cx, |state, _| state.range_highlights.is_some())
2634        }
2635
2636        #[gpui::test]
2637        fn rendered_text_is_the_plain_copy_text(cx: &mut TestAppContext) {
2638            let state = state(
2639                "# Title\n\nhello **world** \\*\n\n- item\n\n| a | b |\n|---|---|\n| c | d |\n\n```\nlet x\n```",
2640                cx,
2641            );
2642            state.read_with(cx, |state, _| {
2643                assert_eq!(
2644                    state.rendered_text().as_str(),
2645                    "Title\nhello world *\nitem\na b\nc d\n\nlet x\n"
2646                );
2647            });
2648        }
2649
2650        #[gpui::test]
2651        fn a_match_across_marks_paints_in_its_paragraph(cx: &mut TestAppContext) {
2652            let state = state("hello **world**", cx);
2653            set(&state, [0.."hello world".len()], cx).unwrap();
2654            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..11]);
2655        }
2656
2657        #[gpui::test]
2658        fn repeated_text_maps_to_the_occurrence_addressed(cx: &mut TestAppContext) {
2659            let state = state("foo\n\nfoo", cx);
2660            let second = state.read_with(cx, |state, _| {
2661                state.rendered_text().as_str().rfind("foo").unwrap()
2662            });
2663            set(&state, [second..second + 3], cx).unwrap();
2664            assert!(painted(&state, TextLeafKey::block(0), cx).is_empty());
2665            assert_eq!(painted(&state, TextLeafKey::block(5), cx), [0..3]);
2666        }
2667
2668        #[gpui::test]
2669        fn a_range_across_blocks_skips_the_separator(cx: &mut TestAppContext) {
2670            let state = state("ab\n\ncd", cx);
2671            // "ab\ncd\n": 1..4 is "b\nc".
2672            set(&state, [1..4], cx).unwrap();
2673            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [1..2]);
2674            assert_eq!(painted(&state, TextLeafKey::block(4), cx), [0..1]);
2675        }
2676
2677        #[gpui::test]
2678        fn table_cells_and_code_blocks_are_leaves(cx: &mut TestAppContext) {
2679            let state = state("| a | b |\n|---|---|\n| c | d |\n\n```\nlet x\n```", cx);
2680            // "a b\nc d\n\nlet x\n"
2681            set(&state, [0..3, 6..7, 9..12], cx).unwrap();
2682            assert_eq!(painted(&state, TextLeafKey::table_cell(0, 0), cx), [0..1]);
2683            assert_eq!(painted(&state, TextLeafKey::table_cell(0, 1), cx), [0..1]);
2684            assert_eq!(painted(&state, TextLeafKey::table_cell(0, 3), cx), [0..1]);
2685            let code_start = "| a | b |\n|---|---|\n| c | d |\n\n".len();
2686            assert_eq!(painted(&state, TextLeafKey::block(code_start), cx), [0..3]);
2687        }
2688
2689        #[gpui::test]
2690        fn invalid_ranges_reject_the_whole_set(cx: &mut TestAppContext) {
2691            let state = state("中文\n\nab", cx);
2692            // "中文\nab\n"
2693            set(&state, [0.."中".len()], cx).unwrap();
2694            let invalid = [Range { start: 6, end: 3 }, 0..1, 0..100];
2695            for range in invalid {
2696                assert_eq!(
2697                    set(&state, [0..3, range.clone()], cx),
2698                    Err(RangeHighlightError::InvalidRange(1)),
2699                    "{range:?}"
2700                );
2701            }
2702            // The rejected sets left the earlier highlight in place.
2703            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..3]);
2704        }
2705
2706        #[gpui::test]
2707        fn text_outside_every_block_is_left_unpainted(cx: &mut TestAppContext) {
2708            let source = "foo one\n\n<div>foo two</div>\n\n| foo | x |\n|---|---|\n\nfoo three";
2709            let state = state(source, cx);
2710            let text = state.read_with(cx, |state, _| state.rendered_text().as_str().to_string());
2711            // Every "foo" and " ", an empty range, and the separator after the
2712            // first block: the HTML block's text and the separators are not
2713            // any block's text, so they paint nothing, but nothing fails.
2714            let ranges = text
2715                .match_indices("foo")
2716                .chain(text.match_indices(' '))
2717                .map(|(start, found)| start..start + found.len())
2718                .chain([3..3, 7..8])
2719                .collect::<Vec<_>>();
2720            set(&state, ranges, cx).unwrap();
2721            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..3, 3..4]);
2722            let table = source.find("| foo").unwrap();
2723            assert_eq!(
2724                painted(&state, TextLeafKey::table_cell(table, 0), cx),
2725                [0..3]
2726            );
2727            let last = source.find("foo three").unwrap();
2728            assert_eq!(painted(&state, TextLeafKey::block(last), cx), [0..3, 3..4]);
2729        }
2730
2731        #[gpui::test]
2732        fn a_later_highlight_paints_over_an_earlier_one(cx: &mut TestAppContext) {
2733            let state = state("abcdef", cx);
2734            set(&state, [0..6, 2..3], cx).unwrap();
2735            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..6, 2..3]);
2736        }
2737
2738        #[gpui::test]
2739        fn html_text_is_unsupported(cx: &mut TestAppContext) {
2740            let html = cx.update(|cx| cx.new(|cx| TextViewState::html("<p>one</p>", cx)));
2741            cx.run_until_parked();
2742            html.update(cx, |html, cx| {
2743                assert_eq!(
2744                    html.set_range_highlights([highlight(0..3)], cx),
2745                    Err(RangeHighlightError::Unsupported)
2746                );
2747            });
2748        }
2749
2750        #[gpui::test]
2751        fn inline_objects_are_skipped(cx: &mut TestAppContext) {
2752            let state = state("x $a$ y", cx);
2753            state.update(cx, |state, cx| {
2754                let extensions = MarkdownExtensions::default().plugin(
2755                    crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with(
2756                        |node, _| {
2757                            let markdown::mdast::Node::InlineMath(math) = node else {
2758                                return None;
2759                            };
2760                            Some(
2761                                crate::text::MarkdownNode::new("formula", ())
2762                                    .text(math.value.clone()),
2763                            )
2764                        },
2765                    ),
2766                );
2767                state.set_markdown_extensions(Arc::new(extensions), cx);
2768            });
2769            cx.run_until_parked();
2770            // "x a y\n", where "a" is the formula.
2771            set(&state, [2..3], cx).unwrap();
2772            assert!(painted(&state, TextLeafKey::block(0), cx).is_empty());
2773            set(&state, [0..5], cx).unwrap();
2774            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..2, 3..5]);
2775        }
2776
2777        #[gpui::test]
2778        fn push_str_keeps_earlier_blocks_and_clips_the_changed_tail(cx: &mut TestAppContext) {
2779            let state = state("first\n\na **b", cx);
2780            // "first\na **b\n"
2781            set(&state, [0..5, 6..11], cx).unwrap();
2782
2783            // Closing the emphasis renders the tail as "a bc".
2784            state.update(cx, |state, cx| state.push_str("c**", cx));
2785            cx.run_until_parked();
2786
2787            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2788            assert_eq!(painted(&state, TextLeafKey::block(7), cx), [0..2]);
2789        }
2790
2791        #[gpui::test]
2792        fn push_str_keeps_a_block_whose_text_is_unchanged(cx: &mut TestAppContext) {
2793            let state = state("first\n\nsecond", cx);
2794            set(&state, [6..12], cx).unwrap();
2795            // A setext underline turns the paragraph into a heading at the
2796            // same source start, rendering the same text.
2797            state.update(cx, |state, cx| state.push_str("\n===", cx));
2798            cx.run_until_parked();
2799            assert_eq!(painted(&state, TextLeafKey::block(7), cx), [0..6]);
2800        }
2801
2802        #[gpui::test]
2803        fn push_str_drops_highlights_of_a_leaf_that_is_gone(cx: &mut TestAppContext) {
2804            let state = state("first\n\n| a |", cx);
2805            set(&state, [0..5, 6..11], cx).unwrap();
2806            // A delimiter row turns the paragraph into a table, whose text
2807            // lives in cells instead.
2808            state.update(cx, |state, cx| state.push_str("\n|---|", cx));
2809            cx.run_until_parked();
2810            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2811            assert!(painted(&state, TextLeafKey::block(7), cx).is_empty());
2812            assert!(painted(&state, TextLeafKey::table_cell(7, 0), cx).is_empty());
2813        }
2814
2815        #[gpui::test]
2816        fn replacing_text_drops_highlights_only_where_it_changed(cx: &mut TestAppContext) {
2817            let state = state("first\n\nsecond", cx);
2818            set(&state, [0..5, 6..12], cx).unwrap();
2819            state.update(cx, |state, cx| state.set_text("first\n\nchanged", cx));
2820            cx.run_until_parked();
2821            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2822            assert!(painted(&state, TextLeafKey::block(7), cx).is_empty());
2823
2824            let large = "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1);
2825            state.update(cx, |state, cx| state.set_text(&large, cx));
2826            cx.run_until_parked();
2827            assert!(!has_highlights(&state, cx));
2828        }
2829
2830        #[gpui::test]
2831        fn a_highlight_follows_its_block_past_an_earlier_edit(cx: &mut TestAppContext) {
2832            let state = state("foo\n\nbar\n\nbar", cx);
2833            // "foo\nbar\nbar\n": the first "bar", in the block at source 5.
2834            set(&state, [4..7], cx).unwrap();
2835            // Deleting "foo" moves that "bar" to 0, and the second one to 5.
2836            state.update(cx, |state, cx| state.set_text("bar\n\nbar", cx));
2837            cx.run_until_parked();
2838            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..3]);
2839            assert!(painted(&state, TextLeafKey::block(5), cx).is_empty());
2840
2841            let state = self::state("ERROR a\n\nERROR b\n\nERROR c", cx);
2842            set(&state, [8..15], cx).unwrap();
2843            state.update(cx, |state, cx| state.set_text("ERROR b\n\nERROR c", cx));
2844            cx.run_until_parked();
2845            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..7]);
2846            assert!(painted(&state, TextLeafKey::block(9), cx).is_empty());
2847        }
2848
2849        #[gpui::test]
2850        fn appending_a_copy_of_the_last_block_keeps_the_highlight_on_it(cx: &mut TestAppContext) {
2851            let state = state("a\n\nfoo", cx);
2852            // "a\nfoo\n"
2853            set(&state, [2..5], cx).unwrap();
2854            state.update(cx, |state, cx| state.set_text("a\n\nfoo\n\nfoo", cx));
2855            cx.run_until_parked();
2856            assert_eq!(painted(&state, TextLeafKey::block(3), cx), [0..3]);
2857            assert!(painted(&state, TextLeafKey::block(8), cx).is_empty());
2858        }
2859
2860        #[gpui::test]
2861        fn deleting_a_table_row_drops_highlights_in_the_rows_it_moves(cx: &mut TestAppContext) {
2862            let table = "| a | b |\n|---|---|\n| x | 1 |\n| x | 2 |";
2863            let without_middle_row = "| a | b |\n|---|---|\n| x | 2 |";
2864            // "a b\nx 1\nx 2\n\n": the last row's cells, then the middle
2865            // row's "x".
2866            for ranges in [vec![8..9, 10..11], vec![4..5]] {
2867                let state = state(table, cx);
2868                set(&state, [0..1].into_iter().chain(ranges), cx).unwrap();
2869                state.update(cx, |state, cx| state.set_text(without_middle_row, cx));
2870                cx.run_until_parked();
2871                assert_eq!(painted(&state, TextLeafKey::table_cell(0, 0), cx), [0..1]);
2872                for cell in 1..4 {
2873                    assert!(
2874                        painted(&state, TextLeafKey::table_cell(0, cell), cx).is_empty(),
2875                        "cell {cell}"
2876                    );
2877                }
2878            }
2879        }
2880
2881        #[gpui::test]
2882        fn streaming_table_rows_keeps_the_highlights_of_earlier_rows(cx: &mut TestAppContext) {
2883            let state = state("| a | b |\n|---|---|\n| x | 1 |", cx);
2884            // "a b\nx 1\n\n"
2885            set(&state, [0..1, 4..5], cx).unwrap();
2886            state.update(cx, |state, cx| {
2887                state.set_text("| a | b |\n|---|---|\n| x | 1 |\n| y | 2 |", cx)
2888            });
2889            cx.run_until_parked();
2890            assert_eq!(painted(&state, TextLeafKey::table_cell(0, 0), cx), [0..1]);
2891            assert_eq!(painted(&state, TextLeafKey::table_cell(0, 2), cx), [0..1]);
2892        }
2893
2894        #[gpui::test]
2895        fn an_edit_in_an_earlier_block_keeps_later_highlights(cx: &mut TestAppContext) {
2896            let state = state("one\n\ntwo", cx);
2897            set(&state, [0..3, 4..7], cx).unwrap();
2898            state.update(cx, |state, cx| state.set_text("one!\n\ntwo", cx));
2899            cx.run_until_parked();
2900            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..3]);
2901            assert_eq!(painted(&state, TextLeafKey::block(6), cx), [0..3]);
2902        }
2903
2904        #[gpui::test]
2905        fn an_append_after_a_full_update_compares_every_block(cx: &mut TestAppContext) {
2906            let state = state("first\n\nsecond", cx);
2907            set(&state, [0..5], cx).unwrap();
2908            // An append result whose baseline was a full update that has not
2909            // been committed: its earlier blocks are not the current ones.
2910            let options = UpdateOptions {
2911                revision: 0,
2912                pending_text: "FIRST\n\nsecond".to_string(),
2913                append: false,
2914                mode: ParseMode::Replace,
2915                markdown_extensions: Arc::default(),
2916            };
2917            let new = parse_content(TextViewFormat::Markdown, ParsedContent::default(), &options)
2918                .unwrap()
2919                .document;
2920            state.update(cx, |state, _| {
2921                state.full_update_revision = state.committed_revision + 1;
2922                let revision = state.committed_revision + 2;
2923                state.reconcile_range_highlights(&new, revision, true);
2924            });
2925            assert!(!has_highlights(&state, cx));
2926        }
2927
2928        #[gpui::test]
2929        fn streaming_through_set_text_keeps_highlights(cx: &mut TestAppContext) {
2930            let state = state("first\n\nsec", cx);
2931            // "first\nsec\n"
2932            set(&state, [0..5, 6..9], cx).unwrap();
2933            state.update(cx, |state, cx| state.set_text("first\n\nsecond", cx));
2934            cx.run_until_parked();
2935            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2936            assert_eq!(painted(&state, TextLeafKey::block(7), cx), [0..3]);
2937        }
2938
2939        #[gpui::test]
2940        fn a_full_parse_merged_with_an_append_compares_every_block(cx: &mut TestAppContext) {
2941            let state = state("", cx);
2942            // The small text is committed at once, and its background parse
2943            // merges with the append into one full parse, in which the
2944            // definition turns the earlier `[foo]` into the link text `foo`.
2945            state.update(cx, |state, cx| {
2946                state.set_text("[foo] and some text\n\nmore", cx);
2947                let text = state.rendered_text();
2948                let some = text.as_str().find("some").unwrap();
2949                state
2950                    .set_range_highlights([highlight(some..some + 4)], cx)
2951                    .unwrap();
2952                state.push_str("\n\n[foo]: https://example.com", cx);
2953            });
2954            cx.run_until_parked();
2955            state.read_with(cx, |state, _| {
2956                assert!(state.rendered_text().as_str().starts_with("foo and some"));
2957            });
2958            assert!(painted(&state, TextLeafKey::block(0), cx).is_empty());
2959        }
2960
2961        #[gpui::test]
2962        fn a_full_update_before_an_append_drops_replaced_highlights(cx: &mut TestAppContext) {
2963            let state = state("first", cx);
2964            set(&state, [0..5], cx).unwrap();
2965            let large = "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1);
2966            state.update(cx, |state, cx| {
2967                state.set_text(&large, cx);
2968                state.push_str(" tail", cx);
2969            });
2970            cx.run_until_parked();
2971            assert!(!has_highlights(&state, cx));
2972        }
2973
2974        #[gpui::test]
2975        fn reparsing_unchanged_text_keeps_highlights(cx: &mut TestAppContext) {
2976            let state = state("first", cx);
2977            set(&state, [0..5], cx).unwrap();
2978            state.update(cx, |state, cx| {
2979                state.set_markdown_extensions(
2980                    Arc::new(MarkdownExtensions::default().parser_revision(1)),
2981                    cx,
2982                )
2983            });
2984            cx.run_until_parked();
2985            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..5]);
2986        }
2987
2988        pub(super) struct Root {
2989            pub(super) state: Entity<TextViewState>,
2990        }
2991
2992        impl Render for Root {
2993            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2994                gpui::div()
2995                    .w(px(120.))
2996                    .child(crate::text::TextView::new(&self.state).selectable(true))
2997            }
2998        }
2999
3000        #[gpui::test]
3001        fn highlights_paint_across_inline_code_tables_and_code_blocks(cx: &mut TestAppContext) {
3002            cx.update(crate::init);
3003            let markdown = "wrapping text with `inline code` and a [link](https://x.y) \
3004                            that wraps\n\n| a | b |\n|---|---|\n| c | d |\n\n```\nlet x = 1;\n```";
3005            let (root, cx) = cx.add_window_view(|_, cx| Root {
3006                state: cx.new(|cx| TextViewState::markdown(markdown, cx)),
3007            });
3008            cx.run_until_parked();
3009            let state = root.read_with(cx, |root, _| root.state.clone());
3010            let text = state.read_with(cx, |state, _| state.rendered_text().as_str().to_string());
3011            let code = text.find("code").unwrap();
3012            let len = text.len();
3013            // Part of the inline code, every character, and the whole text.
3014            let ranges = [code..code + 2]
3015                .into_iter()
3016                .chain(text.char_indices().map(|(ix, c)| ix..ix + c.len_utf8()))
3017                .chain([0..len])
3018                .filter(|range| !text[range.clone()].trim().is_empty());
3019            state.update(cx, |state, cx| {
3020                state
3021                    .set_range_highlights(ranges.map(highlight), cx)
3022                    .unwrap();
3023            });
3024            cx.update(|window, cx| window.draw(cx).clear(cx));
3025            assert_eq!(
3026                painted(&state, TextLeafKey::block(0), cx)[0],
3027                code..code + 2
3028            );
3029        }
3030
3031        /// The ranges of the current rendered text converted from `sources`.
3032        fn converted(
3033            state: &Entity<TextViewState>,
3034            sources: impl IntoIterator<Item = Range<usize>>,
3035            cx: &mut TestAppContext,
3036        ) -> Vec<Option<Range<usize>>> {
3037            state.read_with(cx, |state, _| {
3038                let text = state.rendered_text();
3039                sources
3040                    .into_iter()
3041                    .map(|source| text.range_for_source(source))
3042                    .collect()
3043            })
3044        }
3045
3046        fn find(haystack: &str, needle: &str) -> Range<usize> {
3047            let start = haystack.find(needle).unwrap();
3048            start..start + needle.len()
3049        }
3050
3051        #[gpui::test]
3052        fn source_ranges_highlight_the_text_rendered_from_them(cx: &mut TestAppContext) {
3053            let markdown =
3054                "In Rust, we use `u128` to handle **larger** numbers\n\n| a | **b** |\n|---|---|";
3055            let state = state(markdown, cx);
3056            state.update(cx, |state, cx| {
3057                let text = state.rendered_text();
3058                assert_eq!(text.source(), markdown);
3059                let highlights = ["`u128` to handle **larger**", "**b**"]
3060                    .into_iter()
3061                    .map(|needle| text.range_for_source(find(markdown, needle)).unwrap())
3062                    .map(highlight)
3063                    .collect::<Vec<_>>();
3064                state.set_range_highlights(highlights, cx).unwrap();
3065            });
3066            let rendered = "In Rust, we use u128 to handle larger numbers";
3067            assert_eq!(
3068                painted(&state, TextLeafKey::block(0), cx),
3069                [find(rendered, "u128 to handle larger")]
3070            );
3071            let table = markdown.find("| a").unwrap();
3072            assert_eq!(
3073                painted(&state, TextLeafKey::table_cell(table, 1), cx),
3074                [0..1]
3075            );
3076        }
3077
3078        #[gpui::test]
3079        fn select_all_converts_to_every_rendered_character(cx: &mut TestAppContext) {
3080            let markdown = "# Title\n\nhello **world**\n\n- item";
3081            let state = state(markdown, cx);
3082            state.update(cx, |state, cx| state.select_all(cx));
3083            state.read_with(cx, |state, _| {
3084                let text = state.rendered_text();
3085                assert_eq!(text.as_str(), "Title\nhello world\nitem\n");
3086                let source = state.selected_source_range().unwrap();
3087                // All but the separator after the last block.
3088                assert_eq!(text.range_for_source(source), Some(0..text.len() - 1));
3089            });
3090        }
3091
3092        #[gpui::test]
3093        fn a_snapshot_converts_against_its_own_source(cx: &mut TestAppContext) {
3094            let state = state("first", cx);
3095            let before = state.read_with(cx, |state, _| state.rendered_text());
3096            state.update(cx, |state, cx| state.push_str("\n\nsecond **part**", cx));
3097            let source = "first\n\nsecond **part**";
3098            let second = find(source, "second **part**");
3099
3100            // The append is parsed in the background, so until it lands the
3101            // view renders the source it had.
3102            state.read_with(cx, |state, _| {
3103                let text = state.rendered_text();
3104                assert_eq!(text, before);
3105                assert_eq!(text.source(), "first");
3106                assert_eq!(text.range_for_source(second.clone()), None);
3107            });
3108            cx.run_until_parked();
3109
3110            assert_eq!(
3111                converted(&state, [second.clone(), 0..5], cx),
3112                [Some(6..17), Some(0..5)]
3113            );
3114            state.read_with(cx, |state, _| {
3115                let text = state.rendered_text();
3116                assert_ne!(text, before);
3117                assert_eq!(text.source(), source);
3118                assert_eq!(&text.as_str()[6..17], "second part");
3119            });
3120            // An earlier snapshot keeps converting against its own source.
3121            assert_eq!(before.source(), "first");
3122            assert_eq!(before.range_for_source(0..5), Some(0..5));
3123            assert_eq!(before.range_for_source(second), None);
3124        }
3125
3126        #[gpui::test]
3127        fn appended_blocks_convert_at_their_place_in_the_whole_source(cx: &mut TestAppContext) {
3128            let state = state("first\n\nsecond", cx);
3129            // The tail parse reparses from the last block, whose positions
3130            // must still count from the start of the whole source.
3131            state.update(cx, |state, cx| state.push_str(" more\n\n**écho** end", cx));
3132            cx.run_until_parked();
3133            let source = "first\n\nsecond more\n\n**écho** end";
3134            let converted = converted(
3135                &state,
3136                [
3137                    find(source, "second more"),
3138                    find(source, "**écho**"),
3139                    find(source, "end"),
3140                ],
3141                cx,
3142            );
3143            state.read_with(cx, |state, _| {
3144                let text = state.rendered_text();
3145                assert_eq!(text.source(), source);
3146                let texts = converted
3147                    .into_iter()
3148                    .map(|range| &text.as_str()[range.unwrap()])
3149                    .collect::<Vec<_>>();
3150                assert_eq!(texts, ["second more", "écho", "end"]);
3151            });
3152        }
3153
3154        #[gpui::test]
3155        fn a_background_parse_converts_once_it_lands(cx: &mut TestAppContext) {
3156            cx.update(crate::init);
3157            let markdown = format!(
3158                "{}\n\n**tail**",
3159                "word ".repeat(MAX_SYNC_FULL_REPLACE_BYTES / 4)
3160            );
3161            let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(&markdown, cx)));
3162            let tail = find(&markdown, "**tail**");
3163            state.read_with(cx, |state, _| {
3164                let text = state.rendered_text();
3165                assert!(text.source().is_empty());
3166                assert!(text.is_empty());
3167                assert_eq!(text.range_for_source(tail.clone()), None);
3168            });
3169            cx.run_until_parked();
3170            state.read_with(cx, |state, _| {
3171                let text = state.rendered_text();
3172                assert_eq!(text.source(), markdown);
3173                let range = text.range_for_source(tail).unwrap();
3174                assert_eq!(&text.as_str()[range], "tail");
3175            });
3176        }
3177
3178        #[gpui::test]
3179        fn inline_objects_convert_whole_and_stay_unpainted(cx: &mut TestAppContext) {
3180            let markdown = "x $ab$ y";
3181            let state = state(markdown, cx);
3182            state.update(cx, |state, cx| {
3183                let extensions = MarkdownExtensions::default().plugin(
3184                    crate::text::markdown_ext::TestInlinePlugin::new("test").parse_with(
3185                        |node, _| {
3186                            let markdown::mdast::Node::InlineMath(math) = node else {
3187                                return None;
3188                            };
3189                            Some(
3190                                crate::text::MarkdownNode::new("formula", ())
3191                                    .text(math.value.clone()),
3192                            )
3193                        },
3194                    ),
3195                );
3196                state.set_markdown_extensions(Arc::new(extensions), cx);
3197            });
3198            cx.run_until_parked();
3199            // "x ab y\n", where "ab" is the formula.
3200            let formula = find(markdown, "$ab$");
3201            assert_eq!(
3202                converted(
3203                    &state,
3204                    [
3205                        formula.clone(),
3206                        formula.start + 1..formula.start + 2,
3207                        0..markdown.len(),
3208                        find(markdown, "ab$ y"),
3209                    ],
3210                    cx
3211                ),
3212                [Some(2..4), Some(2..4), Some(0..6), Some(2..6)]
3213            );
3214            let ranges = converted(&state, [formula, 0..markdown.len()], cx);
3215            set(&state, [ranges[0].clone().unwrap()], cx).unwrap();
3216            assert!(painted(&state, TextLeafKey::block(0), cx).is_empty());
3217            set(&state, [ranges[1].clone().unwrap()], cx).unwrap();
3218            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [0..2, 4..6]);
3219        }
3220
3221        #[gpui::test]
3222        fn a_dragged_selection_highlights_through_its_source_range(cx: &mut TestAppContext) {
3223            struct SelectionRoot {
3224                state: Entity<TextViewState>,
3225            }
3226
3227            impl Render for SelectionRoot {
3228                fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3229                    gpui::div()
3230                        .w(px(160.))
3231                        .child(crate::TextSelectionLayer)
3232                        .child(crate::text::TextView::new(&self.state))
3233                }
3234            }
3235
3236            cx.update(crate::init);
3237            let markdown = "hello **world** and `code` &amp; more";
3238            let (root, cx) = cx.add_window_view(|_, cx| SelectionRoot {
3239                state: cx.new(|cx| TextViewState::markdown(markdown, cx)),
3240            });
3241            cx.run_until_parked();
3242            let state = root.read_with(cx, |root, _| root.state.clone());
3243            cx.update(|window, cx| window.draw(cx).clear(cx));
3244            let bounds = state.read_with(cx, |state, _| state.bounds());
3245            assert!(bounds.size.height > px(30.), "the text wraps, {bounds:?}");
3246            let start = bounds.origin + gpui::point(px(2.), px(4.));
3247            let end = bounds.bottom_right() - gpui::point(px(2.), px(4.));
3248            cx.simulate_mouse_down(start, gpui::MouseButton::Left, gpui::Modifiers::default());
3249            cx.update(|window, cx| window.draw(cx).clear(cx));
3250            cx.simulate_mouse_move(end, gpui::MouseButton::Left, gpui::Modifiers::default());
3251            cx.update(|window, cx| window.draw(cx).clear(cx));
3252            cx.simulate_mouse_up(end, gpui::MouseButton::Left, gpui::Modifiers::default());
3253            cx.update(|window, cx| window.draw(cx).clear(cx));
3254
3255            let range = state.update(cx, |state, cx| {
3256                let selected = state.selected_text();
3257                let source = state
3258                    .selected_source_range()
3259                    .expect("selection maps to source");
3260                let text = state.rendered_text();
3261                let range = text.range_for_source(source).expect("source renders text");
3262                assert!(selected.contains("code &"), "selected {selected:?}");
3263                assert_eq!(
3264                    &text.as_str()[range.clone()],
3265                    selected.trim_end_matches('\n')
3266                );
3267                state.clear_selection(cx);
3268                state
3269                    .set_range_highlights([highlight(range.clone())], cx)
3270                    .unwrap();
3271                range
3272            });
3273            cx.update(|window, cx| window.draw(cx).clear(cx));
3274            assert_eq!(painted(&state, TextLeafKey::block(0), cx), [range]);
3275        }
3276
3277        #[gpui::test]
3278        fn html_views_convert_no_source(cx: &mut TestAppContext) {
3279            let html = cx.update(|cx| cx.new(|cx| TextViewState::html("<p>one</p>", cx)));
3280            cx.run_until_parked();
3281            html.read_with(cx, |html, _| {
3282                let text = html.rendered_text();
3283                assert_eq!(text.source(), "<p>one</p>");
3284                assert_eq!(text.range_for_source(0..10), None);
3285                assert_eq!(text.range_for_source(3..6), None);
3286            });
3287        }
3288
3289        #[gpui::test]
3290        fn clear_range_highlights_removes_them(cx: &mut TestAppContext) {
3291            let state = state("first", cx);
3292            set(&state, [0..5], cx).unwrap();
3293            state.update(cx, |state, cx| state.clear_range_highlights(cx));
3294            assert!(!has_highlights(&state, cx));
3295        }
3296    }
3297
3298    mod reveal_range {
3299        use gpui::{
3300            Entity, InteractiveElement as _, ListAlignment, ListState, ScrollHandle,
3301            StatefulInteractiveElement as _, TestAppContext, VisualTestContext, div, list,
3302        };
3303
3304        use super::super::*;
3305        use crate::text::TextView;
3306
3307        /// Where the view sits in a 200 × 100 window.
3308        #[derive(Clone)]
3309        enum Container {
3310            /// A scrollable view.
3311            Scrollable,
3312            /// A fit-content view, second row of an application list.
3313            List(ListState),
3314            /// A fit-content view in a scrolling `div`, which follows reveals
3315            /// through `on_reveal`.
3316            Div(ScrollHandle),
3317            /// A fit-content view clamped to two lines, second row of a list.
3318            Clamped(ListState),
3319            /// A fit-content view in nothing that scrolls.
3320            Fixed,
3321        }
3322
3323        struct Root {
3324            state: Entity<TextViewState>,
3325            container: Container,
3326        }
3327
3328        impl Render for Root {
3329            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3330                let state = self.state.clone();
3331                let frame = div().w(px(200.)).h(px(100.));
3332                let row = |list_state: &ListState, clamp: bool| {
3333                    let state = state.clone();
3334                    list(list_state.clone(), move |ix, _, _| match ix {
3335                        0 => div().h(px(40.)).into_any_element(),
3336                        _ => TextView::new(&state)
3337                            .when(clamp, |view| view.max_lines(2))
3338                            .into_any_element(),
3339                    })
3340                    .size_full()
3341                };
3342                match &self.container {
3343                    Container::Scrollable => frame
3344                        .child(TextView::new(&state).scrollable(true))
3345                        .into_any_element(),
3346                    Container::List(list_state) => {
3347                        frame.child(row(list_state, false)).into_any_element()
3348                    }
3349                    Container::Clamped(list_state) => {
3350                        frame.child(row(list_state, true)).into_any_element()
3351                    }
3352                    Container::Div(handle) => {
3353                        let scroll = handle.clone();
3354                        frame
3355                            .child(
3356                                div()
3357                                    .id("scroll")
3358                                    .size_full()
3359                                    .overflow_y_scroll()
3360                                    .track_scroll(handle)
3361                                    .child(TextView::new(&state).on_reveal(move |line, _, _| {
3362                                        let viewport = scroll.bounds();
3363                                        let mut offset = scroll.offset();
3364                                        if line.bottom() > viewport.bottom() {
3365                                            offset.y -= line.bottom() - viewport.bottom();
3366                                        } else if line.top() < viewport.top() {
3367                                            offset.y += viewport.top() - line.top();
3368                                        }
3369                                        scroll.set_offset(offset);
3370                                    })),
3371                            )
3372                            .into_any_element()
3373                    }
3374                    Container::Fixed => frame.child(TextView::new(&state)).into_any_element(),
3375                }
3376            }
3377        }
3378
3379        fn window<'a>(
3380            markdown: &str,
3381            container: Container,
3382            cx: &'a mut TestAppContext,
3383        ) -> (Entity<TextViewState>, &'a mut VisualTestContext) {
3384            cx.update(crate::init);
3385            let (root, cx) = cx.add_window_view(|_, cx| Root {
3386                state: cx.new(|cx| TextViewState::markdown(markdown, cx)),
3387                container,
3388            });
3389            cx.run_until_parked();
3390            draw(cx);
3391            let state = root.read_with(cx, |root, _| root.state.clone());
3392            (state, cx)
3393        }
3394
3395        fn draw(cx: &mut VisualTestContext) {
3396            cx.update(|window, cx| window.draw(cx).clear(cx));
3397        }
3398
3399        /// Asks to reveal the first occurrence of `needle`, then runs `then`
3400        /// before anything is drawn.
3401        fn request(
3402            state: &Entity<TextViewState>,
3403            needle: &str,
3404            cx: &mut VisualTestContext,
3405            then: impl FnOnce(&mut TextViewState, &mut Context<TextViewState>),
3406        ) {
3407            state.update(cx, |state, cx| {
3408                let text = state.rendered_text();
3409                let start = text.as_str().find(needle).unwrap();
3410                state.reveal_range(start..start + needle.len(), cx).unwrap();
3411                then(state, cx);
3412            });
3413        }
3414
3415        /// Reveals the first occurrence of `needle` and draws a few frames.
3416        fn reveal(state: &Entity<TextViewState>, needle: &str, cx: &mut VisualTestContext) {
3417            request(state, needle, cx, |_, _| {});
3418            for _ in 0..3 {
3419                draw(cx);
3420            }
3421        }
3422
3423        fn is_pending(state: &Entity<TextViewState>, cx: &mut VisualTestContext) -> bool {
3424            state.read_with(cx, |state, _| state.pending_reveal.is_some())
3425        }
3426
3427        fn scroll_top(
3428            state: &Entity<TextViewState>,
3429            cx: &mut VisualTestContext,
3430        ) -> gpui::ListOffset {
3431            state.read_with(cx, |state, _| state.list_state.logical_scroll_top())
3432        }
3433
3434        fn paragraphs(count: usize) -> String {
3435            (0..count)
3436                .map(|ix| format!("paragraph {ix}"))
3437                .collect::<Vec<_>>()
3438                .join("\n\n")
3439        }
3440
3441        fn words(count: usize) -> String {
3442            (0..count)
3443                .map(|ix| format!("w{ix}"))
3444                .collect::<Vec<_>>()
3445                .join(" ")
3446        }
3447
3448        #[gpui::test]
3449        fn a_scrollable_view_scrolls_to_an_offscreen_block(cx: &mut TestAppContext) {
3450            let (state, cx) = window(&paragraphs(200), Container::Scrollable, cx);
3451            reveal(&state, "paragraph 150", cx);
3452            assert!(!is_pending(&state, cx));
3453            let top = scroll_top(&state, cx);
3454            assert!((140..=150).contains(&top.item_ix), "{top:?}");
3455
3456            reveal(&state, "paragraph 3", cx);
3457            assert!(!is_pending(&state, cx));
3458            assert!(scroll_top(&state, cx).item_ix <= 3);
3459        }
3460
3461        #[gpui::test]
3462        fn an_append_adding_blocks_keeps_the_scroll_position(cx: &mut TestAppContext) {
3463            let (state, cx) = window(&paragraphs(200), Container::Scrollable, cx);
3464            reveal(&state, "paragraph 100", cx);
3465            let top = scroll_top(&state, cx);
3466            assert!(top.item_ix > 0, "{top:?}");
3467
3468            state.update(cx, |state, cx| state.push_str("\n\nparagraph 200", cx));
3469            cx.run_until_parked();
3470            draw(cx);
3471
3472            state.read_with(cx, |state, _| {
3473                assert_eq!(state.list_state.item_count(), 201);
3474            });
3475            assert_unmoved(&state, top, cx);
3476        }
3477
3478        #[gpui::test]
3479        fn a_scrollable_view_scrolls_to_a_line_inside_a_long_paragraph(cx: &mut TestAppContext) {
3480            let (state, cx) = window(&words(400), Container::Scrollable, cx);
3481            reveal(&state, "w390", cx);
3482            assert!(!is_pending(&state, cx));
3483            let top = scroll_top(&state, cx);
3484            assert_eq!(top.item_ix, 0);
3485            assert!(top.offset_in_item > px(100.), "{top:?}");
3486        }
3487
3488        #[gpui::test]
3489        fn revealing_a_visible_line_does_not_scroll(cx: &mut TestAppContext) {
3490            let (state, cx) = window(&words(400), Container::Scrollable, cx);
3491            reveal(&state, "w200", cx);
3492            let top = scroll_top(&state, cx);
3493            assert!(top.offset_in_item > px(0.), "{top:?}");
3494            for word in ["w199", "w198", "w197", "w196"] {
3495                reveal(&state, word, cx);
3496                assert!(!is_pending(&state, cx));
3497                let now = scroll_top(&state, cx);
3498                assert_eq!(
3499                    (now.item_ix, now.offset_in_item),
3500                    (top.item_ix, top.offset_in_item),
3501                    "{word}"
3502                );
3503            }
3504        }
3505
3506        #[gpui::test]
3507        fn an_enclosing_list_scrolls_to_a_line_of_a_fit_content_view(cx: &mut TestAppContext) {
3508            let outer = ListState::new(2, ListAlignment::Top, px(1000.));
3509            let (state, cx) = window(&words(400), Container::List(outer.clone()), cx);
3510            reveal(&state, "w390", cx);
3511            assert!(!is_pending(&state, cx));
3512            let top = outer.logical_scroll_top();
3513            assert_eq!(top.item_ix, 1, "{top:?}");
3514            assert!(top.offset_in_item > px(100.), "{top:?}");
3515        }
3516
3517        #[gpui::test]
3518        fn on_reveal_scrolls_a_container_that_ignores_scroll_requests(cx: &mut TestAppContext) {
3519            let handle = ScrollHandle::new();
3520            let (state, cx) = window(&words(400), Container::Div(handle.clone()), cx);
3521            reveal(&state, "w390", cx);
3522            assert!(!is_pending(&state, cx));
3523            assert!(handle.offset().y < px(-100.), "{:?}", handle.offset());
3524        }
3525
3526        #[gpui::test]
3527        fn a_reveal_that_cannot_be_shown_gives_up(cx: &mut TestAppContext) {
3528            let (state, cx) = window(&words(4000), Container::Fixed, cx);
3529            reveal(&state, "w3990", cx);
3530            assert!(is_pending(&state, cx));
3531            for _ in 0..10 {
3532                draw(cx);
3533            }
3534            assert!(!is_pending(&state, cx));
3535        }
3536
3537        #[gpui::test]
3538        fn a_reveal_not_carried_out_in_time_is_dropped(cx: &mut TestAppContext) {
3539            let (state, cx) = window(&paragraphs(200), Container::Scrollable, cx);
3540            request(&state, "paragraph 150", cx, |_, cx| {
3541                cx.background_executor()
3542                    .advance_clock(std::time::Duration::from_secs(2))
3543            });
3544            draw(cx);
3545            assert!(!is_pending(&state, cx));
3546            assert_eq!(scroll_top(&state, cx).item_ix, 0);
3547        }
3548
3549        #[gpui::test]
3550        fn an_empty_range_reveals_its_line(cx: &mut TestAppContext) {
3551            let (state, cx) = window(&words(400), Container::Scrollable, cx);
3552            reveal(&state, "w390", cx);
3553            let top = scroll_top(&state, cx);
3554            // A position on a visible line leaves the view where it is.
3555            state.update(cx, |state, cx| {
3556                let text = state.rendered_text();
3557                let start = text.as_str().find("w391").unwrap();
3558                state.reveal_range(start..start, cx).unwrap();
3559            });
3560            for _ in 0..3 {
3561                draw(cx);
3562            }
3563            assert!(!is_pending(&state, cx));
3564            let now = scroll_top(&state, cx);
3565            assert_eq!(
3566                (now.item_ix, now.offset_in_item),
3567                (top.item_ix, top.offset_in_item)
3568            );
3569        }
3570
3571        #[gpui::test]
3572        fn a_position_after_the_last_character_reveals_its_line(cx: &mut TestAppContext) {
3573            let (state, cx) = window(&words(400), Container::Scrollable, cx);
3574            reveal(&state, "w399", cx);
3575            let top = scroll_top(&state, cx);
3576            assert!(top.offset_in_item > px(1000.), "{top:?}");
3577            // The end of the text, on the visible last line.
3578            state.update(cx, |state, cx| {
3579                let text = state.rendered_text();
3580                let end = text.as_str().find("w399").unwrap() + "w399".len();
3581                state.reveal_range(end..end, cx).unwrap();
3582            });
3583            for _ in 0..3 {
3584                draw(cx);
3585            }
3586            assert!(!is_pending(&state, cx));
3587            let now = scroll_top(&state, cx);
3588            assert_eq!(
3589                (now.item_ix, now.offset_in_item),
3590                (top.item_ix, top.offset_in_item)
3591            );
3592        }
3593
3594        /// Reveals `range` of the current text and draws a few frames.
3595        fn reveal_at(
3596            state: &Entity<TextViewState>,
3597            range: impl FnOnce(&str) -> std::ops::Range<usize>,
3598            cx: &mut VisualTestContext,
3599        ) {
3600            state.update(cx, |state, cx| {
3601                let text = state.rendered_text();
3602                let range = range(text.as_str());
3603                state.reveal_range(range, cx).unwrap();
3604            });
3605            for _ in 0..3 {
3606                draw(cx);
3607            }
3608        }
3609
3610        fn assert_unmoved(
3611            state: &Entity<TextViewState>,
3612            top: gpui::ListOffset,
3613            cx: &mut VisualTestContext,
3614        ) {
3615            assert!(!is_pending(state, cx));
3616            let now = scroll_top(state, cx);
3617            assert_eq!(
3618                (now.item_ix, now.offset_in_item),
3619                (top.item_ix, top.offset_in_item)
3620            );
3621        }
3622
3623        #[gpui::test]
3624        fn the_end_of_the_text_and_its_separators_reveal_the_last_line(cx: &mut TestAppContext) {
3625            let (state, cx) = window(&words(400), Container::Scrollable, cx);
3626            reveal(&state, "w399", cx);
3627            let top = scroll_top(&state, cx);
3628            assert!(top.offset_in_item > px(1000.), "{top:?}");
3629            // The end of the text, after the separator that ends the block.
3630            reveal_at(&state, |text| text.len()..text.len(), cx);
3631            assert_unmoved(&state, top, cx);
3632            // Only that separator.
3633            reveal_at(&state, |text| text.len() - 1..text.len(), cx);
3634            assert_unmoved(&state, top, cx);
3635
3636            let code = (0..200)
3637                .map(|ix| format!("line {ix}"))
3638                .collect::<Vec<_>>()
3639                .join("\n");
3640            state.update(cx, |state, cx| {
3641                state.set_text(&format!("```\n{code}\n```"), cx)
3642            });
3643            cx.run_until_parked();
3644            reveal(&state, "line 199", cx);
3645            let top = scroll_top(&state, cx);
3646            assert!(top.offset_in_item > px(1000.), "{top:?}");
3647            reveal_at(&state, |text| text.len()..text.len(), cx);
3648            assert_unmoved(&state, top, cx);
3649        }
3650
3651        #[gpui::test]
3652        fn the_end_of_a_block_above_reveals_its_last_line(cx: &mut TestAppContext) {
3653            let second = (0..400)
3654                .map(|ix| format!("v{ix}"))
3655                .collect::<Vec<_>>()
3656                .join(" ");
3657            let markdown = format!("{}\n\n{second}", words(400));
3658            let (state, cx) = window(&markdown, Container::Scrollable, cx);
3659            reveal(&state, "v399", cx);
3660            assert_eq!(scroll_top(&state, cx).item_ix, 1);
3661            // The end of the first paragraph, on the separator after it.
3662            reveal_at(
3663                &state,
3664                |text| {
3665                    let end = text.find("w399").unwrap() + "w399".len();
3666                    end..end
3667                },
3668                cx,
3669            );
3670            assert!(!is_pending(&state, cx));
3671            let top = scroll_top(&state, cx);
3672            assert_eq!(top.item_ix, 0, "{top:?}");
3673            assert!(top.offset_in_item > px(1000.), "{top:?}");
3674        }
3675
3676        #[gpui::test]
3677        fn an_empty_view_has_nothing_to_reveal(cx: &mut TestAppContext) {
3678            cx.update(crate::init);
3679            let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("", cx)));
3680            cx.run_until_parked();
3681            state.update(cx, |state, cx| {
3682                assert_eq!(state.reveal_range(0..0, cx), Ok(()));
3683                assert!(state.pending_reveal.is_none());
3684            });
3685        }
3686
3687        #[gpui::test]
3688        fn revealing_a_visible_block_does_not_scroll(cx: &mut TestAppContext) {
3689            let markdown = format!("{}\n\n<div>html</div>\n\n{}", words(400), words(400));
3690            let (state, cx) = window(&markdown, Container::Scrollable, cx);
3691            reveal(&state, "html", cx);
3692            // Still in view a little further down.
3693            state.update(cx, |state, _| state.list_state.scroll_by(px(30.)));
3694            draw(cx);
3695            let top = scroll_top(&state, cx);
3696            reveal(&state, "html", cx);
3697            assert_unmoved(&state, top, cx);
3698        }
3699
3700        #[gpui::test]
3701        fn a_line_of_an_inline_flow_counts_as_shown_once_scrolled_to(cx: &mut TestAppContext) {
3702            // Inline code every tenth word, so the rows are taller than the
3703            // body line and land between pixels.
3704            let markdown = (0..400)
3705                .map(|ix| {
3706                    if ix % 10 == 0 {
3707                        format!("`c{ix}`")
3708                    } else {
3709                        format!("w{ix}")
3710                    }
3711                })
3712                .collect::<Vec<_>>()
3713                .join(" ");
3714            let (state, cx) = window(&markdown, Container::Scrollable, cx);
3715            reveal(&state, "c390", cx);
3716            assert!(!is_pending(&state, cx));
3717            assert!(scroll_top(&state, cx).offset_in_item > px(1000.));
3718        }
3719
3720        #[gpui::test]
3721        fn a_range_starting_on_a_line_break_reveals_the_next_line(cx: &mut TestAppContext) {
3722            let code = (0..200)
3723                .map(|ix| format!("line {ix}"))
3724                .collect::<Vec<_>>()
3725                .join("\n");
3726            let (state, cx) = window(&format!("```\n{code}\n```"), Container::Scrollable, cx);
3727            reveal(&state, "\nline 190", cx);
3728            assert!(!is_pending(&state, cx));
3729            let top = scroll_top(&state, cx);
3730            assert!(top.offset_in_item > px(1000.), "{top:?}");
3731        }
3732
3733        #[gpui::test]
3734        fn a_range_starting_on_a_line_break_in_an_inline_flow_reveals_the_next_line(
3735            cx: &mut TestAppContext,
3736        ) {
3737            // Inline code lays the paragraph out as an inline flow.
3738            let lines = (0..200)
3739                .map(|ix| format!("line {ix} `code`"))
3740                .collect::<Vec<_>>()
3741                .join("\\\n");
3742            let (state, cx) = window(&lines, Container::Scrollable, cx);
3743            reveal(&state, "\nline 190", cx);
3744            assert!(!is_pending(&state, cx));
3745            let top = scroll_top(&state, cx);
3746            assert!(top.offset_in_item > px(1000.), "{top:?}");
3747        }
3748
3749        #[gpui::test]
3750        fn a_reveal_is_dropped_when_its_text_before_it_changes(cx: &mut TestAppContext) {
3751            let (state, cx) = window(&paragraphs(200), Container::Scrollable, cx);
3752            let target = "first words then the target";
3753            let markdown = format!("{target}\n\n{}", paragraphs(200));
3754            state.update(cx, |state, cx| state.set_text(&markdown, cx));
3755            cx.run_until_parked();
3756
3757            // Appending to its paragraph keeps it.
3758            request(&state, "target", cx, |state, cx| {
3759                state.set_text(&markdown.replacen("target", "target and more", 1), cx);
3760                assert!(state.pending_reveal.is_some());
3761            });
3762            // An edit before it in its paragraph drops it.
3763            request(&state, "target", cx, |state, cx| {
3764                state.set_text(&markdown.replacen("words", "WORDS", 1), cx);
3765                assert!(state.pending_reveal.is_none());
3766            });
3767        }
3768
3769        #[gpui::test]
3770        fn a_clamped_view_does_not_reveal(cx: &mut TestAppContext) {
3771            let outer = ListState::new(2, ListAlignment::Top, px(1000.));
3772            let (state, cx) = window(&words(400), Container::Clamped(outer.clone()), cx);
3773            reveal(&state, "w390", cx);
3774            assert!(!is_pending(&state, cx));
3775            assert_eq!(outer.logical_scroll_top().item_ix, 0);
3776        }
3777
3778        #[gpui::test]
3779        fn text_outside_every_block_reveals_its_block(cx: &mut TestAppContext) {
3780            let markdown = format!("{}\n\n<div>html text</div>", paragraphs(100));
3781            let (state, cx) = window(&markdown, Container::Scrollable, cx);
3782            reveal(&state, "html text", cx);
3783            assert!(!is_pending(&state, cx));
3784            assert!(
3785                scroll_top(&state, cx).item_ix >= 90,
3786                "{:?}",
3787                scroll_top(&state, cx)
3788            );
3789        }
3790
3791        #[gpui::test]
3792        fn a_reveal_follows_its_text_past_an_edit_before_it(cx: &mut TestAppContext) {
3793            let (state, cx) = window(&paragraphs(200), Container::Scrollable, cx);
3794            // An inserted paragraph moves the target down one block.
3795            request(&state, "paragraph 150", cx, |state, cx| {
3796                state.set_text(&format!("inserted\n\n{}", paragraphs(200)), cx);
3797                assert!(state.pending_reveal.is_some());
3798            });
3799            for _ in 0..3 {
3800                draw(cx);
3801            }
3802            assert!(!is_pending(&state, cx));
3803            let top = scroll_top(&state, cx);
3804            assert!((141..=151).contains(&top.item_ix), "{top:?}");
3805
3806            // A reveal whose text changed is dropped.
3807            request(&state, "paragraph 150", cx, |state, cx| {
3808                state.set_text(&paragraphs(200).replace("paragraph 150", "changed"), cx);
3809                assert!(state.pending_reveal.is_none());
3810            });
3811        }
3812
3813        #[gpui::test]
3814        fn malformed_ranges_and_html_views_are_rejected(cx: &mut TestAppContext) {
3815            cx.update(crate::init);
3816            let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("first\n\nsecond", cx)));
3817            cx.run_until_parked();
3818            state.update(cx, |state, cx| {
3819                assert_eq!(
3820                    state.reveal_range(std::ops::Range { start: 5, end: 3 }, cx),
3821                    Err(RangeHighlightError::InvalidRange(0))
3822                );
3823                assert_eq!(
3824                    state.reveal_range(0..100, cx),
3825                    Err(RangeHighlightError::InvalidRange(0))
3826                );
3827                state.reveal_range(0..5, cx).unwrap();
3828            });
3829
3830            let html = cx.update(|cx| cx.new(|cx| TextViewState::html("<p>one</p>", cx)));
3831            cx.run_until_parked();
3832            html.update(cx, |html, cx| {
3833                assert_eq!(
3834                    html.reveal_range(0..3, cx),
3835                    Err(RangeHighlightError::Unsupported)
3836                );
3837            });
3838        }
3839    }
3840}