Skip to main content

ui/
input.rs

1//! [`TextField`] — a single-line text field with IME, selection and clipboard.
2//!
3//! Unlike the rest of this crate, a text field cannot be a plain function
4//! returning a `Div`: editing needs state (content, selection, IME marked
5//! range), a focus handle, and gpui's [`EntityInputHandler`]. So it is an
6//! entity the caller holds — SwiftUI's `TextField` bound to `@State`, not a
7//! stateless view.
8//!
9//! Ported from gpui's `examples/input.rs` (Apache-2.0), restyled onto
10//! [`Theme`] tokens, with the key bindings **scoped to the field's key
11//! context** rather than installed globally: a component library must not make
12//! `cmd-a` mean "select all text" for the whole application.
13//!
14//! ```ignore
15//! ui::input::init(cx);                      // once, at startup
16//! let field = cx.new(|cx| TextField::new(cx).with_placeholder("Search…"));
17//! // …then render it: .child(field.clone())
18//! ```
19
20use std::{borrow::Cow, ops::Range, time::Duration};
21
22use gpui::{
23    App, Bounds, ClipboardItem, Context, CursorStyle, DispatchPhase, ElementId,
24    ElementInputHandler, Entity, EntityInputHandler, EventEmitter, FocusHandle, Focusable, Global,
25    GlobalElementId, KeyBinding, LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent,
26    MouseUpEvent, PaintQuad, Pixels, Point, SharedString, Style, Task, TextRun, UTF16Selection,
27    UnderlineStyle, Window, WrappedLine, actions, div, fill, prelude::*, px, relative,
28};
29use unicode_segmentation::UnicodeSegmentation as _;
30
31use theme::{HighlightKind, Metrics, SyntaxPalette, TextStyle, Theme};
32
33pub mod caret;
34mod chip;
35mod edit;
36mod element;
37mod ime;
38pub mod overdraw;
39mod text;
40
41pub use caret::{CaretHeight, CaretShape, InactiveCaret};
42pub use chip::Chip;
43pub use element::*;
44pub use text::*;
45
46actions!(
47    bezel_text_field,
48    [
49        Backspace,
50        Delete,
51        Left,
52        Right,
53        SelectLeft,
54        SelectRight,
55        SelectAll,
56        Home,
57        End,
58        SelectHome,
59        SelectEnd,
60        WordLeft,
61        WordRight,
62        SelectWordLeft,
63        SelectWordRight,
64        DeleteWordLeft,
65        DeleteWordRight,
66        DeleteToLineStart,
67        DeleteToLineEnd,
68        ShowCharacterPalette,
69        Paste,
70        Cut,
71        Copy,
72        Up,
73        Down,
74        SelectUp,
75        SelectDown,
76        InsertNewline,
77        Undo,
78        Redo,
79    ]
80);
81
82/// How many undo steps a field keeps by default.
83///
84/// Steps, not keystrokes: a run of typing coalesces into one, so this is deeper
85/// than it looks. A text field is not a document — nobody walks a search box
86/// back through a long history — and the ceiling is what stops a long-lived
87/// field accumulating snapshots forever. Override per field with
88/// [`TextField::with_undo_limit`].
89pub const DEFAULT_UNDO_LIMIT: usize = 10;
90
91/// What a field reports, one per user action.
92///
93/// [`gpui::Context::observe`] fires on every `notify`, which includes repaints
94/// nothing asked for — the caret's own blink among them. A picker refiltering
95/// on those throws its cursor back to the first row twice a second. Subscribe
96/// to this instead, and take only the half you need: a picker filters on
97/// [`Self::Changed`], a composer reading the word behind the caret wants both.
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub enum FieldEvent {
100    /// The text is different, by this edit.
101    Changed(Edit),
102    /// The text is the same and the caret is somewhere else.
103    Moved,
104}
105
106/// One replacement in a field's text, in bytes: `start..old_end` of the text
107/// before became `start..new_end` of the text after. The fields are
108/// tree-sitter's `InputEdit` byte fields.
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub struct Edit {
111    pub start: usize,
112    pub old_end: usize,
113    pub new_end: usize,
114}
115
116impl Edit {
117    /// The smallest edit that turns `before` into `after`: what they share at
118    /// either end is left out.
119    pub fn between(before: &str, after: &str) -> Self {
120        let prefix = before
121            .char_indices()
122            .zip(after.chars())
123            .find(|((_, a), b)| a != b)
124            .map_or(before.len().min(after.len()), |((at, _), _)| at);
125        let suffix = before[prefix..]
126            .chars()
127            .rev()
128            .zip(after[prefix..].chars().rev())
129            .take_while(|(a, b)| a == b)
130            .map(|(a, _)| a.len_utf8())
131            .sum::<usize>();
132        Self {
133            start: prefix,
134            old_end: before.len() - suffix,
135            new_end: after.len() - suffix,
136        }
137    }
138
139    /// Where `range` of the text before lands in the text after. A range
140    /// wholly before the edit stays, one wholly after moves by the length the
141    /// edit added or took, one the edit falls inside grows or shrinks with it,
142    /// and one the edit cuts keeps the part it did not touch. `None` when the
143    /// edit took all of it.
144    pub fn map(self, range: Range<usize>) -> Option<Range<usize>> {
145        let shift = |at: usize| at + self.new_end - self.old_end;
146        let mapped = if range.end <= self.start {
147            range
148        } else if range.start >= self.old_end {
149            shift(range.start)..shift(range.end)
150        } else if range.start < self.start && self.old_end < range.end {
151            range.start..shift(range.end)
152        } else if range.start < self.start {
153            range.start..self.start
154        } else if self.old_end < range.end {
155            self.new_end..shift(range.end)
156        } else {
157            return None;
158        };
159        (!mapped.is_empty()).then_some(mapped)
160    }
161}
162
163/// Half the caret's blink period — the 500ms on, 500ms off macOS itself uses.
164const BLINK: Duration = Duration::from_millis(500);
165
166/// Whether carets blink. Absent means they do — a global nobody installed is
167/// the default, not the opposite of it.
168struct CaretBlink(bool);
169
170impl Global for CaretBlink {}
171
172/// Whether a caret blinks or is held solid. Read where a blink would start:
173/// [`TextField`] here, and the editor's own caret.
174pub(crate) fn caret_blink(cx: &App) -> bool {
175    cx.try_global::<CaretBlink>().is_none_or(|blink| blink.0)
176}
177
178/// A caret held solid is still a caret — turning the blink off stops the task
179/// and leaves the caret lit, never caught on the half of the beat that hides it.
180pub(crate) fn set_caret_blink(blink: bool, cx: &mut App) {
181    cx.set_global(CaretBlink(blink));
182    cx.refresh_windows();
183}
184
185/// Width of the caret. Named because horizontal scrolling has to keep the caret
186/// itself on screen, not merely the character before it.
187const CARET_WIDTH: Pixels = px(2.);
188
189/// The key context the field claims; bindings from [`init`] are scoped to it.
190pub const KEY_CONTEXT: &str = "TextField";
191
192/// Claimed *in addition* to [`KEY_CONTEXT`] by a multi-line field.
193///
194/// Vertical motion and `enter` hang off this rather than off every field,
195/// because a single-line field is routinely nested inside something that has
196/// already claimed those keys: [`crate::palette`] and [`crate::combobox`] both
197/// bind `up`, `down`, `ctrl-n`, `ctrl-p` and `enter` to drive their lists, and
198/// their query field sits *deeper* in the focus path — so binding those on
199/// every `TextField` would win the dispatch and break list navigation in both.
200pub const MULTILINE_KEY_CONTEXT: &str = "TextArea";
201
202/// Install the bindings — [`bindings`], bound. Call once at startup.
203pub fn init(cx: &mut App) {
204    cx.bind_keys(bindings());
205}
206
207/// The field's keymap, as data, so an app can have it without having to
208/// take it — see [`crate::keys`] for layering over it or taking a chord
209/// away.
210///
211/// Every binding is scoped to [`KEY_CONTEXT`], so they are inert outside a
212/// focused field and an app is free to bind the same chords elsewhere.
213pub fn bindings() -> Vec<KeyBinding> {
214    let mut bindings = Vec::new();
215    let ctx = Some(KEY_CONTEXT);
216    bindings.extend([
217        // Character movement and editing, everywhere.
218        KeyBinding::new("backspace", Backspace, ctx),
219        KeyBinding::new("delete", Delete, ctx),
220        KeyBinding::new("left", Left, ctx),
221        KeyBinding::new("right", Right, ctx),
222        KeyBinding::new("shift-left", SelectLeft, ctx),
223        KeyBinding::new("shift-right", SelectRight, ctx),
224        KeyBinding::new("home", Home, ctx),
225        KeyBinding::new("end", End, ctx),
226        KeyBinding::new("shift-home", SelectHome, ctx),
227        KeyBinding::new("shift-end", SelectEnd, ctx),
228    ]);
229
230    // Multi-line only — see [`MULTILINE_KEY_CONTEXT`] for why these cannot be
231    // bound on every field.
232    let area = Some(MULTILINE_KEY_CONTEXT);
233    bindings.extend([
234        KeyBinding::new("enter", InsertNewline, area),
235        KeyBinding::new("up", Up, area),
236        KeyBinding::new("down", Down, area),
237        KeyBinding::new("shift-up", SelectUp, area),
238        KeyBinding::new("shift-down", SelectDown, area),
239    ]);
240
241    #[cfg(target_os = "macos")]
242    bindings.extend([
243        KeyBinding::new("cmd-a", SelectAll, ctx),
244        KeyBinding::new("cmd-c", Copy, ctx),
245        KeyBinding::new("cmd-x", Cut, ctx),
246        KeyBinding::new("cmd-v", Paste, ctx),
247        KeyBinding::new("cmd-z", Undo, ctx),
248        KeyBinding::new("cmd-shift-z", Redo, ctx),
249        KeyBinding::new("ctrl-cmd-space", ShowCharacterPalette, ctx),
250        // cmd = line, option = word: the macOS convention.
251        KeyBinding::new("cmd-left", Home, ctx),
252        KeyBinding::new("cmd-right", End, ctx),
253        KeyBinding::new("cmd-shift-left", SelectHome, ctx),
254        KeyBinding::new("cmd-shift-right", SelectEnd, ctx),
255        KeyBinding::new("alt-left", WordLeft, ctx),
256        KeyBinding::new("alt-right", WordRight, ctx),
257        KeyBinding::new("alt-shift-left", SelectWordLeft, ctx),
258        KeyBinding::new("alt-shift-right", SelectWordRight, ctx),
259        KeyBinding::new("cmd-backspace", DeleteToLineStart, ctx),
260        KeyBinding::new("alt-backspace", DeleteWordLeft, ctx),
261        KeyBinding::new("alt-delete", DeleteWordRight, ctx),
262        // The emacs bindings macOS honours in every native text field.
263        KeyBinding::new("ctrl-a", Home, ctx),
264        KeyBinding::new("ctrl-e", End, ctx),
265        KeyBinding::new("ctrl-b", Left, ctx),
266        KeyBinding::new("ctrl-f", Right, ctx),
267        KeyBinding::new("ctrl-h", Backspace, ctx),
268        KeyBinding::new("ctrl-d", Delete, ctx),
269        KeyBinding::new("ctrl-k", DeleteToLineEnd, ctx),
270    ]);
271
272    // `C-n`/`C-p` are emacs' vertical motion and macOS `NSTextView` natives
273    // both — the two tests a chord has to pass to earn a binding here.
274    #[cfg(target_os = "macos")]
275    bindings.extend([
276        KeyBinding::new("ctrl-n", Down, area),
277        KeyBinding::new("ctrl-p", Up, area),
278    ]);
279
280    #[cfg(not(target_os = "macos"))]
281    bindings.extend([
282        KeyBinding::new("ctrl-a", SelectAll, ctx),
283        KeyBinding::new("ctrl-c", Copy, ctx),
284        KeyBinding::new("ctrl-x", Cut, ctx),
285        KeyBinding::new("ctrl-v", Paste, ctx),
286        // ctrl = word on Windows/Linux, where there is no line modifier.
287        KeyBinding::new("ctrl-left", WordLeft, ctx),
288        KeyBinding::new("ctrl-right", WordRight, ctx),
289        KeyBinding::new("ctrl-shift-left", SelectWordLeft, ctx),
290        KeyBinding::new("ctrl-shift-right", SelectWordRight, ctx),
291        KeyBinding::new("ctrl-backspace", DeleteWordLeft, ctx),
292        KeyBinding::new("ctrl-delete", DeleteWordRight, ctx),
293        KeyBinding::new("ctrl-z", Undo, ctx),
294        KeyBinding::new("ctrl-shift-z", Redo, ctx),
295        KeyBinding::new("ctrl-y", Redo, ctx),
296    ]);
297
298    bindings
299}
300
301/// What case a field holds its text in.
302///
303/// Applied to every edit rather than to the string on its way out, so what is
304/// painted, what `content()` returns and what a caller stores are one string.
305#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
306pub enum Case {
307    /// Whatever was typed.
308    #[default]
309    Mixed,
310    /// Upper, for a field naming something a heading is drawn from.
311    Upper,
312}
313
314impl Case {
315    /// `text` in this case. Borrowed where the case leaves it alone, which
316    /// is the default and every keystroke through it.
317    fn apply(self, text: &str) -> Cow<'_, str> {
318        match self {
319            Self::Mixed => Cow::Borrowed(text),
320            Self::Upper => Cow::Owned(text.to_uppercase()),
321        }
322    }
323}
324
325/// What shape the field takes.
326///
327/// Editing is identical across every shape — every action works on the content
328/// and a byte range, and none of them cares where the lines break. What this
329/// decides is the box: how tall it is, whether text wraps, and with that what
330/// `enter` and a pasted newline are allowed to mean.
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
332pub enum Shape {
333    /// One line, no wrapping. `enter` does not insert; a pasted newline becomes
334    /// a space rather than silently truncating what was pasted.
335    #[default]
336    Line,
337    /// Exactly `rows` lines tall, wrapping, scrolling past that.
338    Rows(usize),
339    /// Wraps and grows with the content between `min` and `max` rows, then
340    /// scrolls — the composer shape.
341    Grow { min: usize, max: usize },
342    /// As tall as its parent, wrapping, scrolling past that. The parent must
343    /// give it a definite height.
344    Fill,
345}
346
347impl Shape {
348    /// Whether newlines are content. The single branch every editing policy
349    /// hangs off, so it is asked once rather than matched in each caller.
350    fn is_multiline(self) -> bool {
351        !matches!(self, Self::Line)
352    }
353}
354
355/// A point the field can be returned to.
356///
357/// A whole snapshot rather than a diff: a field holds a sentence, not a file,
358/// and `SharedString` clones are a refcount bump. A rope and a transaction log
359/// is what an editor needs and would be the wrong machinery here.
360#[derive(Clone)]
361struct Snapshot {
362    content: SharedString,
363    selection: Range<usize>,
364    reversed: bool,
365    chips: Vec<Chip>,
366}
367
368/// Which way an edit went, so a run of the same kind can coalesce into one
369/// undo step instead of giving the text back a character at a time.
370#[derive(Clone, Copy, PartialEq, Eq)]
371pub enum EditKind {
372    Insert,
373    Delete,
374}
375
376/// A text field. [`Shape`] decides whether it is one line or many; everything
377/// else about it is the same either way.
378pub struct TextField {
379    focus_handle: FocusHandle,
380    content: SharedString,
381    placeholder: SharedString,
382    shape: Shape,
383    /// The case every edit is put through — see [`Case`].
384    case: Case,
385    selected_range: Range<usize>,
386    selection_reversed: bool,
387    /// The IME composition range (underlined while composing).
388    marked_range: Option<Range<usize>>,
389    /// One entry per hard newline; each wraps into rows of its own. Empty until
390    /// the first paint.
391    last_layout: Vec<WrappedLine>,
392    /// Where the content's offsets land in `last_layout`'s.
393    last_shown: Shown,
394    last_bounds: Option<Bounds<Pixels>>,
395    /// The press being dragged out: what it selects by, and what it selected.
396    selecting: Option<(Granularity, Range<usize>)>,
397    /// The column vertical motion is trying to keep, in pixels from the left of
398    /// the row. Held across a run of up/down so that walking through a short
399    /// line and out the other side returns to the column you started in, and
400    /// dropped by anything horizontal — which is every other way the caret
401    /// moves, so [`TextField::move_to`] and [`TextField::select_to`] clear it
402    /// and the vertical handlers put it back.
403    goal_x: Option<Pixels>,
404    /// How far the text is scrolled inside the box. Clamped every frame,
405    /// because the content it is measured against changes under it.
406    ///
407    /// Both axes, though only ever one at a time: a wrapped field's lines are
408    /// shaped to the box width so they cannot overflow sideways, and a
409    /// single-line field is exactly one row tall so it cannot overflow
410    /// downwards. The clamp falls out of that and needs no test for shape.
411    scroll: Point<Pixels>,
412    history: crate::history::SnapshotHistory<Snapshot>,
413    /// The kind of the last edit and the offset it left the caret at, which is
414    /// what decides whether the next edit joins that group or starts a new one.
415    /// Adjacency rather than a pause, so there is no timing threshold to invent.
416    last_edit: Option<(EditKind, usize)>,
417    /// A context this field claims *in addition* to [`KEY_CONTEXT`] and
418    /// [`MULTILINE_KEY_CONTEXT`] — see [`Self::with_key_context`].
419    key_context: Option<SharedString>,
420    /// Whether the field paints a box around itself. Off for a field that
421    /// stands in for text already in place — a rename in a list row, where the
422    /// box would be a second frame inside the row's own.
423    frame: bool,
424    /// What the text is set in. Its leading is a multiple of the painted size,
425    /// so the whole line box follows [`theme::AppExt::set_base_text_size`].
426    metrics: Metrics,
427    mono: bool,
428    /// Which half of the blink the caret is in. Flipped by [`Self::start_blink`].
429    caret_on: bool,
430    /// The blink, alive only while the field holds focus.
431    blink: Option<Task<()>>,
432    /// Set by anything that moves the caret, cleared once a frame has scrolled
433    /// it back into view.
434    ///
435    /// Without the flag the wheel could never win: following the caret
436    /// unconditionally would snap the view back to it on the very next frame,
437    /// so scrolling away to read would be impossible.
438    follow_caret: bool,
439    last_caret_shape: CaretShape,
440    /// Byte ranges to paint in a syntax colour, in document order — see
441    /// [`Self::set_spans`]. Empty for every field that is prose.
442    spans: Vec<(Range<usize>, HighlightKind)>,
443    /// Byte ranges washed behind the text — see [`Self::set_matches`].
444    matches: Vec<Range<usize>>,
445    /// In document order, none overlapping — see [`Self::set_chips`].
446    chips: Vec<Chip>,
447    /// The right-click menu.
448    menu: crate::context_menu::ContextMenu<Self>,
449}
450
451impl EventEmitter<FieldEvent> for TextField {}
452
453impl TextField {
454    pub fn new(cx: &mut Context<Self>) -> Self {
455        Self {
456            // A field is a tab stop from birth; a stateless control needs
457            // `focus::focusable` because its handle lives in the caller.
458            focus_handle: cx.focus_handle().tab_stop(true),
459            frame: true,
460            content: "".into(),
461            placeholder: "".into(),
462            shape: Shape::Line,
463            case: Case::default(),
464            selected_range: 0..0,
465            selection_reversed: false,
466            marked_range: None,
467            last_layout: Vec::new(),
468            last_shown: Shown::default(),
469            last_bounds: None,
470            selecting: None,
471            goal_x: None,
472            scroll: Point::default(),
473            history: crate::history::SnapshotHistory::new(DEFAULT_UNDO_LIMIT),
474            last_edit: None,
475            key_context: None,
476            metrics: TextStyle::Body.into(),
477            mono: false,
478            caret_on: true,
479            blink: None,
480            follow_caret: false,
481            last_caret_shape: CaretShape::Bar,
482            spans: Vec::new(),
483            matches: Vec::new(),
484            chips: Vec::new(),
485            menu: Default::default(),
486        }
487    }
488
489    /// How many undo steps to keep. App-wide configuration would be a gpui
490    /// global alongside [`crate::input::init`], not a [`Theme`] field — the
491    /// theme is rebuilt on every light/dark switch, which would quietly reset
492    /// anything behavioural parked in it.
493    pub fn with_undo_limit(mut self, limit: usize) -> Self {
494        self.history.set_limit(limit);
495        self
496    }
497
498    /// Use the current theme's monospace family for text and placeholder.
499    pub fn with_mono(mut self) -> Self {
500        self.mono = true;
501        self
502    }
503
504    pub fn with_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
505        self.placeholder = placeholder.into();
506        self
507    }
508
509    /// Claim an extra key context on this field, so an app can bind a key
510    /// *here* that it does not want bound in every other field.
511    ///
512    /// The composer case, and the reason this exists: `enter` sends a message
513    /// and `shift-enter` breaks a line, while the notes field two panels over
514    /// still takes `enter` as a newline. gpui resolves a keystroke to the
515    /// binding whose context matches **deepest** in the focus path, and nothing
516    /// is deeper than the focused field — so a container around it cannot win
517    /// `enter`, however it is bound. Rebinding [`MULTILINE_KEY_CONTEXT`]
518    /// globally would win, and would take the newline away from every other
519    /// multi-line field in the app. A context of the field's own is the only
520    /// thing that is both deep enough and narrow enough.
521    ///
522    /// ```ignore
523    /// const COMPOSER: &str = "Composer";
524    /// cx.bind_keys([
525    ///     KeyBinding::new("enter", Send, Some(COMPOSER)),
526    ///     KeyBinding::new("shift-enter", input::InsertNewline, Some(COMPOSER)),
527    /// ]);
528    /// let field = cx.new(|cx| {
529    ///     TextField::new(cx)
530    ///         .with_shape(Shape::Grow { min: 3, max: 12 })
531    ///         .with_key_context(COMPOSER)
532    /// });
533    /// ```
534    pub fn with_key_context(mut self, context: impl Into<SharedString>) -> Self {
535        self.key_context = Some(context.into());
536        self
537    }
538
539    /// Draw without the box, padding and focus ring. The caller owns the
540    /// spacing then, and owns showing that the field is focused.
541    pub fn with_frame(mut self, frame: bool) -> Self {
542        self.frame = frame;
543        self
544    }
545
546    /// Set the text in something other than body copy —
547    /// `cx.typography().h1` sets a field the way a document sets its own
548    /// heading.
549    pub fn with_metrics(mut self, metrics: Metrics) -> Self {
550        self.metrics = metrics;
551        self
552    }
553
554    /// Update typography without replacing the editing state.
555    pub fn set_metrics(&mut self, metrics: Metrics, cx: &mut Context<Self>) {
556        if self.metrics != metrics {
557            self.metrics = metrics;
558            cx.notify();
559        }
560    }
561
562    pub fn with_shape(mut self, shape: Shape) -> Self {
563        self.shape = shape;
564        self
565    }
566
567    pub fn with_case(mut self, case: Case) -> Self {
568        self.case = case;
569        self
570    }
571
572    /// The case from here on. What the field already holds is left as it is:
573    /// the text came from somewhere else, and a caller switching the case of a
574    /// shared field would otherwise rewrite the name it is showing.
575    pub fn set_case(&mut self, case: Case) {
576        self.case = case;
577    }
578
579    pub fn case(&self) -> Case {
580        self.case
581    }
582
583    pub fn shape(&self) -> Shape {
584        self.shape
585    }
586
587    pub fn content(&self) -> &SharedString {
588        &self.content
589    }
590
591    /// The syntax spans this field is painting — see [`Self::set_spans`].
592    pub fn spans(&self) -> &[(Range<usize>, HighlightKind)] {
593        &self.spans
594    }
595
596    /// Replace the content, putting the cursor at the end. Clears the undo
597    /// history.
598    pub fn set_content(&mut self, content: impl Into<SharedString>, cx: &mut Context<Self>) {
599        let normalized = normalize(&content.into(), self.shape);
600        let before = self.content.len();
601        self.content = self.case.apply(&normalized).into_owned().into();
602        // Colours describe text this field no longer holds.
603        self.spans.clear();
604        self.matches.clear();
605        self.chips.clear();
606        // A programmatic reset is not something the user did, so there is
607        // nothing here for them to undo back past.
608        self.history.clear();
609        self.last_edit = None;
610        let end = self.content.len();
611        self.selected_range = end..end;
612        self.marked_range = None;
613        cx.emit(FieldEvent::Changed(Edit {
614            start: 0,
615            old_end: before,
616            new_end: end,
617        }));
618        cx.notify();
619    }
620
621    pub fn clear(&mut self, cx: &mut Context<Self>) {
622        self.set_content("", cx);
623    }
624
625    /// Carry the spans and chips through an edit just applied, and say so.
626    fn edited(&mut self, edit: Edit, cx: &mut Context<Self>) {
627        let spans = std::mem::take(&mut self.spans);
628        self.spans = spans
629            .into_iter()
630            .filter_map(|(range, kind)| Some((edit.map(range)?, kind)))
631            .collect();
632        self.chips
633            .retain_mut(|chip| match chip::follow(edit, &chip.range) {
634                Some(range) => {
635                    chip.range = range;
636                    true
637                }
638                None => false,
639            });
640        cx.emit(FieldEvent::Changed(edit));
641    }
642
643    /// Paint these byte ranges in syntax colours, in document order. Whatever
644    /// they leave uncovered stays the field's own text colour, so a language
645    /// nothing can colour is simply no spans at all.
646    ///
647    /// This field holds text, not a document: it does not parse. Each edit it
648    /// applies moves the spans through [`Edit::map`], so until the caller hands
649    /// over fresh ones — [`FieldEvent::Changed`] carries the edit to reparse
650    /// from — they stay on the characters they were computed for.
651    ///
652    /// [`set_content`](Self::set_content) clears them: replacing the text
653    /// replaces what the colours were about.
654    pub fn set_spans(&mut self, spans: Vec<(Range<usize>, HighlightKind)>, cx: &mut Context<Self>) {
655        self.spans = spans;
656        cx.notify();
657    }
658
659    /// Wash these byte ranges behind the text, as search matches. Not kept in
660    /// step with edits, and cleared by [`Self::set_content`], the same as
661    /// [`Self::set_spans`]. A range past the end or off a char boundary is
662    /// not painted.
663    pub fn set_matches(&mut self, matches: Vec<Range<usize>>, cx: &mut Context<Self>) {
664        self.matches = matches;
665        cx.notify();
666    }
667
668    /// Paint these ranges of the content as chips — see [`Chip`].
669    ///
670    /// The content keeps the source text; only painting and editing change. The
671    /// caret steps over a chip, a selection that cuts one takes all of it, and
672    /// one delete removes it. Each edit moves the chips with the text, and an
673    /// edit reaching inside one drops it. Undo and redo bring back the chips
674    /// each step had.
675    ///
676    /// A caret inside a chip moves to its end. [`Self::set_content`] clears
677    /// them.
678    pub fn set_chips(&mut self, mut chips: Vec<Chip>, cx: &mut Context<Self>) {
679        chips.sort_by_key(|chip| chip.range.start);
680        self.chips = chips;
681        self.selected_range = match self.selected_range.is_empty() {
682            true => {
683                let at = chip::outside(&self.chips, self.selected_range.start, false);
684                at..at
685            }
686            false => chip::widen(&self.chips, self.selected_range.clone()),
687        };
688        cx.notify();
689    }
690
691    /// The chips this field is painting — see [`Self::set_chips`].
692    pub fn chips(&self) -> &[Chip] {
693        &self.chips
694    }
695
696    /// Select `range` and scroll it into view, with the caret at its end.
697    /// Clamped to the content and to char boundaries, and grown over any chip
698    /// it cuts.
699    pub fn select(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
700        let end = floor_boundary(&self.content, range.end);
701        let start = floor_boundary(&self.content, range.start.min(end));
702        self.selected_range = match start == end {
703            true => {
704                let at = chip::outside(&self.chips, start, false);
705                at..at
706            }
707            false => chip::widen(&self.chips, start..end),
708        };
709        self.selection_reversed = false;
710        self.marked_range = None;
711        self.goal_x = None;
712        self.caret_moved();
713        cx.notify();
714    }
715
716    /// [`Self::with_placeholder`] after construction, for a hint that follows
717    /// something else — the field naming whichever agent, file or channel is
718    /// selected rather than being rebuilt each time one is.
719    pub fn set_placeholder(
720        &mut self,
721        placeholder: impl Into<SharedString>,
722        cx: &mut Context<Self>,
723    ) {
724        self.placeholder = placeholder.into();
725        cx.notify();
726    }
727
728    /// The caret moved: bring it back into view, and drop the blink so the next
729    /// render starts a fresh one. Without the reset the caret would blink
730    /// through your own typing, which reads as a dropped keystroke.
731    fn caret_moved(&mut self) {
732        self.follow_caret = true;
733        self.blink = None;
734    }
735
736    /// Blink the caret for as long as the field holds focus.
737    fn start_blink(&mut self, cx: &mut Context<Self>) {
738        self.caret_on = true;
739        self.blink = Some(cx.spawn(async move |field, cx| {
740            loop {
741                cx.background_executor().timer(BLINK).await;
742                let flipped = field.update(cx, |field, cx| {
743                    field.caret_on = !field.caret_on;
744                    cx.notify();
745                });
746                if flipped.is_err() {
747                    break;
748                }
749            }
750        }));
751    }
752
753    /// Where the caret is, as a byte offset into [`Self::content`].
754    ///
755    /// What a caller needs to read the text *behind* the caret: the `#` an
756    /// autocomplete triggers on, the word a lookup would act on. With a
757    /// selection this is the moving end, which is where typing would land.
758    pub fn cursor(&self) -> usize {
759        self.cursor_offset()
760    }
761
762    /// Where a byte offset sits on screen — the bounds of the row it is on, in
763    /// window coordinates.
764    ///
765    /// The anchor for anything that hangs off a position *in the text* rather
766    /// than off the field: a mention picker under the `#` that opened it, in a
767    /// box that is also growing a row at a time. Pass it to
768    /// [`crate::popover::menu_at`], which takes a window point.
769    ///
770    /// `None` until the field has painted once — this is measured off the
771    /// shaped layout, and there is none before then.
772    pub fn offset_bounds(&self, offset: usize) -> Option<Bounds<Pixels>> {
773        self.row_bounds(self.text_origin()?, offset..offset, self.line_height())
774    }
775
776    /// The rectangle `range` spans, starting from the row it opens on, relative
777    /// to `origin`.
778    ///
779    /// The IME's candidate panel and [`Self::offset_bounds`] are the same
780    /// question asked by two callers, so they ask it here — computed apart they
781    /// would answer differently the first time one of them forgot the scroll.
782    fn row_bounds(
783        &self,
784        origin: Point<Pixels>,
785        range: Range<usize>,
786        line_height: Pixels,
787    ) -> Option<Bounds<Pixels>> {
788        let range = self.last_shown.range(&range);
789        let start = position_for_offset(&self.last_layout, range.start, line_height)?;
790        let end = position_for_offset(&self.last_layout, range.end, line_height)?;
791        Some(Bounds::from_corners(
792            origin + start,
793            origin + gpui::point(end.x, end.y + line_height),
794        ))
795    }
796
797    /// Put the caret at `offset`, or past the chip it falls inside in the
798    /// direction it moved.
799    fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
800        let offset = chip::outside(&self.chips, offset, offset < self.cursor_offset());
801        self.selected_range = offset..offset;
802        self.goal_x = None;
803        self.caret_moved();
804        cx.emit(FieldEvent::Moved);
805        cx.notify()
806    }
807
808    fn cursor_offset(&self) -> usize {
809        if self.selection_reversed {
810            self.selected_range.start
811        } else {
812            self.selected_range.end
813        }
814    }
815
816    fn anchor_offset(&self) -> usize {
817        if self.selection_reversed {
818            self.selected_range.end
819        } else {
820            self.selected_range.start
821        }
822    }
823
824    /// Select from `anchor` to `head`, the caret at `head`.
825    fn select_span(&mut self, anchor: usize, head: usize, cx: &mut Context<Self>) {
826        self.selected_range = chip::widen(&self.chips, anchor.min(head)..anchor.max(head));
827        self.selection_reversed = head < anchor;
828        self.goal_x = None;
829        self.caret_moved();
830        cx.emit(FieldEvent::Moved);
831        cx.notify()
832    }
833
834    /// The row height every mapping between a screen point and a byte offset
835    /// walks by: this field's own, which is what its shaped lines were laid
836    /// out at — see [`TextField::render`], which sets it on the box.
837    ///
838    /// Never `window.line_height()`. That answers for whatever text style is
839    /// current, and outside this field's own paint there is none of it on the
840    /// stack — a click handler is told the window's default instead. Walk the
841    /// rows at that stride and the caret lands a line or two above the one
842    /// under the pointer, further out the lower you click, until the last
843    /// lines of a full box cannot be reached at all.
844    fn line_height(&self) -> Pixels {
845        px(self.metrics.line_height())
846    }
847
848    /// Where the shaped text starts on screen: the box, moved up by the scroll.
849    /// Every mapping between a screen point and a byte offset goes through it.
850    fn text_origin(&self) -> Option<Point<Pixels>> {
851        Some(self.last_bounds?.origin - self.scroll)
852    }
853
854    fn index_for_mouse_position(&self, position: Point<Pixels>, line_height: Pixels) -> usize {
855        if self.content.is_empty() || self.last_layout.is_empty() {
856            return 0;
857        }
858        let Some(origin) = self.text_origin() else {
859            return 0;
860        };
861        self.offset_at(position - origin, line_height)
862    }
863
864    /// The chip under a window point, if any.
865    fn chip_at(&self, position: Point<Pixels>, line_height: Pixels) -> Option<Range<usize>> {
866        let at = offset_for_position(
867            &self.last_layout,
868            position - self.text_origin()?,
869            line_height,
870        );
871        self.chips
872            .iter()
873            .map(|chip| chip.range.clone())
874            .find(|range| self.last_shown.range(range).contains(&at))
875    }
876
877    /// Where `offset` sits in the last frame, relative to the text origin.
878    fn position_of(&self, offset: usize, line_height: Pixels) -> Option<Point<Pixels>> {
879        position_for_offset(&self.last_layout, self.last_shown.at(offset), line_height)
880    }
881
882    /// The offset closest to a point relative to the text origin in the last
883    /// frame. A point on a chip lands on its nearer end.
884    fn offset_at(&self, position: Point<Pixels>, line_height: Pixels) -> usize {
885        self.last_shown.offset(offset_for_position(
886            &self.last_layout,
887            position,
888            line_height,
889        ))
890    }
891
892    /// Extend the selection to `offset`, or past the chip it falls inside in
893    /// the direction it moved.
894    fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
895        let offset = chip::outside(&self.chips, offset, offset < self.cursor_offset());
896        self.goal_x = None;
897        self.caret_moved();
898        if self.selection_reversed {
899            self.selected_range.start = offset
900        } else {
901            self.selected_range.end = offset
902        };
903        if self.selected_range.end < self.selected_range.start {
904            self.selection_reversed = !self.selection_reversed;
905            self.selected_range = self.selected_range.end..self.selected_range.start;
906        }
907        cx.emit(FieldEvent::Moved);
908        cx.notify()
909    }
910
911    fn offset_to_utf16(&self, offset: usize) -> usize {
912        offset_to_utf16(&self.content, offset)
913    }
914
915    fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
916        range_to_utf16(&self.content, range.clone())
917    }
918
919    fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
920        range_from_utf16(&self.content, range_utf16.clone())
921    }
922
923    fn previous_boundary(&self, offset: usize) -> usize {
924        previous_boundary(&self.content, offset)
925    }
926
927    fn next_boundary(&self, offset: usize) -> usize {
928        next_boundary(&self.content, offset)
929    }
930}
931
932impl Focusable for TextField {
933    fn focus_handle(&self, _: &App) -> FocusHandle {
934        self.focus_handle.clone()
935    }
936}