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