Skip to main content

gpui_component/text/
state.rs

1use futures::Stream as _;
2use std::{
3    ops::RangeInclusive,
4    pin::Pin,
5    sync::{Arc, Mutex},
6    task::Poll,
7};
8
9use gpui::{
10    App, AppContext as _, Bounds, Context, FocusHandle, IntoElement, KeyBinding, ListState,
11    ParentElement as _, Pixels, Point, Render, SharedString, Styled as _, Task, Window,
12    prelude::FluentBuilder as _, px,
13};
14
15use crate::{
16    ElementExt,
17    async_util::{Receiver, Sender, unbounded},
18    input::{self, SelectAll},
19    scroll::AutoScroll,
20    text::{
21        CodeBlockActionsFn, LinkClickHandlerFn, MarkdownExtensions, TableActionsFn, TextViewStyle,
22        document::ParsedDocument,
23        format,
24        node::{self, NodeContext},
25        selection_adapter::TextViewSelectionAdapter,
26    },
27    v_flex,
28};
29
30const CONTEXT: &'static str = "TextView";
31// Keep coalescing bounded so sustained streams still render intermediate updates.
32const MAX_COALESCED_UPDATES_PER_PARSE: usize = 64;
33// Preserve exact first-layout height for small documents while bounding the
34// amount of source parsed synchronously on the UI thread.
35const MAX_SYNC_FULL_REPLACE_BYTES: usize = 4 * 1024;
36
37pub(crate) fn init(cx: &mut App) {
38    cx.bind_keys(vec![
39        #[cfg(target_os = "macos")]
40        KeyBinding::new("cmd-c", input::Copy, Some(CONTEXT)),
41        #[cfg(not(target_os = "macos"))]
42        KeyBinding::new("ctrl-c", input::Copy, Some(CONTEXT)),
43        #[cfg(target_os = "macos")]
44        KeyBinding::new("cmd-a", input::SelectAll, Some(CONTEXT)),
45        #[cfg(not(target_os = "macos"))]
46        KeyBinding::new("ctrl-a", input::SelectAll, Some(CONTEXT)),
47    ]);
48}
49
50/// The content format of the text view.
51#[derive(Clone, Copy, PartialEq, Eq)]
52pub(super) enum TextViewFormat {
53    /// Markdown view
54    Markdown,
55    /// HTML view
56    Html,
57}
58
59/// The format of the text returned by
60/// [`TextViewState::selected_text`], which is also what copy writes to the
61/// clipboard.
62#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
63pub enum SelectionFormat {
64    /// The rendered text, without any markup.
65    #[default]
66    Plain,
67    /// The source of the selection.
68    ///
69    /// Select-all returns the original source verbatim, a partial selection is
70    /// reconstructed as Markdown from the parsed nodes (e.g. selecting inside
71    /// a `**bold**` run yields `**bold**`).
72    Source,
73}
74
75/// One text element's laid-out vertical extent, reported by `Inline` during
76/// prepaint so `TextView` can snap its `max_lines` clip to a whole-line
77/// boundary.
78#[derive(Clone, Copy)]
79pub(super) struct LineSpan {
80    pub(super) top: Pixels,
81    pub(super) bottom: Pixels,
82    pub(super) line_height: Pixels,
83}
84
85/// The state of a TextView.
86pub struct TextViewState {
87    pub(super) focus_handle: FocusHandle,
88    pub(super) list_state: ListState,
89
90    /// The bounds of the text view
91    bounds: Bounds<Pixels>,
92
93    pub(super) selectable: bool,
94    pub(super) selection_format: SelectionFormat,
95    pub(super) scrollable: bool,
96    pub(super) max_lines: Option<usize>,
97    /// Line spans reported by `Inline` during prepaint (collected only while
98    /// [`Self::max_lines`] is set); cleared by `TextView` at each frame start.
99    pub(super) line_spans: Arc<Mutex<Vec<LineSpan>>>,
100    /// Whether the last painted frame clipped content due to `max_lines`.
101    pub(super) clamped: bool,
102    pub(super) text_view_style: TextViewStyle,
103    pub(super) code_block_actions: Option<std::sync::Arc<CodeBlockActionsFn>>,
104    pub(super) table_actions: Option<std::sync::Arc<TableActionsFn>>,
105    pub(super) link_click_handler: Option<std::sync::Arc<LinkClickHandlerFn>>,
106    pub(super) markdown_extensions: Arc<MarkdownExtensions>,
107
108    pub(super) is_selecting: bool,
109    multi_click_selection: Option<TextViewMultiClickSelection>,
110    selected_text_override: Option<String>,
111    select_all: bool,
112    pub(super) auto_scroll: AutoScroll,
113    pub(super) selection_adapter: TextViewSelectionAdapter,
114
115    pub(super) parsed_content: ParsedContent,
116    /// Content format (markdown / html), used for bounded synchronous parsing
117    /// of small full-replace updates.
118    format: TextViewFormat,
119    text: String,
120    revision: usize,
121    pub(super) selection_revision: usize,
122    compatible_layout_update: bool,
123    parsed_error: Option<SharedString>,
124    tx: Sender<UpdateOptions>,
125    _parse_task: Task<()>,
126    _receive_task: Task<()>,
127}
128
129impl TextViewState {
130    /// Create a Markdown TextViewState.
131    pub fn markdown(text: &str, cx: &mut Context<Self>) -> Self {
132        Self::new(TextViewFormat::Markdown, text, cx)
133    }
134
135    /// Create a HTML TextViewState.
136    pub fn html(text: &str, cx: &mut Context<Self>) -> Self {
137        Self::new(TextViewFormat::Html, text, cx)
138    }
139
140    /// Create a new TextViewState.
141    fn new(format: TextViewFormat, text: &str, cx: &mut Context<Self>) -> Self {
142        let focus_handle = cx.focus_handle();
143        let selection_adapter = TextViewSelectionAdapter::new(cx.entity().downgrade(), cx);
144
145        let (tx, rx) = unbounded::<UpdateOptions>();
146        let (tx_result, rx_result) = unbounded::<ParsedUpdate>();
147        let _receive_task = cx.spawn({
148            async move |weak_self, cx| {
149                while let Ok(parsed_update) = rx_result.recv().await {
150                    _ = weak_self.update(cx, |state, cx| {
151                        if parsed_update.revision != state.revision {
152                            return;
153                        }
154                        if parsed_update.baseline_ack {
155                            debug_assert!(parsed_update.full_parse);
156                            return;
157                        }
158
159                        match parsed_update.result {
160                            Ok(content) => {
161                                state.parsed_content = content;
162                                state.parsed_error = None;
163                                state.compatible_layout_update = parsed_update.selection_compatible;
164                            }
165                            Err(err) => {
166                                state.parsed_error = Some(err);
167                            }
168                        }
169                        // Don't interrupt an active drag-selection; the stored
170                        // positions remain valid for append-only updates and will
171                        // self-correct on the next mouse-move event.
172                        if !parsed_update.selection_compatible && !state.is_selecting {
173                            state.reset_selection_and_adapter(cx);
174                        }
175                        cx.notify();
176                    });
177                }
178            }
179        });
180
181        let _parse_task = cx.background_spawn(UpdateFuture::new(format, rx, tx_result));
182
183        let mut this = Self {
184            focus_handle,
185            bounds: Bounds::default(),
186            multi_click_selection: None,
187            selected_text_override: None,
188            select_all: false,
189            selectable: false,
190            selection_format: SelectionFormat::default(),
191            scrollable: false,
192            max_lines: None,
193            line_spans: Arc::default(),
194            clamped: false,
195            // Measure all blocks (not just visible ones) so the scrollbar
196            // thumb size stays stable. Without this, off-screen blocks count
197            // as zero height until scrolled into view, which makes the
198            // scrollbar jitter as more blocks get measured during scrolling.
199            list_state: ListState::new(0, gpui::ListAlignment::Top, px(1000.)).measure_all(),
200            text_view_style: TextViewStyle::default(),
201            code_block_actions: None,
202            table_actions: None,
203            link_click_handler: None,
204            markdown_extensions: Arc::default(),
205            is_selecting: false,
206            auto_scroll: AutoScroll::default(),
207            selection_adapter,
208            parsed_content: Default::default(),
209            format,
210            parsed_error: None,
211            text: text.to_string(),
212            revision: 0,
213            selection_revision: 0,
214            compatible_layout_update: false,
215            tx,
216            _parse_task,
217            _receive_task,
218        };
219        this.increment_update(&text, false, cx);
220        this
221    }
222
223    /// Get the text content.
224    pub(crate) fn source(&self) -> SharedString {
225        self.parsed_content.document.source.clone()
226    }
227
228    /// Set whether the text is selectable, default false.
229    pub fn selectable(mut self, selectable: bool) -> Self {
230        self.selectable = selectable;
231        self
232    }
233
234    /// Set whether the text is selectable, default false.
235    pub fn set_selectable(&mut self, selectable: bool, cx: &mut Context<Self>) {
236        self.selectable = selectable;
237        cx.notify();
238    }
239
240    /// Set the [`SelectionFormat`], default is [`SelectionFormat::Plain`].
241    pub fn selection_format(mut self, selection_format: SelectionFormat) -> Self {
242        self.selection_format = selection_format;
243        self
244    }
245
246    /// Set the [`SelectionFormat`], default is [`SelectionFormat::Plain`].
247    pub fn set_selection_format(
248        &mut self,
249        selection_format: SelectionFormat,
250        cx: &mut Context<Self>,
251    ) {
252        self.selection_format = selection_format;
253        cx.notify();
254    }
255
256    /// Set whether the text is selectable, default false.
257    pub fn scrollable(mut self, scrollable: bool) -> Self {
258        self.scrollable = scrollable;
259        self
260    }
261
262    /// Set whether the text is selectable, default false.
263    pub fn set_scrollable(&mut self, scrollable: bool, cx: &mut Context<Self>) {
264        if !scrollable {
265            self.reset_selection_and_adapter(cx);
266        }
267        self.scrollable = scrollable;
268        cx.notify();
269    }
270
271    /// Whether the last painted frame clipped content because of
272    /// [`TextView::max_lines`](crate::text::TextView::max_lines).
273    pub fn is_clamped(&self) -> bool {
274        self.clamped
275    }
276
277    /// Set the text content.
278    pub fn set_text(&mut self, text: &str, cx: &mut Context<Self>) {
279        if self.text.as_str() == text {
280            return;
281        }
282
283        self.text.clear();
284        self.text.push_str(text);
285        self.parsed_error = None;
286        self.increment_update(text, false, cx);
287    }
288
289    /// Append partial text content to the existing text.
290    pub fn push_str(&mut self, new_text: &str, cx: &mut Context<Self>) {
291        if new_text.is_empty() {
292            return;
293        }
294        self.text.push_str(new_text);
295        self.increment_update(new_text, true, cx);
296    }
297
298    pub(crate) fn set_markdown_extensions(
299        &mut self,
300        markdown_extensions: Arc<MarkdownExtensions>,
301        cx: &mut Context<Self>,
302    ) {
303        if self.markdown_extensions.revision() == markdown_extensions.revision() {
304            return;
305        }
306
307        self.markdown_extensions = markdown_extensions;
308        if self.format == TextViewFormat::Markdown {
309            let text = self.text.clone();
310            self.increment_update(&text, false, cx);
311        }
312    }
313
314    /// Return the selected text, in the view's [`SelectionFormat`].
315    pub fn selected_text(&self) -> String {
316        self.selected_text_in(None)
317    }
318
319    /// The format to copy in, which is [`SelectionFormat::Plain`] whenever the
320    /// requested one cannot be produced.
321    ///
322    /// Only a Markdown view can return source. Reconstructing HTML would mean
323    /// spelling every attribute back out — a mark's color, an image's
324    /// dimensions, a cell's alignment — with a new way to lose one at each
325    /// step, and html5ever records no source offsets to fall back on (it
326    /// reports only line numbers), so there is no original text to copy from
327    /// either.
328    fn effective_format(&self) -> SelectionFormat {
329        match self.format {
330            TextViewFormat::Markdown => self.selection_format,
331            TextViewFormat::Html => SelectionFormat::Plain,
332        }
333    }
334
335    /// Return the selected text, with `blocks` bounding which top-level blocks
336    /// the selection covers.
337    ///
338    /// The range comes from the selection endpoints, which know their block
339    /// even after it scrolls out of view; see
340    /// [`ParsedDocument::selected_text`](crate::text::document::ParsedDocument).
341    pub(super) fn selected_text_in(&self, blocks: Option<RangeInclusive<usize>>) -> String {
342        let format = self.effective_format();
343
344        if self.select_all {
345            if format == SelectionFormat::Source {
346                return self.source().to_string();
347            }
348
349            return self.parsed_content.document.text();
350        }
351
352        // A multi-click stores the plain text it selected, which is a shortcut
353        // past the block walk. Source mode cannot take it: the word it stored
354        // has lost its markup. The click also set the inline selection it came
355        // from, so the walk reconstructs the same range with the markup intact.
356        if format != SelectionFormat::Source
357            && let Some(text) = &self.selected_text_override
358        {
359            return text.clone();
360        }
361
362        self.parsed_content.document.selected_text(format, blocks)
363    }
364
365    fn increment_update(&mut self, text: &str, append: bool, cx: &mut Context<Self>) {
366        self.revision += 1;
367        if !append {
368            self.selection_revision = self.selection_revision.wrapping_add(1);
369        }
370        let parse_synchronously = !append && text.len() <= MAX_SYNC_FULL_REPLACE_BYTES;
371        let update_options = UpdateOptions {
372            revision: self.revision,
373            append,
374            mode: if append {
375                ParseMode::Compatible
376            } else if parse_synchronously {
377                ParseMode::BaselineAck
378            } else {
379                ParseMode::Replace
380            },
381            pending_text: text.to_string(),
382            markdown_extensions: self.markdown_extensions.clone(),
383        };
384
385        // Keep small full replacements synchronous so their first layout has
386        // the exact content height. Larger replacements use the existing
387        // background parser, bounding synchronous parser input on the UI thread.
388        if parse_synchronously {
389            match parse_content(self.format, ParsedContent::default(), &update_options) {
390                Ok(content) => {
391                    self.parsed_content = content;
392                    self.parsed_error = None;
393                    if !self.is_selecting {
394                        self.reset_selection_and_adapter(cx);
395                    }
396                }
397                Err(err) => {
398                    self.parsed_error = Some(err);
399                }
400            }
401            // Keep the background parser's accumulated document in sync so a
402            // later append extends this baseline instead of parsing the delta
403            // as a standalone document.
404            _ = self.tx.try_send(update_options);
405            cx.notify();
406            return;
407        }
408
409        _ = self.tx.try_send(update_options);
410    }
411
412    /// Save bounds and unselect if bounds changed.
413    pub(super) fn update_bounds(&mut self, bounds: Bounds<Pixels>, _cx: &mut App) {
414        self.bounds = bounds;
415    }
416
417    /// The index of the top-level block at `content_y`, in this view's content
418    /// coordinates (the same space the base selection endpoint stores its point in).
419    ///
420    /// Only laid-out blocks can be located, which is enough for a selection
421    /// endpoint: the user can only put one where they can see it. Returns
422    /// `None` for a view that is not virtualized, where every block paints and
423    /// the range is not needed.
424    pub(super) fn block_ix_at(&self, content_y: Pixels) -> Option<usize> {
425        if !self.scrollable {
426            return None;
427        }
428
429        let origin = self.bounds.origin.y + self.scroll_offset().y;
430        let count = self.list_state.item_count();
431        let mut ix = self.list_state.logical_scroll_top().item_ix;
432        while ix < count {
433            let bounds = self.list_state.bounds_for_item(ix)?;
434            if content_y < bounds.bottom() - origin {
435                return Some(ix);
436            }
437            ix += 1;
438        }
439
440        count.checked_sub(1)
441    }
442
443    pub(super) fn bounds(&self) -> Bounds<Pixels> {
444        self.bounds
445    }
446
447    /// Whether this view has a view-local selection (select-all, multi-click, or override),
448    /// independent of the window-level selection.
449    pub(super) fn has_view_selection(&self) -> bool {
450        self.select_all
451            || self.multi_click_selection.is_some()
452            || self.selected_text_override.is_some()
453    }
454
455    pub(super) fn stop_auto_scroll(&mut self) {
456        self.auto_scroll.stop();
457    }
458
459    pub(super) fn reset_selection(&mut self) {
460        self.multi_click_selection = None;
461        self.selected_text_override = None;
462        self.select_all = false;
463        self.is_selecting = false;
464        self.auto_scroll.stop();
465        // Clear the inline selection state synchronously, so offscreen
466        // (virtualized) views that won't repaint don't leak stale selection
467        // text into a new cross-view copy.
468        self.parsed_content.document.clear_selection();
469    }
470
471    fn reset_selection_and_adapter(&mut self, cx: &mut App) {
472        self.reset_selection();
473        self.selection_adapter.set_local_selection(false, cx);
474    }
475
476    /// Clear the current text selection.
477    pub fn clear_selection(&mut self, cx: &mut Context<Self>) {
478        self.reset_selection_and_adapter(cx);
479        cx.notify();
480    }
481
482    pub(super) fn scroll_offset(&self) -> Point<Pixels> {
483        if self.scrollable {
484            self.list_state.scroll_px_offset_for_scrollbar()
485        } else {
486            Point::default()
487        }
488    }
489
490    /// Select all rendered text in this view.
491    pub fn select_all(&mut self, cx: &mut Context<Self>) {
492        self.multi_click_selection = None;
493        self.selected_text_override = None;
494        self.select_all = true;
495        self.is_selecting = false;
496        self.auto_scroll.stop();
497        self.selection_adapter.set_local_selection(true, cx);
498        cx.notify();
499    }
500
501    pub(crate) fn set_multi_click_selection(
502        &mut self,
503        pos: Point<Pixels>,
504        kind: TextViewMultiClickKind,
505        selected_text: String,
506        cx: &mut App,
507    ) {
508        let scroll_offset = self.scroll_offset();
509        let pos = pos - self.bounds.origin - scroll_offset;
510        self.multi_click_selection = Some(TextViewMultiClickSelection { pos, kind });
511        self.selected_text_override = Some(selected_text);
512        self.select_all = false;
513        self.is_selecting = false;
514        self.auto_scroll.stop();
515        self.selection_adapter.set_local_selection(true, cx);
516    }
517
518    pub(super) fn set_auto_scroll(&mut self, delta: Option<Pixels>, cx: &mut Context<Self>) {
519        self.auto_scroll.set(delta, cx, |delta, state, cx| {
520            state.list_state.scroll_by(delta);
521            cx.notify();
522        });
523    }
524
525    /// Return the window selection (anchor, cursor) in window coordinates if
526    /// this view participates in it.
527    ///
528    /// Single-view fast path: when both endpoints are anchored inside one
529    /// TextView, only that view participates (identical to the previous
530    /// per-view behavior).
531    pub(crate) fn selection_points(&self, cx: &App) -> Option<(Point<Pixels>, Point<Pixels>)> {
532        if !self.selectable {
533            return None;
534        }
535        self.selection_adapter.selection_points(cx)
536    }
537
538    pub(crate) fn has_selection(&self, cx: &App) -> bool {
539        self.has_view_selection() || self.selection_points(cx).is_some()
540    }
541
542    pub(super) fn on_action_select_all(
543        &mut self,
544        _: &SelectAll,
545        _: &mut Window,
546        cx: &mut Context<Self>,
547    ) {
548        if !self.selectable {
549            cx.propagate();
550            return;
551        }
552
553        self.select_all(cx);
554    }
555
556    pub(crate) fn is_selectable(&self) -> bool {
557        self.selectable
558    }
559
560    pub(crate) fn is_all_selected(&self) -> bool {
561        self.select_all
562    }
563
564    pub(crate) fn multi_click_selection(&self) -> Option<TextViewMultiClickSelection> {
565        let scroll_offset = self.scroll_offset();
566        self.multi_click_selection.map(|selection| {
567            let pos = selection.pos + scroll_offset + self.bounds.origin;
568            TextViewMultiClickSelection { pos, ..selection }
569        })
570    }
571}
572
573#[derive(Clone, Copy, Debug, PartialEq)]
574pub(crate) struct TextViewMultiClickSelection {
575    pub(crate) pos: Point<Pixels>,
576    pub(crate) kind: TextViewMultiClickKind,
577}
578
579#[derive(Clone, Copy, Debug, PartialEq, Eq)]
580pub(crate) enum TextViewMultiClickKind {
581    Word,
582    Paragraph,
583}
584
585impl Render for TextViewState {
586    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
587        let state = cx.entity();
588        let document = self.parsed_content.document.clone();
589        let mut node_cx = self.parsed_content.node_cx.clone();
590
591        node_cx.code_block_actions = self.code_block_actions.clone();
592        node_cx.table_actions = self.table_actions.clone();
593        node_cx.link_click_handler = self.link_click_handler.clone();
594        node_cx.markdown_extensions = self.markdown_extensions.clone();
595        node_cx.style = self.text_view_style.clone();
596
597        v_flex()
598            .w_full()
599            // Clamped content must keep its natural height: stretching it to
600            // the capped box would hide the overflow the clamp has to measure.
601            .when(self.max_lines.is_none(), |this| this.h_full())
602            .map(|this| match &mut self.parsed_error {
603                None => this.child(document.render_root(
604                    if self.scrollable {
605                        Some(self.list_state.clone())
606                    } else {
607                        None
608                    },
609                    &node_cx,
610                    window,
611                    cx,
612                )),
613                Some(err) => this.child(
614                    v_flex()
615                        .gap_1()
616                        .child("Failed to parse content")
617                        .child(err.to_string()),
618                ),
619            })
620            .on_prepaint(move |bounds, window, cx| {
621                let (
622                    size_changed,
623                    selection_involves_view,
624                    has_selection_snapshot,
625                    is_selecting,
626                    compatible_layout_update,
627                ) = {
628                    let state = state.read(cx);
629                    (
630                        state.bounds().size != bounds.size,
631                        state.selection_adapter.is_part_of_window_selection(cx),
632                        state.selection_adapter.has_selection_snapshot(cx),
633                        state.is_selecting,
634                        state.compatible_layout_update,
635                    )
636                };
637                let mut revision_changed = false;
638                state.update(cx, |state, cx| {
639                    revision_changed = state
640                        .selection_adapter
641                        .update_layout_revision(state.selection_revision, state.is_selecting);
642                    state.update_bounds(bounds, cx);
643                    state.compatible_layout_update = false;
644                });
645                if !is_selecting
646                    && ((size_changed && selection_involves_view && !compatible_layout_update)
647                        || (revision_changed && has_selection_snapshot))
648                {
649                    gpui_base::TextSelection::clear(window, cx);
650                }
651            })
652    }
653}
654
655#[derive(Clone, PartialEq, Default)]
656pub(crate) struct ParsedContent {
657    pub(crate) document: ParsedDocument,
658    pub(crate) node_cx: node::NodeContext,
659}
660
661struct UpdateFuture {
662    format: TextViewFormat,
663    content: ParsedContent,
664    rx: Pin<Box<Receiver<UpdateOptions>>>,
665    tx_result: Sender<ParsedUpdate>,
666}
667
668impl UpdateFuture {
669    fn new(
670        format: TextViewFormat,
671        rx: Receiver<UpdateOptions>,
672        tx_result: Sender<ParsedUpdate>,
673    ) -> Self {
674        Self {
675            format,
676            content: Default::default(),
677            rx: Box::pin(rx),
678            tx_result,
679        }
680    }
681}
682
683impl Future for UpdateFuture {
684    type Output = ();
685
686    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
687        loop {
688            match self.rx.as_mut().poll_next(cx) {
689                Poll::Ready(Some(mut options)) => {
690                    let hit_coalesce_budget =
691                        merge_pending_options(&mut options, self.rx.as_ref().get_ref());
692
693                    let res = parse_content(self.format, self.content.clone(), &options);
694                    if let Ok(content) = &res {
695                        self.content = content.clone();
696                    }
697                    _ = self.tx_result.try_send(ParsedUpdate {
698                        revision: options.revision,
699                        full_parse: !options.append,
700                        selection_compatible: options.mode == ParseMode::Compatible,
701                        baseline_ack: options.mode == ParseMode::BaselineAck,
702                        result: res,
703                    });
704                    if hit_coalesce_budget {
705                        cx.waker().wake_by_ref();
706                        return Poll::Pending;
707                    }
708                    continue;
709                }
710                Poll::Ready(None) => return Poll::Ready(()),
711                Poll::Pending => return Poll::Pending,
712            }
713        }
714    }
715}
716
717#[derive(Clone)]
718struct UpdateOptions {
719    revision: usize,
720    pending_text: String,
721    append: bool,
722    mode: ParseMode,
723    markdown_extensions: Arc<MarkdownExtensions>,
724}
725
726impl UpdateOptions {
727    fn merge(&mut self, next: UpdateOptions) {
728        if next.append {
729            self.pending_text.push_str(&next.pending_text);
730            self.revision = next.revision;
731            if self.mode != ParseMode::Replace {
732                self.mode = ParseMode::Compatible;
733            }
734        } else {
735            *self = next;
736        }
737    }
738}
739
740struct ParsedUpdate {
741    revision: usize,
742    full_parse: bool,
743    selection_compatible: bool,
744    baseline_ack: bool,
745    result: Result<ParsedContent, SharedString>,
746}
747
748#[derive(Clone, Copy, Debug, PartialEq, Eq)]
749enum ParseMode {
750    BaselineAck,
751    Replace,
752    Compatible,
753}
754
755fn merge_pending_options(options: &mut UpdateOptions, rx: &Receiver<UpdateOptions>) -> bool {
756    let mut update_count = 1;
757
758    while update_count < MAX_COALESCED_UPDATES_PER_PARSE {
759        match rx.try_recv() {
760            Ok(next_options) => {
761                options.merge(next_options);
762                update_count += 1;
763            }
764            Err(_) => return false,
765        }
766    }
767
768    true
769}
770
771fn parse_content(
772    format: TextViewFormat,
773    mut content: ParsedContent,
774    options: &UpdateOptions,
775) -> Result<ParsedContent, SharedString> {
776    let mut node_cx = NodeContext {
777        markdown_extensions: options.markdown_extensions.clone(),
778        ..NodeContext::default()
779    };
780
781    // Re-parse the last block together with the appended text, so a block the
782    // new text continues (an unclosed list, a fenced code block) is not split
783    // in two. A block without a span cannot be located in `source` — the HTML
784    // parser never records spans — so it is left in place and only the
785    // appended text is parsed, positioned at the end of the current source.
786    let last_span = options
787        .append
788        .then(|| {
789            content
790                .document
791                .blocks
792                .last()
793                .and_then(|block| block.span())
794        })
795        .flatten();
796
797    let mut source = String::new();
798    if let Some(span) = last_span {
799        Arc::make_mut(&mut content.document.blocks).pop();
800        node_cx.offset = span.start;
801        source.push_str(&content.document.source[span.start..]);
802        source.push_str(&options.pending_text);
803    } else {
804        if options.append {
805            node_cx.offset = content.document.source.len();
806        }
807        source.push_str(&options.pending_text);
808    }
809
810    let new_document = match format {
811        TextViewFormat::Markdown => format::markdown::parse(&source, &mut node_cx),
812        TextViewFormat::Html => format::html::parse(&source, &mut node_cx),
813    }?;
814
815    if options.append {
816        content.document.source =
817            format!("{}{}", content.document.source, options.pending_text).into();
818        Arc::make_mut(&mut content.document.blocks)
819            .extend(Arc::unwrap_or_clone(new_document.blocks));
820    } else {
821        content.document = new_document;
822    }
823
824    Ok(content)
825}
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830    use crate::text::MarkdownNode;
831    use gpui::TestAppContext;
832
833    #[gpui::test]
834    fn small_full_replace_parses_before_background_executor_runs(cx: &mut TestAppContext) {
835        cx.update(crate::init);
836        let markdown = "# ready";
837        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
838
839        state.read_with(cx, |state, _| {
840            assert_eq!(state.source().as_str(), markdown);
841            assert_eq!(state.parsed_content.document.blocks.len(), 1);
842        });
843    }
844
845    #[gpui::test]
846    fn large_markdown_and_html_full_replacements_wait_for_background_executor(
847        cx: &mut TestAppContext,
848    ) {
849        cx.update(crate::init);
850        let markdown = "# x\n\n".repeat(MAX_SYNC_FULL_REPLACE_BYTES / 5 + 1);
851        let html = format!("<p>{}</p>", "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1));
852        assert!(markdown.len() > MAX_SYNC_FULL_REPLACE_BYTES);
853        assert!(html.len() > MAX_SYNC_FULL_REPLACE_BYTES);
854
855        let (markdown_state, html_state) = cx.update(|cx| {
856            (
857                cx.new(|cx| TextViewState::markdown(&markdown, cx)),
858                cx.new(|cx| TextViewState::html(&html, cx)),
859            )
860        });
861
862        markdown_state.read_with(cx, |state, _| {
863            assert_eq!(state.text.as_str(), markdown.as_str());
864            assert!(state.source().as_str().is_empty());
865            assert!(state.parsed_content.document.blocks.is_empty());
866        });
867        html_state.read_with(cx, |state, _| {
868            assert_eq!(state.text.as_str(), html.as_str());
869            assert!(state.source().as_str().is_empty());
870            assert!(state.parsed_content.document.blocks.is_empty());
871        });
872
873        cx.run_until_parked();
874
875        markdown_state.read_with(cx, |state, _| {
876            assert_eq!(state.source().as_str(), markdown.as_str());
877            assert!(!state.parsed_content.document.blocks.is_empty());
878        });
879        html_state.read_with(cx, |state, _| {
880            assert_eq!(state.source().as_str(), html.as_str());
881            assert!(!state.parsed_content.document.blocks.is_empty());
882        });
883    }
884
885    #[gpui::test]
886    fn async_full_replace_then_push_str_preserves_complete_source(cx: &mut TestAppContext) {
887        cx.update(crate::init);
888        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
889        cx.run_until_parked();
890
891        let replacement = "x".repeat(MAX_SYNC_FULL_REPLACE_BYTES + 1);
892        let expected = format!("{replacement} tail");
893        state.update(cx, |state, cx| {
894            state.set_text(&replacement, cx);
895            state.push_str(" tail", cx);
896        });
897        cx.run_until_parked();
898
899        state.read_with(cx, |state, _| {
900            assert_eq!(state.text.as_str(), expected.as_str());
901            assert_eq!(state.source().as_str(), expected.as_str());
902        });
903    }
904
905    #[gpui::test]
906    fn html_push_str_keeps_earlier_blocks(cx: &mut TestAppContext) {
907        cx.update(crate::init);
908        let state = cx.update(|cx| cx.new(|cx| TextViewState::html("<p>first</p>", cx)));
909        cx.run_until_parked();
910
911        state.update(cx, |state, cx| {
912            state.push_str("<p>second</p>", cx);
913        });
914        cx.run_until_parked();
915
916        state.read_with(cx, |state, _| {
917            assert_eq!(state.source().as_str(), "<p>first</p><p>second</p>");
918            let text = state
919                .parsed_content
920                .document
921                .blocks
922                .iter()
923                .map(|block| block.text())
924                .collect::<String>();
925            assert!(text.contains("first"), "lost the first block: {text:?}");
926            assert!(text.contains("second"), "lost the appended block: {text:?}");
927        });
928    }
929
930    #[gpui::test]
931    fn set_text_then_push_str_appends_to_replaced_content(cx: &mut TestAppContext) {
932        cx.update(crate::init);
933        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
934        cx.run_until_parked();
935
936        state.update(cx, |state, cx| {
937            state.set_text("", cx);
938            state.push_str("new", cx);
939            state.push_str(" text", cx);
940        });
941        cx.run_until_parked();
942
943        state.read_with(cx, |state, _| {
944            assert_eq!(state.text.as_str(), "new text");
945            assert_eq!(state.source().as_str(), "new text");
946        });
947
948        state.update(cx, |state, cx| {
949            state.set_text("", cx);
950        });
951        cx.run_until_parked();
952
953        state.read_with(cx, |state, _| {
954            assert_eq!(state.text.as_str(), "");
955            assert_eq!(state.source().as_str(), "");
956        });
957    }
958
959    #[gpui::test]
960    fn full_parse_coalesced_with_append_preserves_new_select_all(cx: &mut TestAppContext) {
961        cx.update(crate::init);
962        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("old", cx)));
963        cx.run_until_parked();
964
965        state.update(cx, |state, cx| {
966            state.set_text("new", cx);
967            state.push_str(" text", cx);
968            state.select_all(cx);
969        });
970        cx.run_until_parked();
971
972        state.read_with(cx, |state, _| {
973            assert!(state.select_all);
974            assert_eq!(state.selected_text().trim(), "new text");
975        });
976    }
977
978    #[test]
979    fn update_options_merge_keeps_latest_full_text() {
980        let mut options = UpdateOptions {
981            revision: 1,
982            pending_text: "old".to_string(),
983            append: true,
984            mode: ParseMode::Compatible,
985            markdown_extensions: Arc::default(),
986        };
987
988        options.merge(UpdateOptions {
989            revision: 2,
990            pending_text: "new".to_string(),
991            append: false,
992            mode: ParseMode::BaselineAck,
993            markdown_extensions: Arc::default(),
994        });
995        options.merge(UpdateOptions {
996            revision: 3,
997            pending_text: " text".to_string(),
998            append: true,
999            mode: ParseMode::Compatible,
1000            markdown_extensions: Arc::default(),
1001        });
1002
1003        assert_eq!(options.revision, 3);
1004        assert_eq!(options.pending_text, "new text");
1005        assert!(!options.append);
1006    }
1007
1008    #[test]
1009    fn append_merged_into_async_replace_remains_a_replacement() {
1010        let mut options = UpdateOptions {
1011            revision: 1,
1012            pending_text: "new".to_string(),
1013            append: false,
1014            mode: ParseMode::Replace,
1015            markdown_extensions: Arc::default(),
1016        };
1017
1018        options.merge(UpdateOptions {
1019            revision: 2,
1020            pending_text: " text".to_string(),
1021            append: true,
1022            mode: ParseMode::Compatible,
1023            markdown_extensions: Arc::default(),
1024        });
1025
1026        assert_eq!(options.revision, 2);
1027        assert_eq!(options.pending_text, "new text");
1028        assert!(!options.append);
1029        assert_eq!(options.mode, ParseMode::Replace);
1030    }
1031
1032    #[test]
1033    fn update_future_yields_before_coalescing_all_queued_updates() {
1034        let (tx, rx) = unbounded::<UpdateOptions>();
1035        let (tx_result, rx_result) = unbounded::<ParsedUpdate>();
1036        let total_updates = 128;
1037
1038        for revision in 1..=total_updates {
1039            tx.try_send(UpdateOptions {
1040                revision,
1041                pending_text: format!("{revision}\n"),
1042                append: revision != 1,
1043                mode: if revision == 1 {
1044                    ParseMode::BaselineAck
1045                } else {
1046                    ParseMode::Compatible
1047                },
1048                markdown_extensions: Arc::default(),
1049            })
1050            .unwrap();
1051        }
1052
1053        let mut future = Box::pin(UpdateFuture::new(TextViewFormat::Markdown, rx, tx_result));
1054        let waker = futures::task::noop_waker();
1055        let mut task_cx = std::task::Context::from_waker(&waker);
1056
1057        assert!(matches!(
1058            std::future::Future::poll(future.as_mut(), &mut task_cx),
1059            Poll::Pending
1060        ));
1061        let parsed_update = rx_result.try_recv().expect("parse result");
1062
1063        assert!(
1064            parsed_update.revision < total_updates,
1065            "single poll coalesced every queued update through revision {}",
1066            parsed_update.revision
1067        );
1068
1069        assert!(matches!(
1070            std::future::Future::poll(future.as_mut(), &mut task_cx),
1071            Poll::Pending
1072        ));
1073        let parsed_update = rx_result.try_recv().expect("next parse result");
1074        assert_eq!(parsed_update.revision, total_updates);
1075    }
1076
1077    #[gpui::test]
1078    fn select_all_returns_rendered_text(cx: &mut TestAppContext) {
1079        cx.update(crate::init);
1080        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("**quick** value", cx)));
1081        cx.run_until_parked();
1082
1083        state.update(cx, |state, cx| {
1084            state.select_all(cx);
1085        });
1086
1087        state.read_with(cx, |state, _| {
1088            assert!(state.has_view_selection());
1089            assert_eq!(state.selected_text().trim(), "quick value");
1090        });
1091
1092        state.update(cx, |state, cx| {
1093            state.clear_selection(cx);
1094        });
1095
1096        state.read_with(cx, |state, _| {
1097            assert!(!state.has_view_selection());
1098            assert_eq!(state.selected_text(), "");
1099        });
1100    }
1101
1102    #[gpui::test]
1103    fn select_all_in_source_format_returns_source(cx: &mut TestAppContext) {
1104        cx.update(crate::init);
1105        let markdown = "**quick** value";
1106        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown(markdown, cx)));
1107        cx.run_until_parked();
1108
1109        state.update(cx, |state, cx| state.select_all(cx));
1110
1111        // The default (plain) mode strips the markup.
1112        state.read_with(cx, |state, _| {
1113            assert_eq!(state.selected_text().trim(), "quick value");
1114        });
1115
1116        state.update(cx, |state, cx| {
1117            state.set_selection_format(SelectionFormat::Source, cx)
1118        });
1119
1120        // Source mode yields the whole source verbatim.
1121        state.read_with(cx, |state, _| {
1122            assert_eq!(state.selected_text().trim(), markdown);
1123        });
1124    }
1125
1126    #[gpui::test]
1127    fn set_markdown_extensions_reparses_existing_text(cx: &mut TestAppContext) {
1128        cx.update(crate::init);
1129        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("$TSLA.US", cx)));
1130        cx.run_until_parked();
1131
1132        let extensions = MarkdownExtensions::default().block_parser(|node, cx| {
1133            let markdown::mdast::Node::Paragraph(paragraph) = node else {
1134                return None;
1135            };
1136            let [markdown::mdast::Node::Text(text)] = paragraph.children.as_slice() else {
1137                return None;
1138            };
1139            let symbol = text.value.strip_prefix('$')?.to_string();
1140            let node_text = format!("${symbol}");
1141
1142            Some(
1143                MarkdownNode::new("ticker", symbol)
1144                    .text(node_text)
1145                    .markdown(cx.node_source(node).unwrap_or_default()),
1146            )
1147        });
1148
1149        state.update(cx, |state, cx| {
1150            state.set_markdown_extensions(Arc::new(extensions), cx);
1151        });
1152        cx.run_until_parked();
1153
1154        state.read_with(cx, |state, _| {
1155            let node::BlockNode::Custom(node) = &state.parsed_content.document.blocks[0] else {
1156                panic!("expected custom markdown node");
1157            };
1158            assert_eq!(node.name(), "ticker");
1159            assert_eq!(node.data::<String>().map(String::as_str), Some("TSLA.US"));
1160        });
1161    }
1162}