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