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    /// Which half of the blink the caret is in. Flipped by [`Self::start_blink`].
428    caret_on: bool,
429    /// The blink, alive only while the field holds focus.
430    blink: Option<Task<()>>,
431    /// Set by anything that moves the caret, cleared once a frame has scrolled
432    /// it back into view.
433    ///
434    /// Without the flag the wheel could never win: following the caret
435    /// unconditionally would snap the view back to it on the very next frame,
436    /// so scrolling away to read would be impossible.
437    follow_caret: bool,
438    last_caret_shape: CaretShape,
439    /// Byte ranges to paint in a syntax colour, in document order — see
440    /// [`Self::set_spans`]. Empty for every field that is prose.
441    spans: Vec<(Range<usize>, HighlightKind)>,
442    /// Byte ranges washed behind the text — see [`Self::set_matches`].
443    matches: Vec<Range<usize>>,
444    /// In document order, none overlapping — see [`Self::set_chips`].
445    chips: Vec<Chip>,
446    /// The right-click menu.
447    menu: crate::context_menu::ContextMenu<Self>,
448}
449
450impl EventEmitter<FieldEvent> for TextField {}
451
452impl TextField {
453    pub fn new(cx: &mut Context<Self>) -> Self {
454        Self {
455            // A field is a tab stop from birth; a stateless control needs
456            // `focus::focusable` because its handle lives in the caller.
457            focus_handle: cx.focus_handle().tab_stop(true),
458            frame: true,
459            content: "".into(),
460            placeholder: "".into(),
461            shape: Shape::Line,
462            case: Case::default(),
463            selected_range: 0..0,
464            selection_reversed: false,
465            marked_range: None,
466            last_layout: Vec::new(),
467            last_shown: Shown::default(),
468            last_bounds: None,
469            selecting: None,
470            goal_x: None,
471            scroll: Point::default(),
472            history: crate::history::SnapshotHistory::new(DEFAULT_UNDO_LIMIT),
473            last_edit: None,
474            key_context: None,
475            metrics: TextStyle::Body.into(),
476            caret_on: true,
477            blink: None,
478            follow_caret: false,
479            last_caret_shape: CaretShape::Bar,
480            spans: Vec::new(),
481            matches: Vec::new(),
482            chips: Vec::new(),
483            menu: Default::default(),
484        }
485    }
486
487    /// How many undo steps to keep. App-wide configuration would be a gpui
488    /// global alongside [`crate::input::init`], not a [`Theme`] field — the
489    /// theme is rebuilt on every light/dark switch, which would quietly reset
490    /// anything behavioural parked in it.
491    pub fn with_undo_limit(mut self, limit: usize) -> Self {
492        self.history.set_limit(limit);
493        self
494    }
495
496    pub fn with_placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
497        self.placeholder = placeholder.into();
498        self
499    }
500
501    /// Claim an extra key context on this field, so an app can bind a key
502    /// *here* that it does not want bound in every other field.
503    ///
504    /// The composer case, and the reason this exists: `enter` sends a message
505    /// and `shift-enter` breaks a line, while the notes field two panels over
506    /// still takes `enter` as a newline. gpui resolves a keystroke to the
507    /// binding whose context matches **deepest** in the focus path, and nothing
508    /// is deeper than the focused field — so a container around it cannot win
509    /// `enter`, however it is bound. Rebinding [`MULTILINE_KEY_CONTEXT`]
510    /// globally would win, and would take the newline away from every other
511    /// multi-line field in the app. A context of the field's own is the only
512    /// thing that is both deep enough and narrow enough.
513    ///
514    /// ```ignore
515    /// const COMPOSER: &str = "Composer";
516    /// cx.bind_keys([
517    ///     KeyBinding::new("enter", Send, Some(COMPOSER)),
518    ///     KeyBinding::new("shift-enter", input::InsertNewline, Some(COMPOSER)),
519    /// ]);
520    /// let field = cx.new(|cx| {
521    ///     TextField::new(cx)
522    ///         .with_shape(Shape::Grow { min: 3, max: 12 })
523    ///         .with_key_context(COMPOSER)
524    /// });
525    /// ```
526    pub fn with_key_context(mut self, context: impl Into<SharedString>) -> Self {
527        self.key_context = Some(context.into());
528        self
529    }
530
531    /// Draw without the box, padding and focus ring. The caller owns the
532    /// spacing then, and owns showing that the field is focused.
533    pub fn with_frame(mut self, frame: bool) -> Self {
534        self.frame = frame;
535        self
536    }
537
538    /// Set the text in something other than body copy —
539    /// `cx.typography().h1` sets a field the way a document sets its own
540    /// heading.
541    pub fn with_metrics(mut self, metrics: Metrics) -> Self {
542        self.metrics = metrics;
543        self
544    }
545
546    /// Update typography without replacing the editing state.
547    pub fn set_metrics(&mut self, metrics: Metrics, cx: &mut Context<Self>) {
548        if self.metrics != metrics {
549            self.metrics = metrics;
550            cx.notify();
551        }
552    }
553
554    pub fn with_shape(mut self, shape: Shape) -> Self {
555        self.shape = shape;
556        self
557    }
558
559    pub fn with_case(mut self, case: Case) -> Self {
560        self.case = case;
561        self
562    }
563
564    /// The case from here on. What the field already holds is left as it is:
565    /// the text came from somewhere else, and a caller switching the case of a
566    /// shared field would otherwise rewrite the name it is showing.
567    pub fn set_case(&mut self, case: Case) {
568        self.case = case;
569    }
570
571    pub fn case(&self) -> Case {
572        self.case
573    }
574
575    pub fn shape(&self) -> Shape {
576        self.shape
577    }
578
579    pub fn content(&self) -> &SharedString {
580        &self.content
581    }
582
583    /// The syntax spans this field is painting — see [`Self::set_spans`].
584    pub fn spans(&self) -> &[(Range<usize>, HighlightKind)] {
585        &self.spans
586    }
587
588    /// Replace the content, putting the cursor at the end. Clears the undo
589    /// history.
590    pub fn set_content(&mut self, content: impl Into<SharedString>, cx: &mut Context<Self>) {
591        let normalized = normalize(&content.into(), self.shape);
592        let before = self.content.len();
593        self.content = self.case.apply(&normalized).into_owned().into();
594        // Colours describe text this field no longer holds.
595        self.spans.clear();
596        self.matches.clear();
597        self.chips.clear();
598        // A programmatic reset is not something the user did, so there is
599        // nothing here for them to undo back past.
600        self.history.clear();
601        self.last_edit = None;
602        let end = self.content.len();
603        self.selected_range = end..end;
604        self.marked_range = None;
605        cx.emit(FieldEvent::Changed(Edit {
606            start: 0,
607            old_end: before,
608            new_end: end,
609        }));
610        cx.notify();
611    }
612
613    pub fn clear(&mut self, cx: &mut Context<Self>) {
614        self.set_content("", cx);
615    }
616
617    /// Carry the spans and chips through an edit just applied, and say so.
618    fn edited(&mut self, edit: Edit, cx: &mut Context<Self>) {
619        let spans = std::mem::take(&mut self.spans);
620        self.spans = spans
621            .into_iter()
622            .filter_map(|(range, kind)| Some((edit.map(range)?, kind)))
623            .collect();
624        self.chips
625            .retain_mut(|chip| match chip::follow(edit, &chip.range) {
626                Some(range) => {
627                    chip.range = range;
628                    true
629                }
630                None => false,
631            });
632        cx.emit(FieldEvent::Changed(edit));
633    }
634
635    /// Paint these byte ranges in syntax colours, in document order. Whatever
636    /// they leave uncovered stays the field's own text colour, so a language
637    /// nothing can colour is simply no spans at all.
638    ///
639    /// This field holds text, not a document: it does not parse. Each edit it
640    /// applies moves the spans through [`Edit::map`], so until the caller hands
641    /// over fresh ones — [`FieldEvent::Changed`] carries the edit to reparse
642    /// from — they stay on the characters they were computed for.
643    ///
644    /// [`set_content`](Self::set_content) clears them: replacing the text
645    /// replaces what the colours were about.
646    pub fn set_spans(&mut self, spans: Vec<(Range<usize>, HighlightKind)>, cx: &mut Context<Self>) {
647        self.spans = spans;
648        cx.notify();
649    }
650
651    /// Wash these byte ranges behind the text, as search matches. Not kept in
652    /// step with edits, and cleared by [`Self::set_content`], the same as
653    /// [`Self::set_spans`]. A range past the end or off a char boundary is
654    /// not painted.
655    pub fn set_matches(&mut self, matches: Vec<Range<usize>>, cx: &mut Context<Self>) {
656        self.matches = matches;
657        cx.notify();
658    }
659
660    /// Paint these ranges of the content as chips — see [`Chip`].
661    ///
662    /// The content keeps the source text; only painting and editing change. The
663    /// caret steps over a chip, a selection that cuts one takes all of it, and
664    /// one delete removes it. Each edit moves the chips with the text, and an
665    /// edit reaching inside one drops it. Undo and redo bring back the chips
666    /// each step had.
667    ///
668    /// A caret inside a chip moves to its end. [`Self::set_content`] clears
669    /// them.
670    pub fn set_chips(&mut self, mut chips: Vec<Chip>, cx: &mut Context<Self>) {
671        chips.sort_by_key(|chip| chip.range.start);
672        self.chips = chips;
673        self.selected_range = match self.selected_range.is_empty() {
674            true => {
675                let at = chip::outside(&self.chips, self.selected_range.start, false);
676                at..at
677            }
678            false => chip::widen(&self.chips, self.selected_range.clone()),
679        };
680        cx.notify();
681    }
682
683    /// The chips this field is painting — see [`Self::set_chips`].
684    pub fn chips(&self) -> &[Chip] {
685        &self.chips
686    }
687
688    /// Select `range` and scroll it into view, with the caret at its end.
689    /// Clamped to the content and to char boundaries, and grown over any chip
690    /// it cuts.
691    pub fn select(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
692        let end = floor_boundary(&self.content, range.end);
693        let start = floor_boundary(&self.content, range.start.min(end));
694        self.selected_range = match start == end {
695            true => {
696                let at = chip::outside(&self.chips, start, false);
697                at..at
698            }
699            false => chip::widen(&self.chips, start..end),
700        };
701        self.selection_reversed = false;
702        self.marked_range = None;
703        self.goal_x = None;
704        self.caret_moved();
705        cx.notify();
706    }
707
708    /// [`Self::with_placeholder`] after construction, for a hint that follows
709    /// something else — the field naming whichever agent, file or channel is
710    /// selected rather than being rebuilt each time one is.
711    pub fn set_placeholder(
712        &mut self,
713        placeholder: impl Into<SharedString>,
714        cx: &mut Context<Self>,
715    ) {
716        self.placeholder = placeholder.into();
717        cx.notify();
718    }
719
720    /// The caret moved: bring it back into view, and drop the blink so the next
721    /// render starts a fresh one. Without the reset the caret would blink
722    /// through your own typing, which reads as a dropped keystroke.
723    fn caret_moved(&mut self) {
724        self.follow_caret = true;
725        self.blink = None;
726    }
727
728    /// Blink the caret for as long as the field holds focus.
729    fn start_blink(&mut self, cx: &mut Context<Self>) {
730        self.caret_on = true;
731        self.blink = Some(cx.spawn(async move |field, cx| {
732            loop {
733                cx.background_executor().timer(BLINK).await;
734                let flipped = field.update(cx, |field, cx| {
735                    field.caret_on = !field.caret_on;
736                    cx.notify();
737                });
738                if flipped.is_err() {
739                    break;
740                }
741            }
742        }));
743    }
744
745    /// Where the caret is, as a byte offset into [`Self::content`].
746    ///
747    /// What a caller needs to read the text *behind* the caret: the `#` an
748    /// autocomplete triggers on, the word a lookup would act on. With a
749    /// selection this is the moving end, which is where typing would land.
750    pub fn cursor(&self) -> usize {
751        self.cursor_offset()
752    }
753
754    /// Where a byte offset sits on screen — the bounds of the row it is on, in
755    /// window coordinates.
756    ///
757    /// The anchor for anything that hangs off a position *in the text* rather
758    /// than off the field: a mention picker under the `#` that opened it, in a
759    /// box that is also growing a row at a time. Pass it to
760    /// [`crate::popover::menu_at`], which takes a window point.
761    ///
762    /// `None` until the field has painted once — this is measured off the
763    /// shaped layout, and there is none before then.
764    pub fn offset_bounds(&self, offset: usize) -> Option<Bounds<Pixels>> {
765        self.row_bounds(self.text_origin()?, offset..offset, self.line_height())
766    }
767
768    /// The rectangle `range` spans, starting from the row it opens on, relative
769    /// to `origin`.
770    ///
771    /// The IME's candidate panel and [`Self::offset_bounds`] are the same
772    /// question asked by two callers, so they ask it here — computed apart they
773    /// would answer differently the first time one of them forgot the scroll.
774    fn row_bounds(
775        &self,
776        origin: Point<Pixels>,
777        range: Range<usize>,
778        line_height: Pixels,
779    ) -> Option<Bounds<Pixels>> {
780        let range = self.last_shown.range(&range);
781        let start = position_for_offset(&self.last_layout, range.start, line_height)?;
782        let end = position_for_offset(&self.last_layout, range.end, line_height)?;
783        Some(Bounds::from_corners(
784            origin + start,
785            origin + gpui::point(end.x, end.y + line_height),
786        ))
787    }
788
789    /// Put the caret at `offset`, or past the chip it falls inside in the
790    /// direction it moved.
791    fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
792        let offset = chip::outside(&self.chips, offset, offset < self.cursor_offset());
793        self.selected_range = offset..offset;
794        self.goal_x = None;
795        self.caret_moved();
796        cx.emit(FieldEvent::Moved);
797        cx.notify()
798    }
799
800    fn cursor_offset(&self) -> usize {
801        if self.selection_reversed {
802            self.selected_range.start
803        } else {
804            self.selected_range.end
805        }
806    }
807
808    fn anchor_offset(&self) -> usize {
809        if self.selection_reversed {
810            self.selected_range.end
811        } else {
812            self.selected_range.start
813        }
814    }
815
816    /// Select from `anchor` to `head`, the caret at `head`.
817    fn select_span(&mut self, anchor: usize, head: usize, cx: &mut Context<Self>) {
818        self.selected_range = chip::widen(&self.chips, anchor.min(head)..anchor.max(head));
819        self.selection_reversed = head < anchor;
820        self.goal_x = None;
821        self.caret_moved();
822        cx.emit(FieldEvent::Moved);
823        cx.notify()
824    }
825
826    /// The row height every mapping between a screen point and a byte offset
827    /// walks by: this field's own, which is what its shaped lines were laid
828    /// out at — see [`TextField::render`], which sets it on the box.
829    ///
830    /// Never `window.line_height()`. That answers for whatever text style is
831    /// current, and outside this field's own paint there is none of it on the
832    /// stack — a click handler is told the window's default instead. Walk the
833    /// rows at that stride and the caret lands a line or two above the one
834    /// under the pointer, further out the lower you click, until the last
835    /// lines of a full box cannot be reached at all.
836    fn line_height(&self) -> Pixels {
837        px(self.metrics.line_height())
838    }
839
840    /// Where the shaped text starts on screen: the box, moved up by the scroll.
841    /// Every mapping between a screen point and a byte offset goes through it.
842    fn text_origin(&self) -> Option<Point<Pixels>> {
843        Some(self.last_bounds?.origin - self.scroll)
844    }
845
846    fn index_for_mouse_position(&self, position: Point<Pixels>, line_height: Pixels) -> usize {
847        if self.content.is_empty() || self.last_layout.is_empty() {
848            return 0;
849        }
850        let Some(origin) = self.text_origin() else {
851            return 0;
852        };
853        self.offset_at(position - origin, line_height)
854    }
855
856    /// The chip under a window point, if any.
857    fn chip_at(&self, position: Point<Pixels>, line_height: Pixels) -> Option<Range<usize>> {
858        let at = offset_for_position(
859            &self.last_layout,
860            position - self.text_origin()?,
861            line_height,
862        );
863        self.chips
864            .iter()
865            .map(|chip| chip.range.clone())
866            .find(|range| self.last_shown.range(range).contains(&at))
867    }
868
869    /// Where `offset` sits in the last frame, relative to the text origin.
870    fn position_of(&self, offset: usize, line_height: Pixels) -> Option<Point<Pixels>> {
871        position_for_offset(&self.last_layout, self.last_shown.at(offset), line_height)
872    }
873
874    /// The offset closest to a point relative to the text origin in the last
875    /// frame. A point on a chip lands on its nearer end.
876    fn offset_at(&self, position: Point<Pixels>, line_height: Pixels) -> usize {
877        self.last_shown.offset(offset_for_position(
878            &self.last_layout,
879            position,
880            line_height,
881        ))
882    }
883
884    /// Extend the selection to `offset`, or past the chip it falls inside in
885    /// the direction it moved.
886    fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
887        let offset = chip::outside(&self.chips, offset, offset < self.cursor_offset());
888        self.goal_x = None;
889        self.caret_moved();
890        if self.selection_reversed {
891            self.selected_range.start = offset
892        } else {
893            self.selected_range.end = offset
894        };
895        if self.selected_range.end < self.selected_range.start {
896            self.selection_reversed = !self.selection_reversed;
897            self.selected_range = self.selected_range.end..self.selected_range.start;
898        }
899        cx.emit(FieldEvent::Moved);
900        cx.notify()
901    }
902
903    fn offset_to_utf16(&self, offset: usize) -> usize {
904        offset_to_utf16(&self.content, offset)
905    }
906
907    fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
908        range_to_utf16(&self.content, range.clone())
909    }
910
911    fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
912        range_from_utf16(&self.content, range_utf16.clone())
913    }
914
915    fn previous_boundary(&self, offset: usize) -> usize {
916        previous_boundary(&self.content, offset)
917    }
918
919    fn next_boundary(&self, offset: usize) -> usize {
920        next_boundary(&self.content, offset)
921    }
922}
923
924impl Focusable for TextField {
925    fn focus_handle(&self, _: &App) -> FocusHandle {
926        self.focus_handle.clone()
927    }
928}