| 1 | //! A text input field that allows the user to enter text. |
| 2 | //! |
| 3 | //! Based on the `Input` example from the `gpui` crate. |
| 4 | //! https://github.com/zed-industries/zed/blob/main/crates/gpui/examples/input.rs |
| 5 | use gpui::TextAlign; |
| 6 | use gpui::{ |
| 7 | Action, App, AppContext, Bounds, ClipboardItem, Context, Edges, Entity, EntityInputHandler, |
| 8 | EventEmitter, FocusHandle, Focusable, InteractiveElement as _, IntoElement, KeyBinding, |
| 9 | MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point, |
| 10 | Render, ScrollHandle, ScrollWheelEvent, SharedString, Styled as _, Subscription, |
| 11 | UTF16Selection, Window, actions, div, point, prelude::FluentBuilder as _, px, |
| 12 | }; |
| 13 | use ropey::{Rope, RopeSlice}; |
| 14 | use serde::Deserialize; |
| 15 | use std::borrow::Cow; |
| 16 | use std::cell::Cell; |
| 17 | use std::ops::Range; |
| 18 | use std::rc::Rc; |
| 19 | use sum_tree::Bias; |
| 20 | use unicode_segmentation::*; |
| 21 | |
| 22 | use super::{ |
| 23 | DiagnosticSet, DisplayMap, InputContextMenuCapabilities, InputEditorStyle, |
| 24 | InputHighlighterFactory, MASK_CHAR, MaskPattern, NativeMenu, NumberStep, WrappingIndent, |
| 25 | blink_cursor::BlinkCursor, |
| 26 | change::Change, |
| 27 | cursor::{CursorSelection, Selections}, |
| 28 | element::{ |
| 29 | EditorScrollbar, EditorScrollbarSnapshot, LongestLineKey, TextElement, |
| 30 | clamp_horizontal_scroll_offset, |
| 31 | }, |
| 32 | kind::InputModeKind, |
| 33 | mask_pattern::normalize_number_input, |
| 34 | mode::LayoutMode, |
| 35 | undo_manager::{EditIntent, UndoManager}, |
| 36 | }; |
| 37 | use crate::actions::{SelectDown, SelectLeft, SelectRight, SelectUp}; |
| 38 | use crate::input::blink_cursor::CURSOR_WIDTH; |
| 39 | use crate::input::movement::MoveDirection; |
| 40 | use crate::input::{ |
| 41 | InputExtras as _, Position, RopeExt as _, element::RIGHT_MARGIN, layout::LastLayout, |
| 42 | }; |
| 43 | use crate::{AutoScroll, StepAction}; |
| 44 | |
| 45 | /// Vertical clearance to retain when revealing a text position. |
| 46 | pub(crate) enum ScrollPadding { |
| 47 | Minimal, |
| 48 | SurroundingLines, |
| 49 | } |
| 50 | |
| 51 | #[derive(Action, Clone, PartialEq, Eq, Deserialize)] |
| 52 | #[action(namespace = input, no_json)] |
| 53 | pub struct Enter { |
| 54 | /// Is confirm with secondary. |
| 55 | pub secondary: bool, |
| 56 | /// Whether the Shift modifier was held when Enter was pressed. |
| 57 | pub shift: bool, |
| 58 | } |
| 59 | |
| 60 | impl Enter { |
| 61 | /// Returns true if `action` is a primary `Enter` action (`secondary: false`), |
| 62 | /// regardless of whether Shift was held. |
| 63 | pub fn is_primary(action: &dyn Action) -> bool { |
| 64 | action.partial_eq(&Enter { |
| 65 | secondary: false, |
| 66 | shift: false, |
| 67 | }) || action.partial_eq(&Enter { |
| 68 | secondary: false, |
| 69 | shift: true, |
| 70 | }) |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | actions!( |
| 75 | input, |
| 76 | [ |
| 77 | ActivateToken, |
| 78 | Backspace, |
| 79 | Delete, |
| 80 | DeleteToBeginningOfLine, |
| 81 | DeleteToEndOfLine, |
| 82 | DeleteToPreviousWordStart, |
| 83 | DeleteToNextWordEnd, |
| 84 | Indent, |
| 85 | Outdent, |
| 86 | IndentInline, |
| 87 | OutdentInline, |
| 88 | MoveUp, |
| 89 | MoveDown, |
| 90 | MoveLeft, |
| 91 | MoveRight, |
| 92 | MoveHome, |
| 93 | MoveEnd, |
| 94 | MovePageUp, |
| 95 | MovePageDown, |
| 96 | AddCursorAbove, |
| 97 | AddCursorBelow, |
| 98 | SelectAll, |
| 99 | SelectToStartOfLine, |
| 100 | SelectToEndOfLine, |
| 101 | SelectToStart, |
| 102 | SelectToEnd, |
| 103 | SelectToPreviousWordStart, |
| 104 | SelectToNextWordEnd, |
| 105 | ShowCharacterPalette, |
| 106 | Copy, |
| 107 | Cut, |
| 108 | Paste, |
| 109 | Undo, |
| 110 | Redo, |
| 111 | MoveToStartOfLine, |
| 112 | MoveToEndOfLine, |
| 113 | MoveToStart, |
| 114 | MoveToEnd, |
| 115 | MoveToPreviousWord, |
| 116 | MoveToNextWord, |
| 117 | Escape, |
| 118 | ToggleCodeActions, |
| 119 | Search, |
| 120 | Replace, |
| 121 | GoToDefinition, |
| 122 | ] |
| 123 | ); |
| 124 | |
| 125 | #[derive(Clone)] |
| 126 | pub enum InputEvent { |
| 127 | Change, |
| 128 | PressEnter { secondary: bool, shift: bool }, |
| 129 | Focus, |
| 130 | Blur, |
| 131 | } |
| 132 | |
| 133 | pub(super) const CONTEXT: &str = "Input"; |
| 134 | |
| 135 | pub(crate) fn init(cx: &mut App) { |
| 136 | cx.bind_keys([ |
| 137 | KeyBinding::new("backspace", Backspace, Some(CONTEXT)), |
| 138 | KeyBinding::new("shift-backspace", Backspace, Some(CONTEXT)), |
| 139 | #[cfg(target_os = "macos")] |
| 140 | KeyBinding::new("ctrl-backspace", Backspace, Some(CONTEXT)), |
| 141 | KeyBinding::new("delete", Delete, Some(CONTEXT)), |
| 142 | KeyBinding::new("shift-delete", Delete, Some(CONTEXT)), |
| 143 | #[cfg(target_os = "macos")] |
| 144 | KeyBinding::new("cmd-backspace", DeleteToBeginningOfLine, Some(CONTEXT)), |
| 145 | #[cfg(target_os = "macos")] |
| 146 | KeyBinding::new("cmd-delete", DeleteToEndOfLine, Some(CONTEXT)), |
| 147 | #[cfg(target_os = "macos")] |
| 148 | KeyBinding::new("alt-backspace", DeleteToPreviousWordStart, Some(CONTEXT)), |
| 149 | #[cfg(not(target_os = "macos"))] |
| 150 | KeyBinding::new("ctrl-backspace", DeleteToPreviousWordStart, Some(CONTEXT)), |
| 151 | #[cfg(target_os = "macos")] |
| 152 | KeyBinding::new("alt-delete", DeleteToNextWordEnd, Some(CONTEXT)), |
| 153 | #[cfg(not(target_os = "macos"))] |
| 154 | KeyBinding::new("ctrl-delete", DeleteToNextWordEnd, Some(CONTEXT)), |
| 155 | KeyBinding::new( |
| 156 | "enter", |
| 157 | Enter { |
| 158 | secondary: false, |
| 159 | shift: false, |
| 160 | }, |
| 161 | Some(CONTEXT), |
| 162 | ), |
| 163 | KeyBinding::new( |
| 164 | "shift-enter", |
| 165 | Enter { |
| 166 | secondary: false, |
| 167 | shift: true, |
| 168 | }, |
| 169 | Some(CONTEXT), |
| 170 | ), |
| 171 | KeyBinding::new( |
| 172 | "secondary-enter", |
| 173 | Enter { |
| 174 | secondary: true, |
| 175 | shift: false, |
| 176 | }, |
| 177 | Some(CONTEXT), |
| 178 | ), |
| 179 | KeyBinding::new("escape", Escape, Some(CONTEXT)), |
| 180 | KeyBinding::new("up", MoveUp, Some(CONTEXT)), |
| 181 | KeyBinding::new("down", MoveDown, Some(CONTEXT)), |
| 182 | KeyBinding::new("left", MoveLeft, Some(CONTEXT)), |
| 183 | KeyBinding::new("right", MoveRight, Some(CONTEXT)), |
| 184 | KeyBinding::new("pageup", MovePageUp, Some(CONTEXT)), |
| 185 | KeyBinding::new("pagedown", MovePageDown, Some(CONTEXT)), |
| 186 | KeyBinding::new("tab", IndentInline, Some(CONTEXT)), |
| 187 | KeyBinding::new("shift-tab", OutdentInline, Some(CONTEXT)), |
| 188 | #[cfg(target_os = "macos")] |
| 189 | KeyBinding::new("cmd-]", Indent, Some(CONTEXT)), |
| 190 | #[cfg(not(target_os = "macos"))] |
| 191 | KeyBinding::new("ctrl-]", Indent, Some(CONTEXT)), |
| 192 | #[cfg(target_os = "macos")] |
| 193 | KeyBinding::new("cmd-[", Outdent, Some(CONTEXT)), |
| 194 | #[cfg(not(target_os = "macos"))] |
| 195 | KeyBinding::new("ctrl-[", Outdent, Some(CONTEXT)), |
| 196 | KeyBinding::new("shift-left", SelectLeft, Some(CONTEXT)), |
| 197 | KeyBinding::new("shift-right", SelectRight, Some(CONTEXT)), |
| 198 | KeyBinding::new("shift-up", SelectUp, Some(CONTEXT)), |
| 199 | KeyBinding::new("shift-down", SelectDown, Some(CONTEXT)), |
| 200 | #[cfg(not(any(target_os = "macos", target_os = "linux")))] |
| 201 | KeyBinding::new("shift-alt-left", SelectLeft, Some(CONTEXT)), |
| 202 | #[cfg(not(any(target_os = "macos", target_os = "linux")))] |
| 203 | KeyBinding::new("shift-alt-right", SelectRight, Some(CONTEXT)), |
| 204 | // Avoid Ctrl+Alt+arrows on Linux, where desktops may reserve them. |
| 205 | #[cfg(target_os = "macos")] |
| 206 | KeyBinding::new("cmd-alt-up", AddCursorAbove, Some(CONTEXT)), |
| 207 | #[cfg(target_os = "macos")] |
| 208 | KeyBinding::new("cmd-alt-down", AddCursorBelow, Some(CONTEXT)), |
| 209 | #[cfg(target_os = "windows")] |
| 210 | KeyBinding::new("ctrl-alt-up", AddCursorAbove, Some(CONTEXT)), |
| 211 | #[cfg(not(any(target_os = "macos", target_os = "windows")))] |
| 212 | KeyBinding::new("shift-alt-up", AddCursorAbove, Some(CONTEXT)), |
| 213 | #[cfg(target_os = "windows")] |
| 214 | KeyBinding::new("ctrl-alt-down", AddCursorBelow, Some(CONTEXT)), |
| 215 | #[cfg(not(any(target_os = "macos", target_os = "windows")))] |
| 216 | KeyBinding::new("shift-alt-down", AddCursorBelow, Some(CONTEXT)), |
| 217 | KeyBinding::new("home", MoveHome, Some(CONTEXT)), |
| 218 | KeyBinding::new("end", MoveEnd, Some(CONTEXT)), |
| 219 | #[cfg(not(target_os = "macos"))] |
| 220 | KeyBinding::new("ctrl-home", MoveToStart, Some(CONTEXT)), |
| 221 | #[cfg(not(target_os = "macos"))] |
| 222 | KeyBinding::new("ctrl-end", MoveToEnd, Some(CONTEXT)), |
| 223 | #[cfg(not(target_os = "macos"))] |
| 224 | KeyBinding::new("ctrl-shift-home", SelectToStart, Some(CONTEXT)), |
| 225 | #[cfg(not(target_os = "macos"))] |
| 226 | KeyBinding::new("ctrl-shift-end", SelectToEnd, Some(CONTEXT)), |
| 227 | KeyBinding::new("shift-home", SelectToStartOfLine, Some(CONTEXT)), |
| 228 | KeyBinding::new("shift-end", SelectToEndOfLine, Some(CONTEXT)), |
| 229 | #[cfg(target_os = "macos")] |
| 230 | KeyBinding::new("ctrl-shift-a", SelectToStartOfLine, Some(CONTEXT)), |
| 231 | #[cfg(target_os = "macos")] |
| 232 | KeyBinding::new("ctrl-shift-e", SelectToEndOfLine, Some(CONTEXT)), |
| 233 | #[cfg(target_os = "macos")] |
| 234 | KeyBinding::new("shift-cmd-left", SelectToStartOfLine, Some(CONTEXT)), |
| 235 | #[cfg(target_os = "macos")] |
| 236 | KeyBinding::new("shift-cmd-right", SelectToEndOfLine, Some(CONTEXT)), |
| 237 | #[cfg(any(target_os = "macos", target_os = "linux"))] |
| 238 | KeyBinding::new("alt-shift-left", SelectToPreviousWordStart, Some(CONTEXT)), |
| 239 | #[cfg(not(target_os = "macos"))] |
| 240 | KeyBinding::new("ctrl-shift-left", SelectToPreviousWordStart, Some(CONTEXT)), |
| 241 | #[cfg(any(target_os = "macos", target_os = "linux"))] |
| 242 | KeyBinding::new("alt-shift-right", SelectToNextWordEnd, Some(CONTEXT)), |
| 243 | #[cfg(not(target_os = "macos"))] |
| 244 | KeyBinding::new("ctrl-shift-right", SelectToNextWordEnd, Some(CONTEXT)), |
| 245 | #[cfg(target_os = "macos")] |
| 246 | KeyBinding::new("ctrl-cmd-space", ShowCharacterPalette, Some(CONTEXT)), |
| 247 | #[cfg(target_os = "macos")] |
| 248 | KeyBinding::new("cmd-a", SelectAll, Some(CONTEXT)), |
| 249 | #[cfg(not(target_os = "macos"))] |
| 250 | KeyBinding::new("ctrl-a", SelectAll, Some(CONTEXT)), |
| 251 | #[cfg(target_os = "macos")] |
| 252 | KeyBinding::new("cmd-c", Copy, Some(CONTEXT)), |
| 253 | #[cfg(not(target_os = "macos"))] |
| 254 | KeyBinding::new("ctrl-c", Copy, Some(CONTEXT)), |
| 255 | #[cfg(target_os = "macos")] |
| 256 | KeyBinding::new("cmd-x", Cut, Some(CONTEXT)), |
| 257 | #[cfg(not(target_os = "macos"))] |
| 258 | KeyBinding::new("ctrl-x", Cut, Some(CONTEXT)), |
| 259 | #[cfg(target_os = "macos")] |
| 260 | KeyBinding::new("cmd-v", Paste, Some(CONTEXT)), |
| 261 | #[cfg(not(target_os = "macos"))] |
| 262 | KeyBinding::new("ctrl-v", Paste, Some(CONTEXT)), |
| 263 | #[cfg(target_os = "macos")] |
| 264 | KeyBinding::new("ctrl-a", MoveHome, Some(CONTEXT)), |
| 265 | #[cfg(target_os = "macos")] |
| 266 | KeyBinding::new("cmd-left", MoveHome, Some(CONTEXT)), |
| 267 | #[cfg(target_os = "macos")] |
| 268 | KeyBinding::new("ctrl-e", MoveEnd, Some(CONTEXT)), |
| 269 | #[cfg(target_os = "macos")] |
| 270 | KeyBinding::new("cmd-right", MoveEnd, Some(CONTEXT)), |
| 271 | #[cfg(target_os = "macos")] |
| 272 | KeyBinding::new("cmd-z", Undo, Some(CONTEXT)), |
| 273 | #[cfg(target_os = "macos")] |
| 274 | KeyBinding::new("cmd-shift-z", Redo, Some(CONTEXT)), |
| 275 | #[cfg(target_os = "macos")] |
| 276 | KeyBinding::new("cmd-up", MoveToStart, Some(CONTEXT)), |
| 277 | #[cfg(target_os = "macos")] |
| 278 | KeyBinding::new("cmd-down", MoveToEnd, Some(CONTEXT)), |
| 279 | #[cfg(target_os = "macos")] |
| 280 | KeyBinding::new("alt-left", MoveToPreviousWord, Some(CONTEXT)), |
| 281 | #[cfg(target_os = "macos")] |
| 282 | KeyBinding::new("alt-right", MoveToNextWord, Some(CONTEXT)), |
| 283 | #[cfg(not(target_os = "macos"))] |
| 284 | KeyBinding::new("ctrl-left", MoveToPreviousWord, Some(CONTEXT)), |
| 285 | #[cfg(not(target_os = "macos"))] |
| 286 | KeyBinding::new("ctrl-right", MoveToNextWord, Some(CONTEXT)), |
| 287 | #[cfg(target_os = "macos")] |
| 288 | KeyBinding::new("cmd-shift-up", SelectToStart, Some(CONTEXT)), |
| 289 | #[cfg(target_os = "macos")] |
| 290 | KeyBinding::new("cmd-shift-down", SelectToEnd, Some(CONTEXT)), |
| 291 | #[cfg(not(target_os = "macos"))] |
| 292 | KeyBinding::new("ctrl-z", Undo, Some(CONTEXT)), |
| 293 | #[cfg(not(target_os = "macos"))] |
| 294 | KeyBinding::new("ctrl-y", Redo, Some(CONTEXT)), |
| 295 | #[cfg(target_os = "macos")] |
| 296 | KeyBinding::new("cmd-.", ToggleCodeActions, Some(CONTEXT)), |
| 297 | #[cfg(not(target_os = "macos"))] |
| 298 | KeyBinding::new("ctrl-.", ToggleCodeActions, Some(CONTEXT)), |
| 299 | #[cfg(target_os = "macos")] |
| 300 | KeyBinding::new("cmd-f", Search, Some(CONTEXT)), |
| 301 | #[cfg(not(target_os = "macos"))] |
| 302 | KeyBinding::new("ctrl-f", Search, Some(CONTEXT)), |
| 303 | #[cfg(target_os = "macos")] |
| 304 | KeyBinding::new("cmd-shift-f", Replace, Some(CONTEXT)), |
| 305 | #[cfg(not(target_os = "macos"))] |
| 306 | KeyBinding::new("ctrl-h", Replace, Some(CONTEXT)), |
| 307 | ]); |
| 308 | } |
| 309 | |
| 310 | /// A mouse position resolved for a columnar (block) selection. |
| 311 | /// |
| 312 | /// A position past the end of a short row has no glyph to land on, so `offset` clips to |
| 313 | /// that row's end and `columns_past_line_end` keeps what the clip dropped. Together they |
| 314 | /// say which column the pointer really reached, which is what a block spanning rows of |
| 315 | /// different lengths has to be measured in. |
| 316 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 317 | pub(super) struct ColumnarPoint { |
| 318 | offset: usize, |
| 319 | columns_past_line_end: usize, |
| 320 | } |
| 321 | |
| 322 | impl ColumnarPoint { |
| 323 | pub(super) fn new(offset: usize, columns_past_line_end: usize) -> Self { |
| 324 | Self { |
| 325 | offset, |
| 326 | columns_past_line_end, |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | /// The document and selections a paste was asked to replace, taken when the |
| 332 | /// `Paste` action ran so a clipboard read that resolves later can tell |
| 333 | /// whether it still applies. See [`InputBaseState::paste_target`]. |
| 334 | #[derive(Debug, PartialEq)] |
| 335 | struct PasteTarget { |
| 336 | document_revision: u64, |
| 337 | selections: Vec<CursorSelection>, |
| 338 | } |
| 339 | |
| 340 | /// The shared text-editing engine behind [`crate::input::InputState`], |
| 341 | /// [`crate::input::TextareaState`] and [`crate::input::EditorState`]. |
| 342 | /// |
| 343 | /// `M` is the mode marker: it carries no data and only decides which methods |
| 344 | /// exist, so an ordinary input cannot reach the editor's language features. |
| 345 | /// |
| 346 | /// The three states are type aliases of this one, which is why this name is |
| 347 | /// public: an alias is only as usable as the type behind it, so hiding this |
| 348 | /// would leave `InputState` unable to do anything. Prefer naming the aliases |
| 349 | /// — write `InputState`, not `InputBaseState<InputMode>`. |
| 350 | pub struct InputBaseState<M: InputModeKind> { |
| 351 | /// State only this mode needs. See [`InputModeKind::Extras`]. |
| 352 | pub(crate) extras: M::Extras, |
| 353 | pub(super) focus_handle: FocusHandle, |
| 354 | pub(super) mode: LayoutMode, |
| 355 | pub(super) text: Rope, |
| 356 | pub(super) display_map: DisplayMap, |
| 357 | pub(super) undo_manager: UndoManager, |
| 358 | pub(super) inline_tokens: Option<Box<super::inline_tokens::InlineTokenStore>>, |
| 359 | pub(super) pending_token: Option<super::InlineToken>, |
| 360 | pub(super) replaying_history: bool, |
| 361 | pub(super) validated_token_edit: bool, |
| 362 | pub(super) document_revision: u64, |
| 363 | pub(super) token_presentation: super::InlineTokenPresentation, |
| 364 | pub(super) token_layout_cache: Option<Box<super::token_presentation::TokenLayoutCache>>, |
| 365 | /// Real per-frame bounds of the placed token elements, keyed by token |
| 366 | /// start offset; used for hover payloads and stale-hover reconciliation. |
| 367 | pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>, |
| 368 | /// The currently hovered token: its entered span, last measured bounds, |
| 369 | /// and UTF-16 range as of entry. Retained so hover exit can still be |
| 370 | /// delivered when the token is removed, replaced, scrolled out, or |
| 371 | /// disabled. |
| 372 | pub(super) hovered_token: Option<super::token_presentation::HoverSnapshot>, |
| 373 | pub(super) pending_token_hover_exits: Vec<super::token_presentation::HoverSnapshot>, |
| 374 | /// The start offset of a pressed token, with the document revision and |
| 375 | /// pointer position at the press. |
| 376 | pub(super) pressed_token: Option<(usize, u64, Point<Pixels>)>, |
| 377 | pub(super) search_session: super::SearchSession, |
| 378 | /// Advances every time search is explicitly invoked. See |
| 379 | /// [`InputBaseState::search_activation_revision`]. |
| 380 | pub(super) search_activation_revision: u64, |
| 381 | pub(super) searchable: bool, |
| 382 | pub(super) replaceable: bool, |
| 383 | pub(super) soft_wrap: bool, |
| 384 | pub(super) wrapping_indent: WrappingIndent, |
| 385 | pub(super) scroll_beyond_last_line: Option<usize>, |
| 386 | pub(super) cursor_surrounding_lines: Option<usize>, |
| 387 | pub(super) blink_cursor: Entity<BlinkCursor>, |
| 388 | pub(super) loading: bool, |
| 389 | /// The cursors and selections. |
| 390 | /// |
| 391 | /// Always contains at least one selection where index 0 is the active cursor. |
| 392 | pub(super) selections: Selections, |
| 393 | /// Range for save the selected word, use to keep word range when drag move. |
| 394 | pub(super) selected_word_range: Option<CursorSelection>, |
| 395 | /// The marked range is the temporary insert text on IME typing. |
| 396 | pub(super) ime_marked_range: Option<CursorSelection>, |
| 397 | pub(super) last_layout: Option<LastLayout>, |
| 398 | pub(super) last_cursor: Option<usize>, |
| 399 | /// The input container bounds |
| 400 | pub(super) input_bounds: Bounds<Pixels>, |
| 401 | /// The text bounds |
| 402 | pub(super) last_bounds: Option<Bounds<Pixels>>, |
| 403 | pub(super) last_selected_range: Option<CursorSelection>, |
| 404 | pub(super) selecting: bool, |
| 405 | /// Anchor point of an in-progress columnar (block) selection. |
| 406 | pub(super) column_select_start: Option<ColumnarPoint>, |
| 407 | /// The selection a long press made, with its handles and edit menu. |
| 408 | pub(super) touch_selection: super::touch::TouchSelection, |
| 409 | pub(crate) disabled: bool, |
| 410 | pub(crate) readonly: bool, |
| 411 | pub(crate) text_align: TextAlign, |
| 412 | pub(super) masked: bool, |
| 413 | pub(super) clean_on_escape: bool, |
| 414 | pub(super) submit_on_enter: bool, |
| 415 | pub(super) show_whitespaces: bool, |
| 416 | /// This flag tells the renderer to prefer the end of the current visual line. |
| 417 | pub(crate) cursor_line_end_affinity: bool, |
| 418 | pub(super) pattern: Option<regex::Regex>, |
| 419 | pub(super) validate: Option<Box<dyn Fn(&str, &mut App) -> bool + 'static>>, |
| 420 | /// The step strategy for [`super::NumberInput`] to increment/decrement. |
| 421 | /// See [`Self::step`] and [`Self::step_by`]. |
| 422 | pub(crate) number_step: Option<NumberStep>, |
| 423 | /// The minimum value for [`super::NumberInput`]. See [`Self::min`]. |
| 424 | pub(crate) number_min: Option<f64>, |
| 425 | /// The maximum value for [`super::NumberInput`]. See [`Self::max`]. |
| 426 | pub(crate) number_max: Option<f64>, |
| 427 | pub(crate) scroll_handle: ScrollHandle, |
| 428 | /// The deferred scroll offset to apply on next layout. |
| 429 | pub(crate) deferred_scroll_offset: Option<Point<Pixels>>, |
| 430 | /// The size of the scrollable content. |
| 431 | pub(crate) scroll_size: gpui::Size<Pixels>, |
| 432 | pub(super) editor_scrollbar_snapshot: Cell<Option<EditorScrollbarSnapshot>>, |
| 433 | /// The unwrapped width of the longest line and what it was measured for. |
| 434 | pub(super) longest_line_width: Cell<Option<(LongestLineKey, Pixels)>>, |
| 435 | pub(super) editor_paddings: Edges<Pixels>, |
| 436 | /// The style this state paints with: what was projected onto it, with |
| 437 | /// every colour left unset resolved from the palette that is current. It |
| 438 | /// is rebuilt at the top of every render, which is what keeps it current |
| 439 | /// when the palette changes after the state was built. |
| 440 | pub(super) editor_style: InputEditorStyle, |
| 441 | /// What a consumer projected, kept verbatim so that resolution never |
| 442 | /// consumes its own output: resolving in place would fill the unset |
| 443 | /// colours once and then never see them as unset again, which is the same |
| 444 | /// freeze in a different place. |
| 445 | projected_editor_style: InputEditorStyle, |
| 446 | |
| 447 | /// The mask pattern for formatting the input text |
| 448 | pub(crate) mask_pattern: MaskPattern, |
| 449 | /// Whether the `mask_pattern` was explicitly set (via [`Self::mask_pattern`] |
| 450 | /// or [`Self::set_mask_pattern`]), to let [`super::NumberInput`] only apply |
| 451 | /// its default mask when the user has not made an explicit choice. |
| 452 | pub(super) mask_pattern_set: bool, |
| 453 | pub(super) placeholder: SharedString, |
| 454 | |
| 455 | /// Diagnostic currently requested by pointer hover; applications render it. |
| 456 | pub(super) diagnostic_popover: Option<Rc<crate::input::DiagnosticEntry>>, |
| 457 | |
| 458 | context_menu_handler: Option< |
| 459 | Rc<dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App)>, |
| 460 | >, |
| 461 | pending_context_menu: Option<(Point<Pixels>, usize)>, |
| 462 | |
| 463 | /// Whether the context menu that shows on right-click is enabled. |
| 464 | /// |
| 465 | pub(super) enable_context_menu: bool, |
| 466 | |
| 467 | /// A flag to indicate if we are currently inserting a completion item. |
| 468 | pub(super) completion_inserting: bool, |
| 469 | pub(super) overlay_action_handler: Option< |
| 470 | Rc< |
| 471 | dyn Fn( |
| 472 | super::InputOverlayKind, |
| 473 | Box<dyn Action>, |
| 474 | &mut Window, |
| 475 | &mut Context<InputBaseState<M>>, |
| 476 | ) -> bool, |
| 477 | >, |
| 478 | >, |
| 479 | |
| 480 | /// A flag to indicate if we have a pending update to the text. |
| 481 | /// |
| 482 | /// If true, will call some update (for example LSP, Syntax Highlight) before render. |
| 483 | _pending_update: bool, |
| 484 | /// A flag to indicate if we should ignore the next completion event. |
| 485 | pub(super) silent_replace_text: bool, |
| 486 | /// A flag to indicate if we should emit InputEvents. |
| 487 | pub(super) emit_events: bool, |
| 488 | |
| 489 | _subscriptions: Vec<Subscription>, |
| 490 | |
| 491 | pub(super) auto_scroll: AutoScroll, |
| 492 | } |
| 493 | |
| 494 | /// Read-only styling data exposed to presentation facades. |
| 495 | /// |
| 496 | /// The fields are private and read through the methods below, so that a new |
| 497 | /// one can be added without breaking the facades. |
| 498 | #[derive(Clone)] |
| 499 | pub struct InputPresentation { |
| 500 | focus_handle: FocusHandle, |
| 501 | disabled: bool, |
| 502 | readonly: bool, |
| 503 | loading: bool, |
| 504 | masked: bool, |
| 505 | multi_line: bool, |
| 506 | code_editor: bool, |
| 507 | text_align: TextAlign, |
| 508 | placeholder: SharedString, |
| 509 | mask_placeholder: Option<String>, |
| 510 | } |
| 511 | |
| 512 | impl InputPresentation { |
| 513 | pub fn focus_handle(&self) -> &FocusHandle { |
| 514 | &self.focus_handle |
| 515 | } |
| 516 | |
| 517 | pub fn is_disabled(&self) -> bool { |
| 518 | self.disabled |
| 519 | } |
| 520 | |
| 521 | pub fn is_readonly(&self) -> bool { |
| 522 | self.readonly |
| 523 | } |
| 524 | |
| 525 | /// Returns true if the user is allowed to change the text. |
| 526 | /// |
| 527 | /// See also: [`InputBaseState::is_editable`]. |
| 528 | pub fn is_editable(&self) -> bool { |
| 529 | !self.disabled && !self.readonly |
| 530 | } |
| 531 | |
| 532 | pub fn is_loading(&self) -> bool { |
| 533 | self.loading |
| 534 | } |
| 535 | |
| 536 | pub fn is_masked(&self) -> bool { |
| 537 | self.masked |
| 538 | } |
| 539 | |
| 540 | pub fn is_multi_line(&self) -> bool { |
| 541 | self.multi_line |
| 542 | } |
| 543 | |
| 544 | pub fn is_code_editor(&self) -> bool { |
| 545 | self.code_editor |
| 546 | } |
| 547 | |
| 548 | pub fn text_align(&self) -> TextAlign { |
| 549 | self.text_align |
| 550 | } |
| 551 | |
| 552 | pub fn placeholder(&self) -> &SharedString { |
| 553 | &self.placeholder |
| 554 | } |
| 555 | |
| 556 | /// The placeholder derived from the mask pattern, e.g.: `(___) ___-____`. |
| 557 | pub fn mask_placeholder(&self) -> Option<&str> { |
| 558 | self.mask_placeholder.as_deref() |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | impl<M: InputModeKind> EventEmitter<InputEvent> for InputBaseState<M> {} |
| 563 | |
| 564 | impl<M: InputModeKind> InputBaseState<M> { |
| 565 | #[doc(hidden)] |
| 566 | pub fn cursor_layout(&self) -> Option<(Bounds<Pixels>, Pixels)> { |
| 567 | let layout = self.last_layout.as_ref()?; |
| 568 | Some((layout.cursor_bounds?, layout.line_height)) |
| 569 | } |
| 570 | |
| 571 | pub fn input_bounds(&self) -> Bounds<Pixels> { |
| 572 | self.input_bounds |
| 573 | } |
| 574 | |
| 575 | pub fn text_bounds(&self) -> Option<Bounds<Pixels>> { |
| 576 | self.last_bounds |
| 577 | } |
| 578 | |
| 579 | pub fn diagnostic_popover(&self) -> Option<Rc<crate::input::DiagnosticEntry>> { |
| 580 | self.diagnostic_popover.clone() |
| 581 | } |
| 582 | |
| 583 | pub fn presentation(&self) -> InputPresentation { |
| 584 | InputPresentation { |
| 585 | focus_handle: self.focus_handle.clone(), |
| 586 | disabled: self.disabled, |
| 587 | readonly: self.readonly, |
| 588 | loading: self.loading, |
| 589 | masked: self.masked, |
| 590 | multi_line: self.is_multi_line(), |
| 591 | code_editor: self.is_code_editor(), |
| 592 | text_align: self.text_align, |
| 593 | placeholder: self.placeholder.clone(), |
| 594 | mask_placeholder: self.mask_pattern.placeholder(), |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | /// Whether this input spans more than one line. |
| 599 | /// |
| 600 | /// Answered by the mode marker, which is fixed when the state is built. |
| 601 | /// [`LayoutMode`] holds the row counts and growth policy, not the kind. |
| 602 | #[inline] |
| 603 | /// Whether this input paints scrollbars. |
| 604 | /// |
| 605 | /// Only a multi-line input can scroll: a single-line input keeps its |
| 606 | /// caret in view by moving its own offset, and never has a viewport a |
| 607 | /// user could drag. Adding the editor scrollbar to every input put a |
| 608 | /// thumb inside every text field, which is a control the field does not |
| 609 | /// have. |
| 610 | pub(crate) fn shows_scrollbar(&self) -> bool { |
| 611 | self.is_multi_line() |
| 612 | } |
| 613 | |
| 614 | pub fn is_multi_line(&self) -> bool { |
| 615 | M::MULTI_LINE |
| 616 | } |
| 617 | |
| 618 | /// Whether this input is a single-line text field. See [`Self::is_multi_line`]. |
| 619 | #[inline] |
| 620 | pub fn is_single_line(&self) -> bool { |
| 621 | !M::MULTI_LINE |
| 622 | } |
| 623 | |
| 624 | /// Whether this input is a source-code editor. |
| 625 | #[inline] |
| 626 | pub fn is_code_editor(&self) -> bool { |
| 627 | M::CODE_EDITOR |
| 628 | } |
| 629 | |
| 630 | /// Whether the user is allowed to copy the selection out. |
| 631 | /// |
| 632 | /// A masked input keeps its value out of the clipboard. |
| 633 | pub fn is_copyable(&self) -> bool { |
| 634 | self.selections.iter().any(|sel| !sel.is_empty()) && !self.masked |
| 635 | } |
| 636 | |
| 637 | pub fn context_menu_capabilities(&self) -> InputContextMenuCapabilities { |
| 638 | let (go_to_definition, code_actions) = self.extras.context_menu_capabilities(); |
| 639 | InputContextMenuCapabilities::new() |
| 640 | .disabled(self.disabled) |
| 641 | .readonly(self.readonly) |
| 642 | .code_editor(self.is_code_editor()) |
| 643 | .selection(!self.active_selection().is_empty()) |
| 644 | .masked(self.masked) |
| 645 | .go_to_definition(go_to_definition) |
| 646 | .code_actions(code_actions) |
| 647 | } |
| 648 | |
| 649 | pub fn set_text_align(&mut self, text_align: TextAlign, cx: &mut Context<Self>) { |
| 650 | if !self.is_single_line() || self.text_align == text_align { |
| 651 | return; |
| 652 | } |
| 653 | |
| 654 | self.text_align = text_align; |
| 655 | cx.notify(); |
| 656 | } |
| 657 | |
| 658 | /// Flip the password mask. |
| 659 | /// |
| 660 | /// Setting the mask is a single-line method, but flipping it stays here: |
| 661 | /// the reveal button is rendered from the generic path, and it can only be |
| 662 | /// switched on through [`crate::input::InputState`] anyway. |
| 663 | pub fn toggle_masked(&mut self, _: &mut Window, cx: &mut Context<Self>) { |
| 664 | self.masked = !self.masked; |
| 665 | cx.notify(); |
| 666 | } |
| 667 | |
| 668 | pub fn on_context_menu( |
| 669 | &mut self, |
| 670 | handler: Rc< |
| 671 | dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App), |
| 672 | >, |
| 673 | ) { |
| 674 | self.context_menu_handler = Some(handler); |
| 675 | } |
| 676 | |
| 677 | /// Build the engine. Each mode's own `new` sets its layout on top of this. |
| 678 | fn new_in_mode(window: &mut Window, cx: &mut Context<Self>) -> Self { |
| 679 | let focus_handle = cx.focus_handle().tab_stop(true); |
| 680 | let blink_cursor = cx.new(|_| BlinkCursor::new()); |
| 681 | let undo_manager = UndoManager::new(); |
| 682 | |
| 683 | let _subscriptions = vec![ |
| 684 | // Key bindings can consume events before on_key_down. Observe input |
| 685 | // before action dispatch so every keystroke resets the blink delay. |
| 686 | cx.intercept_keystrokes({ |
| 687 | let focus_handle = focus_handle.clone(); |
| 688 | let blink_cursor = blink_cursor.downgrade(); |
| 689 | move |_, window, cx| { |
| 690 | if focus_handle.is_focused(window) { |
| 691 | _ = blink_cursor.update(cx, |cursor, cx| cursor.pause(cx)); |
| 692 | } |
| 693 | } |
| 694 | }), |
| 695 | // Observe the blink cursor to repaint the view when it changes. |
| 696 | cx.observe(&blink_cursor, |_, _, cx| cx.notify()), |
| 697 | // Blink the cursor when the window is active, pause when it's not. |
| 698 | cx.observe_window_activation(window, |input, window, cx| { |
| 699 | if window.is_window_active() { |
| 700 | let focus_handle = input.focus_handle.clone(); |
| 701 | if focus_handle.is_focused(window) { |
| 702 | input.blink_cursor.update(cx, |blink_cursor, cx| { |
| 703 | blink_cursor.start(cx); |
| 704 | }); |
| 705 | } |
| 706 | } |
| 707 | }), |
| 708 | cx.on_focus(&focus_handle, window, Self::on_focus), |
| 709 | cx.on_blur(&focus_handle, window, Self::on_blur), |
| 710 | ]; |
| 711 | |
| 712 | let text_style = window.text_style(); |
| 713 | |
| 714 | Self { |
| 715 | extras: M::Extras::default(), |
| 716 | focus_handle: focus_handle.clone(), |
| 717 | text: "".into(), |
| 718 | display_map: DisplayMap::new(text_style.font(), window.rem_size(), None), |
| 719 | search_session: super::SearchSession::default(), |
| 720 | search_activation_revision: 0, |
| 721 | searchable: false, |
| 722 | replaceable: true, |
| 723 | soft_wrap: true, |
| 724 | wrapping_indent: WrappingIndent::default(), |
| 725 | scroll_beyond_last_line: None, |
| 726 | cursor_surrounding_lines: None, |
| 727 | blink_cursor, |
| 728 | undo_manager, |
| 729 | inline_tokens: None, |
| 730 | pending_token: None, |
| 731 | replaying_history: false, |
| 732 | validated_token_edit: false, |
| 733 | document_revision: 0, |
| 734 | token_presentation: Default::default(), |
| 735 | token_bounds: Default::default(), |
| 736 | hovered_token: None, |
| 737 | pending_token_hover_exits: Vec::new(), |
| 738 | token_layout_cache: None, |
| 739 | pressed_token: None, |
| 740 | selections: Selections::default(), |
| 741 | selected_word_range: None, |
| 742 | ime_marked_range: None, |
| 743 | input_bounds: Bounds::default(), |
| 744 | selecting: false, |
| 745 | touch_selection: Default::default(), |
| 746 | disabled: false, |
| 747 | readonly: false, |
| 748 | text_align: TextAlign::Left, |
| 749 | masked: false, |
| 750 | clean_on_escape: false, |
| 751 | submit_on_enter: false, |
| 752 | show_whitespaces: false, |
| 753 | loading: false, |
| 754 | pattern: None, |
| 755 | validate: None, |
| 756 | number_step: Some(NumberStep::Fixed(1.)), |
| 757 | number_min: None, |
| 758 | number_max: None, |
| 759 | mode: LayoutMode::default(), |
| 760 | last_layout: None, |
| 761 | last_bounds: None, |
| 762 | last_selected_range: None, |
| 763 | column_select_start: None, |
| 764 | last_cursor: None, |
| 765 | scroll_handle: ScrollHandle::new(), |
| 766 | scroll_size: gpui::size(px(0.), px(0.)), |
| 767 | editor_scrollbar_snapshot: Cell::new(None), |
| 768 | longest_line_width: Cell::new(None), |
| 769 | editor_paddings: Edges::default(), |
| 770 | deferred_scroll_offset: None, |
| 771 | placeholder: SharedString::default(), |
| 772 | mask_pattern: MaskPattern::default(), |
| 773 | mask_pattern_set: false, |
| 774 | editor_style: InputEditorStyle::default(), |
| 775 | projected_editor_style: InputEditorStyle::default(), |
| 776 | diagnostic_popover: None, |
| 777 | context_menu_handler: None, |
| 778 | pending_context_menu: None, |
| 779 | enable_context_menu: true, |
| 780 | completion_inserting: false, |
| 781 | overlay_action_handler: None, |
| 782 | silent_replace_text: false, |
| 783 | emit_events: true, |
| 784 | _subscriptions, |
| 785 | _pending_update: false, |
| 786 | cursor_line_end_affinity: false, |
| 787 | auto_scroll: AutoScroll::default(), |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | /// Sets whether the context menu that shows on right-click is enabled. |
| 792 | /// |
| 793 | /// The context menu is enabled by default. Disabling it turns off the |
| 794 | /// right-click menu entirely, including a custom menu set on the element. |
| 795 | /// A custom menu already replaces the built-in one, so keep this enabled |
| 796 | /// to show only your own items. |
| 797 | pub fn context_menu(mut self, enable: bool) -> Self { |
| 798 | self.enable_context_menu = enable; |
| 799 | self |
| 800 | } |
| 801 | |
| 802 | pub fn set_context_menu_enabled(&mut self, enabled: bool) { |
| 803 | self.enable_context_menu = enabled; |
| 804 | } |
| 805 | |
| 806 | /// Set whether search UI allows replacement, default is true. |
| 807 | #[doc(hidden)] |
| 808 | pub fn replaceable(mut self, allow: bool) -> Self { |
| 809 | self.replaceable = allow; |
| 810 | self |
| 811 | } |
| 812 | |
| 813 | /// Set placeholder |
| 814 | pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self { |
| 815 | self.placeholder = placeholder.into(); |
| 816 | self |
| 817 | } |
| 818 | |
| 819 | /// Set highlighter language for for [`LayoutMode::CodeEditor`] mode. |
| 820 | pub fn set_highlighter( |
| 821 | &mut self, |
| 822 | new_language: impl Into<SharedString>, |
| 823 | cx: &mut Context<Self>, |
| 824 | ) { |
| 825 | match &mut self.mode { |
| 826 | LayoutMode::CodeEditor { |
| 827 | language, |
| 828 | highlighter, |
| 829 | .. |
| 830 | } => { |
| 831 | language.set_name(new_language.into()); |
| 832 | *highlighter.borrow_mut() = None; |
| 833 | } |
| 834 | _ => {} |
| 835 | } |
| 836 | self.refresh(cx); |
| 837 | } |
| 838 | |
| 839 | fn reset_highlighter(&mut self, cx: &mut Context<Self>) { |
| 840 | match &mut self.mode { |
| 841 | LayoutMode::CodeEditor { highlighter, .. } => { |
| 842 | *highlighter.borrow_mut() = None; |
| 843 | } |
| 844 | _ => {} |
| 845 | } |
| 846 | cx.notify(); |
| 847 | } |
| 848 | |
| 849 | /// Install the parser/highlighter adapter used by code-editor mode. |
| 850 | pub fn set_highlighter_factory( |
| 851 | &mut self, |
| 852 | factory: InputHighlighterFactory, |
| 853 | cx: &mut Context<Self>, |
| 854 | ) { |
| 855 | self.mode.set_highlighter_factory(factory); |
| 856 | self._pending_update = true; |
| 857 | self.token_layout_cache = None; |
| 858 | cx.notify(); |
| 859 | } |
| 860 | |
| 861 | /// Install a default adapter without replacing an application-provided one. |
| 862 | pub fn ensure_highlighter_factory(&mut self, factory: InputHighlighterFactory) { |
| 863 | self.mode.ensure_highlighter_factory(factory); |
| 864 | } |
| 865 | |
| 866 | pub fn set_editor_style(&mut self, style: InputEditorStyle) { |
| 867 | self.editor_style = style.clone(); |
| 868 | self.projected_editor_style = style; |
| 869 | } |
| 870 | |
| 871 | /// Set presentation padding for multi-line text and its scrollbar layout. |
| 872 | #[doc(hidden)] |
| 873 | pub fn set_editor_paddings(&mut self, paddings: Edges<Pixels>) { |
| 874 | self.editor_paddings = paddings; |
| 875 | } |
| 876 | |
| 877 | pub fn apply_highlighter_fold_candidates( |
| 878 | &mut self, |
| 879 | candidates: Vec<crate::input::FoldRange>, |
| 880 | cx: &mut Context<Self>, |
| 881 | ) { |
| 882 | if self.mode.is_folding() { |
| 883 | self.display_map.set_fold_candidates(candidates); |
| 884 | } |
| 885 | cx.notify(); |
| 886 | } |
| 887 | |
| 888 | #[inline] |
| 889 | pub fn diagnostics(&self) -> Option<&DiagnosticSet> { |
| 890 | self.mode.diagnostics() |
| 891 | } |
| 892 | |
| 893 | #[inline] |
| 894 | pub fn diagnostics_mut(&mut self) -> Option<&mut DiagnosticSet> { |
| 895 | self.mode.diagnostics_mut() |
| 896 | } |
| 897 | |
| 898 | /// Set placeholder |
| 899 | pub fn set_placeholder( |
| 900 | &mut self, |
| 901 | placeholder: impl Into<SharedString>, |
| 902 | _: &mut Window, |
| 903 | cx: &mut Context<Self>, |
| 904 | ) { |
| 905 | self.placeholder = placeholder.into(); |
| 906 | cx.notify(); |
| 907 | } |
| 908 | |
| 909 | /// Find which line and sub-line the given offset belongs to, along with the position within that sub-line. |
| 910 | /// |
| 911 | /// Returns: |
| 912 | /// |
| 913 | /// - The index of the line (zero-based) containing the offset. |
| 914 | /// - The index of the sub-line (zero-based) within the line containing the offset. |
| 915 | /// - The position of the offset. |
| 916 | pub(super) fn line_and_position_for_offset( |
| 917 | &self, |
| 918 | offset: usize, |
| 919 | ) -> (usize, usize, Option<Point<Pixels>>) { |
| 920 | let Some(last_layout) = &self.last_layout else { |
| 921 | return (0, 0, None); |
| 922 | }; |
| 923 | let line_height = last_layout.line_height; |
| 924 | |
| 925 | let mut y_offset = last_layout.visible_top; |
| 926 | for (vi, line) in last_layout.lines.iter().enumerate() { |
| 927 | let prev_lines_offset = last_layout.visible_line_byte_offsets[vi]; |
| 928 | let local_offset = offset.saturating_sub(prev_lines_offset); |
| 929 | if let Some(pos) = line.position_for_index(local_offset, last_layout, false) { |
| 930 | let sub_line_index = line.row_at_y(pos.y, line_height).unwrap_or(0); |
| 931 | let adjusted_pos = point(pos.x + last_layout.line_number_width, pos.y + y_offset); |
| 932 | return (vi, sub_line_index, Some(adjusted_pos)); |
| 933 | } |
| 934 | |
| 935 | y_offset += line.size(line_height).height; |
| 936 | } |
| 937 | (0, 0, None) |
| 938 | } |
| 939 | |
| 940 | /// Set the value of the input field: plain text, or [`InputContent`] to |
| 941 | /// restore text together with its inline tokens. Editing history is |
| 942 | /// cleared and no [`InputEvent::Change`] is emitted. |
| 943 | /// |
| 944 | /// For single-line inputs the caret is placed at the end of the text while |
| 945 | /// the view is scrolled back to the start, so a long value shows its |
| 946 | /// beginning instead of its tail (matching HTML `<input>`). Multi-line |
| 947 | /// inputs reset the selection to `0..0`. |
| 948 | pub fn set_value( |
| 949 | &mut self, |
| 950 | value: impl Into<super::InputContent>, |
| 951 | window: &mut Window, |
| 952 | cx: &mut Context<Self>, |
| 953 | ) { |
| 954 | let content = value.into(); |
| 955 | self.inline_tokens = None; |
| 956 | self.undo_manager.set_ignoring(true); |
| 957 | self.emit_events = false; |
| 958 | self.replace_text(content.text().clone(), window, cx); |
| 959 | self.install_tokens(content); |
| 960 | self.undo_manager.set_ignoring(false); |
| 961 | self.emit_events = true; |
| 962 | |
| 963 | self.reset_selection(); |
| 964 | self.reset_lsp_state(); |
| 965 | self.reset_scroll_to_start(); |
| 966 | |
| 967 | self.undo_manager.clear(); |
| 968 | cx.notify(); |
| 969 | } |
| 970 | |
| 971 | /// Replace the entire text content while preserving undo history. |
| 972 | /// |
| 973 | /// Unlike [`set_value`](Self::set_value), this method records the |
| 974 | /// replacement in the undo stack, allowing the user to undo/redo |
| 975 | /// the change. The selection is placed at the end of the new text |
| 976 | /// for single-line inputs, or cleared (0..0) for multi-line inputs. |
| 977 | /// |
| 978 | /// Use this when programmatically replacing the full text but the |
| 979 | /// user should still be able to undo the operation — e.g. formatting. |
| 980 | pub fn replace_all( |
| 981 | &mut self, |
| 982 | text: impl Into<SharedString>, |
| 983 | window: &mut Window, |
| 984 | cx: &mut Context<Self>, |
| 985 | ) { |
| 986 | self.replace_text(text, window, cx); |
| 987 | self.reset_selection(); |
| 988 | self.reset_lsp_state(); |
| 989 | self.reset_scroll_to_start(); |
| 990 | |
| 991 | cx.notify(); |
| 992 | } |
| 993 | |
| 994 | /// Perform `f` with the user-facing edit restrictions lifted. |
| 995 | /// |
| 996 | /// The `disabled` and `readonly` modes only reject the changes made by the |
| 997 | /// user, the programmatic APIs must always be able to update the text. |
| 998 | pub(super) fn with_edits_allowed(&mut self, f: impl FnOnce(&mut Self)) { |
| 999 | let (was_disabled, was_readonly) = (self.disabled, self.readonly); |
| 1000 | (self.disabled, self.readonly) = (false, false); |
| 1001 | f(self); |
| 1002 | (self.disabled, self.readonly) = (was_disabled, was_readonly); |
| 1003 | } |
| 1004 | |
| 1005 | /// Insert text at the current cursor position. |
| 1006 | /// |
| 1007 | /// And the cursor will be moved to the end of inserted text. |
| 1008 | pub fn insert( |
| 1009 | &mut self, |
| 1010 | text: impl Into<SharedString>, |
| 1011 | window: &mut Window, |
| 1012 | cx: &mut Context<Self>, |
| 1013 | ) { |
| 1014 | let text: SharedString = text.into(); |
| 1015 | self.with_edits_allowed(|this| { |
| 1016 | this.undo_manager.set_pending_intent(EditIntent::Atomic); |
| 1017 | let range_utf16 = this.range_to_utf16(&(this.cursor()..this.cursor())); |
| 1018 | this.replace_text_in_range_silent(Some(range_utf16), &text, window, cx); |
| 1019 | let end = this.active_selection().end; |
| 1020 | this.set_cursor_to(end); |
| 1021 | }); |
| 1022 | } |
| 1023 | |
| 1024 | /// Apply `(byte range in the current text, replacement)` edits as one undo step. |
| 1025 | pub fn apply_edits( |
| 1026 | &mut self, |
| 1027 | edits: &[(Range<usize>, String)], |
| 1028 | window: &mut Window, |
| 1029 | cx: &mut Context<Self>, |
| 1030 | ) { |
| 1031 | self.with_edits_allowed(|this| { |
| 1032 | this.undo_manager.set_pending_intent(EditIntent::Atomic); |
| 1033 | this.replace_text_in_ranges(edits, window, cx); |
| 1034 | }); |
| 1035 | } |
| 1036 | |
| 1037 | /// Replace text at the current cursor position. |
| 1038 | /// |
| 1039 | /// And the cursor will be moved to the end of replaced text. |
| 1040 | pub fn replace( |
| 1041 | &mut self, |
| 1042 | text: impl Into<SharedString>, |
| 1043 | window: &mut Window, |
| 1044 | cx: &mut Context<Self>, |
| 1045 | ) { |
| 1046 | let text: SharedString = text.into(); |
| 1047 | self.with_edits_allowed(|this| { |
| 1048 | this.undo_manager.set_pending_intent(EditIntent::Atomic); |
| 1049 | this.replace_text_in_range_silent(None, &text, window, cx); |
| 1050 | let end = this.active_selection().end; |
| 1051 | this.set_cursor_to(end); |
| 1052 | }); |
| 1053 | } |
| 1054 | |
| 1055 | fn replace_text( |
| 1056 | &mut self, |
| 1057 | text: impl Into<SharedString>, |
| 1058 | window: &mut Window, |
| 1059 | cx: &mut Context<Self>, |
| 1060 | ) { |
| 1061 | let text: SharedString = text.into(); |
| 1062 | self.with_edits_allowed(|this| { |
| 1063 | this.undo_manager.set_pending_intent(EditIntent::Atomic); |
| 1064 | let range = 0..this.text.chars().map(|c| c.len_utf16()).sum(); |
| 1065 | this.replace_text_in_range_silent(Some(range), &text, window, cx); |
| 1066 | this.reset_highlighter(cx); |
| 1067 | }); |
| 1068 | } |
| 1069 | |
| 1070 | fn reset_selection(&mut self) { |
| 1071 | self.selections.remove_all_but_active(); |
| 1072 | |
| 1073 | // For single-line inputs the caret is placed at the end of the text |
| 1074 | // (matching HTML `<input>`); multi-line inputs reset the selection to |
| 1075 | // `0..0`. |
| 1076 | if self.is_single_line() { |
| 1077 | let end = self.text.len(); |
| 1078 | self.set_cursor_to(end); |
| 1079 | } else { |
| 1080 | self.active_selection_mut().clear(); |
| 1081 | } |
| 1082 | } |
| 1083 | |
| 1084 | fn reset_lsp_state(&mut self) { |
| 1085 | if self.is_code_editor() { |
| 1086 | self._pending_update = true; |
| 1087 | M::reset_language_features(self); |
| 1088 | } |
| 1089 | } |
| 1090 | |
| 1091 | fn reset_scroll_to_start(&mut self) { |
| 1092 | // Move scroll to the start. For single-line the caret is at the end, so |
| 1093 | // override the cursor-follow scroll for the next painted frame to keep |
| 1094 | // the start visible; the deferred offset is consumed during that paint. |
| 1095 | self.scroll_handle.set_offset(point(px(0.), px(0.))); |
| 1096 | if self.is_single_line() { |
| 1097 | self.deferred_scroll_offset = Some(point(px(0.), px(0.))); |
| 1098 | } |
| 1099 | } |
| 1100 | |
| 1101 | /// Set with disabled mode. |
| 1102 | /// |
| 1103 | /// See also: [`Self::set_disabled`]. |
| 1104 | #[allow(unused)] |
| 1105 | pub(crate) fn disabled(mut self, disabled: bool) -> Self { |
| 1106 | self.disabled = disabled; |
| 1107 | self |
| 1108 | } |
| 1109 | |
| 1110 | pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) { |
| 1111 | if self.disabled == disabled { |
| 1112 | return; |
| 1113 | } |
| 1114 | |
| 1115 | self.disabled = disabled; |
| 1116 | if disabled { |
| 1117 | M::hide_context_menu(self, cx); |
| 1118 | M::clear_inline_completion(self, cx); |
| 1119 | } |
| 1120 | cx.notify(); |
| 1121 | } |
| 1122 | |
| 1123 | /// Set with read-only mode. |
| 1124 | /// |
| 1125 | /// Unlike [`Self::disabled`], a read-only input keeps the normal appearance, |
| 1126 | /// focus, cursor, selection and copy behavior, it only rejects any change |
| 1127 | /// of the text made by the user. |
| 1128 | /// |
| 1129 | /// See also: [`Self::set_readonly`]. |
| 1130 | #[allow(unused)] |
| 1131 | pub(crate) fn readonly(mut self, readonly: bool) -> Self { |
| 1132 | self.readonly = readonly; |
| 1133 | self |
| 1134 | } |
| 1135 | |
| 1136 | pub fn set_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) { |
| 1137 | if self.readonly == readonly { |
| 1138 | return; |
| 1139 | } |
| 1140 | |
| 1141 | self.readonly = readonly; |
| 1142 | if readonly { |
| 1143 | M::hide_context_menu(self, cx); |
| 1144 | M::clear_inline_completion(self, cx); |
| 1145 | self.search_session.replace_mode = false; |
| 1146 | } |
| 1147 | cx.notify(); |
| 1148 | } |
| 1149 | |
| 1150 | /// Returns true if the user is allowed to change the text. |
| 1151 | /// |
| 1152 | /// This is false when the input is `disabled` or `readonly`, the programmatic |
| 1153 | /// APIs (e.g.: [`Self::set_value`], [`Self::insert`]) are not limited by this. |
| 1154 | pub fn is_editable(&self) -> bool { |
| 1155 | !self.disabled && !self.readonly |
| 1156 | } |
| 1157 | |
| 1158 | /// Set true to clear the input by pressing Escape key. |
| 1159 | pub fn clean_on_escape(mut self) -> Self { |
| 1160 | self.clean_on_escape = true; |
| 1161 | self |
| 1162 | } |
| 1163 | |
| 1164 | pub fn set_clean_on_escape(&mut self, clean: bool) { |
| 1165 | self.clean_on_escape = clean; |
| 1166 | } |
| 1167 | |
| 1168 | /// Set true to treat `Enter` as a submit action in multi-line mode, |
| 1169 | /// while `Shift+Enter` inserts a newline. |
| 1170 | /// |
| 1171 | /// Default is `false` (both `Enter` and `Shift+Enter` insert a newline). |
| 1172 | #[doc(hidden)] |
| 1173 | pub fn submit_on_enter(mut self, submit: bool) -> Self { |
| 1174 | self.submit_on_enter = submit; |
| 1175 | self |
| 1176 | } |
| 1177 | |
| 1178 | pub fn set_submit_on_enter(&mut self, submit: bool, cx: &mut Context<Self>) { |
| 1179 | self.submit_on_enter = submit; |
| 1180 | cx.notify(); |
| 1181 | } |
| 1182 | |
| 1183 | /// Set whether to show whitespace characters. |
| 1184 | #[doc(hidden)] |
| 1185 | pub fn show_whitespaces(mut self, show: bool) -> Self { |
| 1186 | self.show_whitespaces = show; |
| 1187 | self |
| 1188 | } |
| 1189 | |
| 1190 | /// Update whether to show whitespace characters. |
| 1191 | pub fn set_show_whitespaces(&mut self, show: bool, _: &mut Window, cx: &mut Context<Self>) { |
| 1192 | self.show_whitespaces = show; |
| 1193 | cx.notify(); |
| 1194 | } |
| 1195 | |
| 1196 | /// Empty rows reserved below the last line of content ("scroll |
| 1197 | /// beyond last line"), code-editor mode only. Mirrors VSCode's |
| 1198 | /// `editor.scrollBeyondLastLine` / Zed's `scroll_beyond_last_line`. |
| 1199 | /// |
| 1200 | /// - `None` (default): half the viewport, floored at |
| 1201 | /// [`BOTTOM_MARGIN_ROWS`] line-heights. |
| 1202 | /// - `Some(0)`: no trailing space; the cursor sits flush with the |
| 1203 | /// last row at scroll-max. |
| 1204 | /// - `Some(n)`: exactly `n` rows. |
| 1205 | pub fn scroll_beyond_last_line(mut self, rows: Option<usize>) -> Self { |
| 1206 | self.scroll_beyond_last_line = rows; |
| 1207 | self |
| 1208 | } |
| 1209 | |
| 1210 | /// Update [`Self::scroll_beyond_last_line`] after construction. |
| 1211 | pub fn set_scroll_beyond_last_line( |
| 1212 | &mut self, |
| 1213 | rows: Option<usize>, |
| 1214 | _: &mut Window, |
| 1215 | cx: &mut Context<Self>, |
| 1216 | ) { |
| 1217 | if self.scroll_beyond_last_line == rows { |
| 1218 | return; |
| 1219 | } |
| 1220 | self.scroll_beyond_last_line = rows; |
| 1221 | cx.notify(); |
| 1222 | } |
| 1223 | |
| 1224 | /// Minimum number of lines the cursor is kept clear of the viewport's |
| 1225 | /// top/bottom edge before auto-scroll engages. Mirrors VSCode's |
| 1226 | /// `editor.cursorSurroundingLines` / Zed's `vertical_scroll_margin`. |
| 1227 | /// Orthogonal to [`Self::scroll_beyond_last_line`], which sizes the |
| 1228 | /// empty region; this controls the cursor's resting distance from the |
| 1229 | /// edge. |
| 1230 | /// |
| 1231 | /// - `None` (default): [`BOTTOM_MARGIN_ROWS`] lines, falling back to |
| 1232 | /// one line on small viewports. |
| 1233 | /// - `Some(n)`: exactly `n` lines, clamped to half the viewport. |
| 1234 | pub fn cursor_surrounding_lines(mut self, lines: Option<usize>) -> Self { |
| 1235 | self.cursor_surrounding_lines = lines; |
| 1236 | self |
| 1237 | } |
| 1238 | |
| 1239 | /// Update [`Self::cursor_surrounding_lines`] after construction. |
| 1240 | pub fn set_cursor_surrounding_lines( |
| 1241 | &mut self, |
| 1242 | lines: Option<usize>, |
| 1243 | _: &mut Window, |
| 1244 | cx: &mut Context<Self>, |
| 1245 | ) { |
| 1246 | if self.cursor_surrounding_lines == lines { |
| 1247 | return; |
| 1248 | } |
| 1249 | self.cursor_surrounding_lines = lines; |
| 1250 | cx.notify(); |
| 1251 | } |
| 1252 | |
| 1253 | /// Set the default value of the input field. |
| 1254 | pub fn default_value(mut self, value: impl Into<SharedString>) -> Self { |
| 1255 | let text: SharedString = value.into(); |
| 1256 | self.text = Rope::from(self.normalize_input(&text).as_ref()); |
| 1257 | if let Some(diagnostics) = self.mode.diagnostics_mut() { |
| 1258 | diagnostics.reset(&self.text) |
| 1259 | } |
| 1260 | // Note: We can't call display_map.set_text here because it needs cx. |
| 1261 | // The text will be set during prepare_if_need in element.rs |
| 1262 | self._pending_update = true; |
| 1263 | self |
| 1264 | } |
| 1265 | |
| 1266 | /// Return the value of the input field as an owned string. |
| 1267 | /// |
| 1268 | /// The string is materialized on each call. See [`Self::text`] for the |
| 1269 | /// [`Rope`] the state owns, which is borrowed and costs nothing to read. |
| 1270 | pub fn value(&self) -> SharedString { |
| 1271 | SharedString::new(self.text.to_string()) |
| 1272 | } |
| 1273 | |
| 1274 | /// Return the portion of the value within the input field that |
| 1275 | /// is selected by the user, as an owned string. |
| 1276 | /// |
| 1277 | /// The string is materialized on each call. See [`Self::selected_text`] |
| 1278 | /// for the same selection borrowed out of the [`Rope`] the state owns. |
| 1279 | pub fn selected_value(&self) -> SharedString { |
| 1280 | SharedString::new(self.selected_text().to_string()) |
| 1281 | } |
| 1282 | |
| 1283 | /// Return the value without mask. |
| 1284 | pub fn unmask_value(&self) -> SharedString { |
| 1285 | self.mask_pattern.unmask(&self.text.to_string()).into() |
| 1286 | } |
| 1287 | |
| 1288 | /// Kept so existing render paths keep compiling. |
| 1289 | /// |
| 1290 | /// Configuration used to be collected by a facade and applied here; the |
| 1291 | /// state now configures itself, so this does nothing and can be deleted at |
| 1292 | /// the call site. |
| 1293 | #[doc(hidden)] |
| 1294 | pub fn prepare(&mut self, _: &mut Window, _: &mut Context<Self>) {} |
| 1295 | |
| 1296 | /// Return the text [`Rope`] of the input field. |
| 1297 | /// |
| 1298 | /// Borrowed from the state, so reading even a large document copies |
| 1299 | /// nothing. See [`Self::value`] when an owned string is wanted. |
| 1300 | pub fn text(&self) -> &Rope { |
| 1301 | &self.text |
| 1302 | } |
| 1303 | |
| 1304 | /// Return the (0-based) [`Position`] of the cursor. |
| 1305 | pub fn cursor_position(&self) -> Position { |
| 1306 | let offset = self.cursor(); |
| 1307 | self.text.offset_to_position(offset) |
| 1308 | } |
| 1309 | |
| 1310 | /// Set (0-based) [`Position`] of the cursor. |
| 1311 | /// |
| 1312 | /// This will move the cursor to the specified line and column, and update the selection range. |
| 1313 | pub fn set_cursor_position( |
| 1314 | &mut self, |
| 1315 | position: impl Into<Position>, |
| 1316 | window: &mut Window, |
| 1317 | cx: &mut Context<Self>, |
| 1318 | ) { |
| 1319 | let position: Position = position.into(); |
| 1320 | let offset = self.text.position_to_offset(&position); |
| 1321 | |
| 1322 | self.move_to(offset, None, cx); |
| 1323 | self.update_preferred_column(); |
| 1324 | self.focus(window, cx); |
| 1325 | } |
| 1326 | |
| 1327 | /// Focus the input field. |
| 1328 | pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) { |
| 1329 | self.focus_handle.focus(window, cx); |
| 1330 | self.blink_cursor.update(cx, |cursor, cx| { |
| 1331 | cursor.start(cx); |
| 1332 | }); |
| 1333 | } |
| 1334 | |
| 1335 | /// Refresh the input, so the next render re-runs syntax highlighting and |
| 1336 | /// the LSP providers, not just a redraw. |
| 1337 | /// |
| 1338 | /// Assigning the `lsp` providers (or other render-affecting state) at |
| 1339 | /// runtime does not take effect until the text next changes. Call this |
| 1340 | /// afterwards to force the refresh on the next render. |
| 1341 | /// |
| 1342 | /// ```ignore |
| 1343 | /// input.update(cx, |state, cx| { |
| 1344 | /// state.extras.lsp.hover_provider = Some(provider); |
| 1345 | /// state.refresh(cx); |
| 1346 | /// }); |
| 1347 | /// ``` |
| 1348 | pub fn refresh(&mut self, cx: &mut Context<Self>) { |
| 1349 | self._pending_update = true; |
| 1350 | cx.notify(); |
| 1351 | } |
| 1352 | |
| 1353 | pub(super) fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) { |
| 1354 | self.undo_manager.break_transaction_coalescing(); |
| 1355 | self.select_all_cursors_to(|s, sel| s.previous_boundary(sel.cursor_offset()), cx); |
| 1356 | } |
| 1357 | |
| 1358 | pub(super) fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) { |
| 1359 | self.select_all_cursors_to(|s, sel| s.next_boundary(sel.cursor_offset()), cx); |
| 1360 | } |
| 1361 | |
| 1362 | pub(super) fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) { |
| 1363 | if self.is_single_line() { |
| 1364 | return; |
| 1365 | } |
| 1366 | self.select_all_cursors_to_with_affinity( |
| 1367 | |s, sel| { |
| 1368 | s.vertical_selection_target( |
| 1369 | sel.cursor_offset(), |
| 1370 | sel.column_anchor, |
| 1371 | s.line_end_affinity_for(sel), |
| 1372 | -1, |
| 1373 | ) |
| 1374 | }, |
| 1375 | true, |
| 1376 | cx, |
| 1377 | ); |
| 1378 | } |
| 1379 | |
| 1380 | pub(super) fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) { |
| 1381 | if self.is_single_line() { |
| 1382 | return; |
| 1383 | } |
| 1384 | self.select_all_cursors_to_with_affinity( |
| 1385 | |s, sel| { |
| 1386 | s.vertical_selection_target( |
| 1387 | sel.cursor_offset(), |
| 1388 | sel.column_anchor, |
| 1389 | s.line_end_affinity_for(sel), |
| 1390 | 1, |
| 1391 | ) |
| 1392 | }, |
| 1393 | true, |
| 1394 | cx, |
| 1395 | ); |
| 1396 | } |
| 1397 | |
| 1398 | pub(super) fn on_action_select_all( |
| 1399 | &mut self, |
| 1400 | _: &SelectAll, |
| 1401 | window: &mut Window, |
| 1402 | cx: &mut Context<Self>, |
| 1403 | ) { |
| 1404 | self.select_all(window, cx); |
| 1405 | } |
| 1406 | |
| 1407 | pub(super) fn select_to_start( |
| 1408 | &mut self, |
| 1409 | _: &SelectToStart, |
| 1410 | _: &mut Window, |
| 1411 | cx: &mut Context<Self>, |
| 1412 | ) { |
| 1413 | self.undo_manager.break_transaction_coalescing(); |
| 1414 | self.select_all_cursors_to(|_, _| 0, cx); |
| 1415 | } |
| 1416 | |
| 1417 | pub(super) fn select_to_end( |
| 1418 | &mut self, |
| 1419 | _: &SelectToEnd, |
| 1420 | _: &mut Window, |
| 1421 | cx: &mut Context<Self>, |
| 1422 | ) { |
| 1423 | self.undo_manager.break_transaction_coalescing(); |
| 1424 | let end = self.text.len(); |
| 1425 | self.select_all_cursors_to(move |_, _| end, cx); |
| 1426 | } |
| 1427 | |
| 1428 | pub(super) fn select_to_start_of_line( |
| 1429 | &mut self, |
| 1430 | _: &SelectToStartOfLine, |
| 1431 | _: &mut Window, |
| 1432 | cx: &mut Context<Self>, |
| 1433 | ) { |
| 1434 | self.undo_manager.break_transaction_coalescing(); |
| 1435 | self.select_all_cursors_to( |
| 1436 | |s, sel| s.start_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)), |
| 1437 | cx, |
| 1438 | ); |
| 1439 | } |
| 1440 | |
| 1441 | pub(super) fn select_to_end_of_line( |
| 1442 | &mut self, |
| 1443 | _: &SelectToEndOfLine, |
| 1444 | _: &mut Window, |
| 1445 | cx: &mut Context<Self>, |
| 1446 | ) { |
| 1447 | self.undo_manager.break_transaction_coalescing(); |
| 1448 | self.select_all_cursors_to_with_affinity( |
| 1449 | |s, sel| { |
| 1450 | ( |
| 1451 | s.end_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)), |
| 1452 | true, |
| 1453 | ) |
| 1454 | }, |
| 1455 | false, |
| 1456 | cx, |
| 1457 | ); |
| 1458 | } |
| 1459 | |
| 1460 | pub(super) fn select_to_previous_word( |
| 1461 | &mut self, |
| 1462 | _: &SelectToPreviousWordStart, |
| 1463 | _: &mut Window, |
| 1464 | cx: &mut Context<Self>, |
| 1465 | ) { |
| 1466 | self.undo_manager.break_transaction_coalescing(); |
| 1467 | self.select_all_cursors_to( |
| 1468 | |s, sel| s.previous_start_of_word_at(sel.cursor_offset()), |
| 1469 | cx, |
| 1470 | ); |
| 1471 | } |
| 1472 | |
| 1473 | pub(super) fn select_to_next_word( |
| 1474 | &mut self, |
| 1475 | _: &SelectToNextWordEnd, |
| 1476 | _: &mut Window, |
| 1477 | cx: &mut Context<Self>, |
| 1478 | ) { |
| 1479 | self.undo_manager.break_transaction_coalescing(); |
| 1480 | self.select_all_cursors_to(|s, sel| s.next_end_of_word_at(sel.cursor_offset()), cx); |
| 1481 | } |
| 1482 | |
| 1483 | /// Return the start offset of the previous word. |
| 1484 | /// Return the previous start offset of the word before `offset`. |
| 1485 | pub(super) fn previous_start_of_word_at(&self, offset: usize) -> usize { |
| 1486 | if self.masked { |
| 1487 | // The mask replaces every character, so the displayed text has no |
| 1488 | // word boundaries to move or delete by. Collapse the word to the |
| 1489 | // whole text. |
| 1490 | return 0; |
| 1491 | } |
| 1492 | |
| 1493 | let offset = self.offset_from_utf16(self.offset_to_utf16(offset)); |
| 1494 | // FIXME: Avoid to_string |
| 1495 | let left_part = self.text.slice(0..offset).to_string(); |
| 1496 | |
| 1497 | let target = UnicodeSegmentation::split_word_bound_indices(left_part.as_str()) |
| 1498 | .rfind(|(_, s)| !s.trim_start().is_empty()) |
| 1499 | .map(|(i, _)| i) |
| 1500 | .unwrap_or(0); |
| 1501 | self.token_boundary(target, Bias::Left) |
| 1502 | } |
| 1503 | |
| 1504 | /// Return the next end offset of the word after `offset`. |
| 1505 | pub(super) fn next_end_of_word_at(&self, offset: usize) -> usize { |
| 1506 | if self.masked { |
| 1507 | // See `previous_start_of_word_at`. |
| 1508 | return self.text.len(); |
| 1509 | } |
| 1510 | |
| 1511 | let offset = self.offset_from_utf16(self.offset_to_utf16(offset)); |
| 1512 | let right_part = self.text.slice(offset..self.text.len()).to_string(); |
| 1513 | |
| 1514 | let target = UnicodeSegmentation::split_word_bound_indices(right_part.as_str()) |
| 1515 | .find(|(_, s)| !s.trim_start().is_empty()) |
| 1516 | .map(|(i, s)| offset + i + s.len()) |
| 1517 | .unwrap_or(self.text.len()); |
| 1518 | self.token_boundary(target, Bias::Right) |
| 1519 | } |
| 1520 | |
| 1521 | /// Get start of line byte offset for the given `offset`. |
| 1522 | /// |
| 1523 | /// When soft wrap is active, first press goes to visual line start, |
| 1524 | /// second press (already at visual start) goes to logical line start. |
| 1525 | pub(super) fn start_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize { |
| 1526 | if self.is_single_line() { |
| 1527 | return 0; |
| 1528 | } |
| 1529 | |
| 1530 | let row = self.text.offset_to_point(offset).row; |
| 1531 | let logical_start = self.text.line_start_offset(row); |
| 1532 | |
| 1533 | if self.soft_wrap && self.is_code_editor() { |
| 1534 | let wrap_point = self |
| 1535 | .display_map |
| 1536 | .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity); |
| 1537 | if let Some(line) = self.display_map.line(row) |
| 1538 | && let Some(range) = line.wrapped_lines.get(wrap_point.local_row) |
| 1539 | { |
| 1540 | let visual_start = logical_start + range.start; |
| 1541 | if offset != visual_start { |
| 1542 | return visual_start; |
| 1543 | } |
| 1544 | } |
| 1545 | } |
| 1546 | |
| 1547 | logical_start |
| 1548 | } |
| 1549 | |
| 1550 | /// Get end of line byte offset for the given `offset`. |
| 1551 | /// |
| 1552 | /// When soft wrap is active, first press goes to visual line end, |
| 1553 | /// second press (already at visual end) goes to logical line end. |
| 1554 | pub(super) fn end_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize { |
| 1555 | if self.is_single_line() { |
| 1556 | return self.text.len(); |
| 1557 | } |
| 1558 | |
| 1559 | let row = self.text.offset_to_point(offset).row; |
| 1560 | let logical_start = self.text.line_start_offset(row); |
| 1561 | let logical_end = self.text.line_end_offset(row); |
| 1562 | |
| 1563 | if self.soft_wrap && self.is_code_editor() { |
| 1564 | // Use the row the caret is drawn on: at a wrap boundary the raw offset would name |
| 1565 | // the next row, and a second End press would keep walking down instead of falling |
| 1566 | // through to the logical line end. |
| 1567 | let wrap_point = self |
| 1568 | .display_map |
| 1569 | .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity); |
| 1570 | if let Some(line) = self.display_map.line(row) |
| 1571 | && let Some(range) = line.wrapped_lines.get(wrap_point.local_row) |
| 1572 | { |
| 1573 | let visual_end = logical_start + range.end; |
| 1574 | if offset != visual_end { |
| 1575 | return visual_end; |
| 1576 | } |
| 1577 | } |
| 1578 | } |
| 1579 | |
| 1580 | logical_end |
| 1581 | } |
| 1582 | |
| 1583 | /// Get indent string of next line. |
| 1584 | /// |
| 1585 | /// To get current and next line indent, to return more depth one. |
| 1586 | pub(super) fn indent_of_next_line(&mut self) -> String { |
| 1587 | self.indent_of_next_line_at(self.cursor()) |
| 1588 | } |
| 1589 | |
| 1590 | /// Get indent string of the next line, relative to the given `offset`. |
| 1591 | pub(super) fn indent_of_next_line_at(&mut self, offset: usize) -> String { |
| 1592 | if self.is_single_line() { |
| 1593 | return "".into(); |
| 1594 | } |
| 1595 | |
| 1596 | let mut current_indent = String::new(); |
| 1597 | let mut next_indent = String::new(); |
| 1598 | let line_end_affinity = self.line_end_affinity_at(offset); |
| 1599 | let current_line_start_pos = self.start_of_line_at(offset, line_end_affinity); |
| 1600 | let next_line_start_pos = self.end_of_line_at(offset, line_end_affinity); |
| 1601 | for c in self.text.slice(current_line_start_pos..).chars() { |
| 1602 | if !c.is_whitespace() { |
| 1603 | break; |
| 1604 | } |
| 1605 | if c == '\n' || c == '\r' { |
| 1606 | break; |
| 1607 | } |
| 1608 | current_indent.push(c); |
| 1609 | } |
| 1610 | |
| 1611 | for c in self.text.slice(next_line_start_pos..).chars() { |
| 1612 | if !c.is_whitespace() { |
| 1613 | break; |
| 1614 | } |
| 1615 | if c == '\n' || c == '\r' { |
| 1616 | break; |
| 1617 | } |
| 1618 | next_indent.push(c); |
| 1619 | } |
| 1620 | |
| 1621 | if next_indent.len() > current_indent.len() { |
| 1622 | return next_indent; |
| 1623 | } |
| 1624 | |
| 1625 | // Smart indent: one extra level after lines ending with a trigger. |
| 1626 | // Skipped inside strings and comments: the trigger is literal text. |
| 1627 | if let Some(rules) = self.mode.language_config() { |
| 1628 | if self.mode.is_smart_indent() |
| 1629 | && M::editing_syntax_context(self, offset) == crate::input::SyntaxContext::Code |
| 1630 | { |
| 1631 | let line_before: String = self |
| 1632 | .text |
| 1633 | .slice(current_line_start_pos..offset) |
| 1634 | .chars() |
| 1635 | .collect(); |
| 1636 | if rules.opens_indent(line_before.trim_end()) { |
| 1637 | let tab = self.mode.tab_size(); |
| 1638 | if tab.hard_tabs { |
| 1639 | current_indent.push('\t'); |
| 1640 | } else { |
| 1641 | for _ in 0..tab.tab_size { |
| 1642 | current_indent.push(' '); |
| 1643 | } |
| 1644 | } |
| 1645 | } else { |
| 1646 | let line_after = self.text.slice(offset..next_line_start_pos).to_string(); |
| 1647 | if rules.closes_indent(&line_after) { |
| 1648 | let tab = self.mode.tab_size(); |
| 1649 | if current_indent.ends_with('\t') { |
| 1650 | current_indent.pop(); |
| 1651 | } else { |
| 1652 | for _ in 0..tab.tab_size { |
| 1653 | if !current_indent.ends_with(' ') { |
| 1654 | break; |
| 1655 | } |
| 1656 | current_indent.pop(); |
| 1657 | } |
| 1658 | } |
| 1659 | } |
| 1660 | } |
| 1661 | } |
| 1662 | } |
| 1663 | |
| 1664 | current_indent |
| 1665 | } |
| 1666 | |
| 1667 | /// Delete every selection as one batch. Collapsed cursors are first |
| 1668 | /// expanded to a deletion range by `collapsed_target` and non-empty |
| 1669 | /// selections delete their own range. |
| 1670 | /// |
| 1671 | /// `collapsed_intent` is the intent to record when every cursor is |
| 1672 | /// collapsed, which is what makes a run of single-character deletes undo |
| 1673 | /// as one gesture. Deleting a real selection is always atomic. |
| 1674 | fn delete_selections( |
| 1675 | &mut self, |
| 1676 | silent: bool, |
| 1677 | collapsed_intent: EditIntent, |
| 1678 | mut collapsed_target: impl FnMut(&mut Self, usize) -> Range<usize>, |
| 1679 | window: &mut Window, |
| 1680 | cx: &mut Context<Self>, |
| 1681 | ) { |
| 1682 | if !self.is_editable() { |
| 1683 | return; |
| 1684 | } |
| 1685 | let cursors: Vec<CursorSelection> = self.selections.iter().copied().collect(); |
| 1686 | let intent = if cursors.iter().all(|sel| sel.is_empty()) { |
| 1687 | collapsed_intent |
| 1688 | } else { |
| 1689 | EditIntent::Atomic |
| 1690 | }; |
| 1691 | let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(cursors.len()); |
| 1692 | for sel in &cursors { |
| 1693 | let range = if sel.is_empty() { |
| 1694 | collapsed_target(self, sel.cursor_offset()) |
| 1695 | } else { |
| 1696 | sel.start..sel.end |
| 1697 | }; |
| 1698 | let (start, end) = (range.start.min(range.end), range.start.max(range.end)); |
| 1699 | let mut selection = *sel; |
| 1700 | selection.start = start; |
| 1701 | selection.end = end; |
| 1702 | new_selections.push(selection); |
| 1703 | } |
| 1704 | // Capture the user's selections before expanding or merging deletion |
| 1705 | // ranges. The edit ranges cannot reconstruct their original carets. |
| 1706 | self.undo_manager.begin_transaction_with(intent); |
| 1707 | self.undo_manager |
| 1708 | .record_selections(cursors.clone(), cursors.clone()); |
| 1709 | self.selections.replace_all(new_selections); |
| 1710 | self.undo_manager.set_pending_intent(intent); |
| 1711 | |
| 1712 | let was_silent = self.silent_replace_text; |
| 1713 | self.silent_replace_text = silent; |
| 1714 | self.replace_text_in_range(None, "", window, cx); |
| 1715 | self.silent_replace_text = was_silent; |
| 1716 | self.undo_manager |
| 1717 | .record_selections(cursors, self.selections.iter().copied().collect()); |
| 1718 | self.undo_manager.commit_transaction(); |
| 1719 | self.pause_blink_cursor(cx); |
| 1720 | } |
| 1721 | |
| 1722 | /// Decide pairing against the pre-edit text, before an opening quote can |
| 1723 | /// change its own syntax context. Ordinary characters never query syntax. |
| 1724 | fn auto_close_target(&self, range: &Range<usize>, text: &str) -> Option<(usize, SharedString)> { |
| 1725 | if self.silent_replace_text |
| 1726 | || self.ime_marked_range.is_some() |
| 1727 | || !self.selections.is_single() |
| 1728 | || !self.active_selection().is_empty() |
| 1729 | || !range.is_empty() |
| 1730 | || range.start != self.cursor() |
| 1731 | || text.chars().count() != 1 |
| 1732 | || !self.mode.is_auto_close() |
| 1733 | { |
| 1734 | return None; |
| 1735 | } |
| 1736 | let rules = self.mode.language_config()?; |
| 1737 | if self |
| 1738 | .text |
| 1739 | .chars_at(range.start) |
| 1740 | .next() |
| 1741 | .is_some_and(|c| !c.is_whitespace() && !rules.auto_close_before.contains(c)) |
| 1742 | { |
| 1743 | return None; |
| 1744 | } |
| 1745 | for (open, close, not_in) in rules.closing_pairs() { |
| 1746 | let Some(prefix) = open.strip_suffix(text) else { |
| 1747 | continue; |
| 1748 | }; |
| 1749 | if !self.text_before_matches(range.start, prefix) { |
| 1750 | continue; |
| 1751 | } |
| 1752 | let start = range.start - prefix.len(); |
| 1753 | if open == close |
| 1754 | && (self.is_escaped_at(start) |
| 1755 | || self |
| 1756 | .text |
| 1757 | .chars_at(start) |
| 1758 | .reversed() |
| 1759 | .next() |
| 1760 | .is_some_and(|c| c.is_alphanumeric() || c == '_')) |
| 1761 | { |
| 1762 | continue; |
| 1763 | } |
| 1764 | if not_in.contains(&M::editing_syntax_context(self, start)) { |
| 1765 | continue; |
| 1766 | } |
| 1767 | return Some((open.len(), close.into())); |
| 1768 | } |
| 1769 | None |
| 1770 | } |
| 1771 | |
| 1772 | fn text_before_matches(&self, offset: usize, text: &str) -> bool { |
| 1773 | offset >= text.len() |
| 1774 | && self.text.is_char_boundary(offset - text.len()) |
| 1775 | && self.text.slice(offset - text.len()..offset) == text |
| 1776 | } |
| 1777 | |
| 1778 | fn text_after_matches(&self, offset: usize, text: &str) -> bool { |
| 1779 | offset + text.len() <= self.text.len() |
| 1780 | && self.text.is_char_boundary(offset + text.len()) |
| 1781 | && self.text.slice(offset..offset + text.len()) == text |
| 1782 | } |
| 1783 | |
| 1784 | fn is_escaped_at(&self, offset: usize) -> bool { |
| 1785 | self.text |
| 1786 | .chars_at(offset) |
| 1787 | .reversed() |
| 1788 | .take_while(|c| *c == '\\') |
| 1789 | .count() |
| 1790 | % 2 |
| 1791 | == 1 |
| 1792 | } |
| 1793 | |
| 1794 | /// Cursor target when a typed closer should skip over an existing one. |
| 1795 | /// |
| 1796 | /// Returns `Some(offset)` when `new_text` is a single closer from the |
| 1797 | /// active [`LanguageConfig`](crate::input::language_config::LanguageConfig) that already follows the collapsed cursor and is |
| 1798 | /// not escaped. The caller then moves the cursor without editing text or |
| 1799 | /// history. `None` means insert normally. |
| 1800 | fn skip_over_target(&self, new_text: &str) -> Option<usize> { |
| 1801 | if !self.mode.is_auto_close() || new_text.chars().count() != 1 { |
| 1802 | return None; |
| 1803 | } |
| 1804 | let rules = self.mode.language_config()?; |
| 1805 | let cursor = self.cursor(); |
| 1806 | for (open, close, not_in) in rules.closing_pairs() { |
| 1807 | for (index, _) in close.char_indices() { |
| 1808 | if !close[index..].starts_with(new_text) |
| 1809 | || !self.text_before_matches(cursor, &close[..index]) |
| 1810 | || !self.text_after_matches(cursor, &close[index..]) |
| 1811 | { |
| 1812 | continue; |
| 1813 | } |
| 1814 | let context = M::editing_syntax_context(self, cursor); |
| 1815 | let generated = |
| 1816 | self.mode |
| 1817 | .auto_closed_pairs() |
| 1818 | .contains_closer(cursor, index, close.len()); |
| 1819 | if !generated |
| 1820 | && not_in.contains(&context) |
| 1821 | && !(context == crate::input::SyntaxContext::String && open == close) |
| 1822 | { |
| 1823 | continue; |
| 1824 | } |
| 1825 | if self.is_escaped_at(cursor - index) { |
| 1826 | continue; |
| 1827 | } |
| 1828 | return Some(cursor + new_text.len()); |
| 1829 | } |
| 1830 | } |
| 1831 | None |
| 1832 | } |
| 1833 | |
| 1834 | pub(super) fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) { |
| 1835 | // Nothing to delete at the start of the text. Propagate so an ancestor |
| 1836 | // (e.g. a command palette navigating back a level) can act on it. |
| 1837 | // This is harmless when nothing upstream is bound to backspace. With multiple |
| 1838 | // cursors the others can still delete, so only the lone-cursor case |
| 1839 | // propagates. |
| 1840 | if self.selections.is_single() && self.active_selection().is_empty() && self.cursor() == 0 { |
| 1841 | cx.propagate(); |
| 1842 | return; |
| 1843 | } |
| 1844 | |
| 1845 | // Pair deletion follows automatic closing rules, independently of |
| 1846 | // structural brackets used by Enter. |
| 1847 | if self.mode.is_auto_close() |
| 1848 | && self.selections.is_single() |
| 1849 | && self.active_selection().is_empty() |
| 1850 | { |
| 1851 | let off = self.cursor(); |
| 1852 | let deletion = self.mode.language_config().and_then(|rules| { |
| 1853 | rules.closing_pairs().find_map(|(open, close, not_in)| { |
| 1854 | if !self.text_before_matches(off, open) || !self.text_after_matches(off, close) |
| 1855 | { |
| 1856 | return None; |
| 1857 | } |
| 1858 | let start = off - open.len(); |
| 1859 | let generated = self |
| 1860 | .mode |
| 1861 | .auto_closed_pairs() |
| 1862 | .contains(start..off, off..off + close.len()); |
| 1863 | if self.is_escaped_at(start) |
| 1864 | || (!generated && not_in.contains(&M::editing_syntax_context(self, start))) |
| 1865 | { |
| 1866 | return None; |
| 1867 | } |
| 1868 | Some(start..off + close.len()) |
| 1869 | }) |
| 1870 | }); |
| 1871 | if let Some(range) = deletion { |
| 1872 | let utf16 = self.range_to_utf16(&range); |
| 1873 | self.replace_text_in_range_silent(Some(utf16), "", window, cx); |
| 1874 | return; |
| 1875 | } |
| 1876 | } |
| 1877 | |
| 1878 | self.delete_selections( |
| 1879 | false, |
| 1880 | EditIntent::Backspace, |
| 1881 | |s, offset| s.previous_boundary(offset)..offset, |
| 1882 | window, |
| 1883 | cx, |
| 1884 | ); |
| 1885 | } |
| 1886 | |
| 1887 | pub(super) fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) { |
| 1888 | self.delete_selections( |
| 1889 | false, |
| 1890 | EditIntent::DeleteForward, |
| 1891 | |s, offset| offset..s.next_boundary(offset), |
| 1892 | window, |
| 1893 | cx, |
| 1894 | ); |
| 1895 | } |
| 1896 | |
| 1897 | pub(super) fn delete_to_beginning_of_line( |
| 1898 | &mut self, |
| 1899 | _: &DeleteToBeginningOfLine, |
| 1900 | window: &mut Window, |
| 1901 | cx: &mut Context<Self>, |
| 1902 | ) { |
| 1903 | self.delete_selections( |
| 1904 | true, |
| 1905 | EditIntent::Atomic, |
| 1906 | |s, offset| { |
| 1907 | let mut start = s.start_of_line_at(offset, s.line_end_affinity_at(offset)); |
| 1908 | if start == offset { |
| 1909 | start = start.saturating_sub(1); |
| 1910 | } |
| 1911 | start..offset |
| 1912 | }, |
| 1913 | window, |
| 1914 | cx, |
| 1915 | ); |
| 1916 | } |
| 1917 | |
| 1918 | pub(super) fn delete_to_end_of_line( |
| 1919 | &mut self, |
| 1920 | _: &DeleteToEndOfLine, |
| 1921 | window: &mut Window, |
| 1922 | cx: &mut Context<Self>, |
| 1923 | ) { |
| 1924 | self.delete_selections( |
| 1925 | true, |
| 1926 | EditIntent::Atomic, |
| 1927 | |s, offset| { |
| 1928 | let mut end = s.end_of_line_at(offset, s.line_end_affinity_at(offset)); |
| 1929 | if end == offset { |
| 1930 | end = (end + 1).clamp(0, s.text.len()); |
| 1931 | } |
| 1932 | offset..end |
| 1933 | }, |
| 1934 | window, |
| 1935 | cx, |
| 1936 | ); |
| 1937 | } |
| 1938 | |
| 1939 | pub(super) fn delete_previous_word( |
| 1940 | &mut self, |
| 1941 | _: &DeleteToPreviousWordStart, |
| 1942 | window: &mut Window, |
| 1943 | cx: &mut Context<Self>, |
| 1944 | ) { |
| 1945 | self.delete_selections( |
| 1946 | true, |
| 1947 | EditIntent::Atomic, |
| 1948 | |s, offset| s.previous_start_of_word_at(offset)..offset, |
| 1949 | window, |
| 1950 | cx, |
| 1951 | ); |
| 1952 | } |
| 1953 | |
| 1954 | pub(super) fn delete_next_word( |
| 1955 | &mut self, |
| 1956 | _: &DeleteToNextWordEnd, |
| 1957 | window: &mut Window, |
| 1958 | cx: &mut Context<Self>, |
| 1959 | ) { |
| 1960 | self.delete_selections( |
| 1961 | true, |
| 1962 | EditIntent::Atomic, |
| 1963 | |s, offset| offset..s.next_end_of_word_at(offset), |
| 1964 | window, |
| 1965 | cx, |
| 1966 | ); |
| 1967 | } |
| 1968 | |
| 1969 | pub(super) fn enter(&mut self, action: &Enter, window: &mut Window, cx: &mut Context<Self>) { |
| 1970 | if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) { |
| 1971 | return; |
| 1972 | } |
| 1973 | |
| 1974 | // Clear inline completion on enter (user chose not to accept it) |
| 1975 | if M::has_inline_completion(self) { |
| 1976 | M::clear_inline_completion(self, cx); |
| 1977 | } |
| 1978 | |
| 1979 | // In multi-line mode with `submit_on_enter` enabled, a plain `Enter` |
| 1980 | // (without Shift) is treated as submit: propagate the action and emit |
| 1981 | // PressEnter without inserting a newline. `Shift+Enter` still inserts |
| 1982 | // a newline. |
| 1983 | let insert_newline = self.is_multi_line() && (!self.submit_on_enter || action.shift); |
| 1984 | |
| 1985 | if insert_newline { |
| 1986 | if !self.selections.is_single() { |
| 1987 | // Insert a newline (with per-line indent) at every cursor. |
| 1988 | self.selections.merge_overlapping(); |
| 1989 | let selections: Vec<CursorSelection> = self.selections.iter().copied().collect(); |
| 1990 | let mut edits: Vec<(Range<usize>, String)> = Vec::with_capacity(selections.len()); |
| 1991 | for sel in &selections { |
| 1992 | let indent = if self.is_code_editor() { |
| 1993 | self.indent_of_next_line_at(sel.cursor_offset()) |
| 1994 | } else { |
| 1995 | String::new() |
| 1996 | }; |
| 1997 | edits.push((sel.start..sel.end, format!("\n{}", indent))); |
| 1998 | } |
| 1999 | edits.sort_by_key(|(range, _)| range.start); |
| 2000 | self.replace_text_in_ranges(&edits, window, cx); |
| 2001 | self.pause_blink_cursor(cx); |
| 2002 | } else { |
| 2003 | // Bracket split: Enter between `{|}` produces `{\n \n}` |
| 2004 | // with the cursor on the middle line. Controlled by smart_indent, |
| 2005 | // independently of automatic closing. |
| 2006 | // Skipped inside strings and comments: splitting there would |
| 2007 | // restructure literal text. |
| 2008 | let mut split = false; |
| 2009 | if self.is_code_editor() && self.active_selection().is_empty() { |
| 2010 | if let Some(rules) = self.mode.language_config() { |
| 2011 | if self.mode.is_smart_indent() |
| 2012 | && M::editing_syntax_context(self, self.cursor()) |
| 2013 | == crate::input::SyntaxContext::Code |
| 2014 | { |
| 2015 | let off = self.cursor(); |
| 2016 | let is_pair = rules.brackets.iter().any(|p| { |
| 2017 | !p.open.is_empty() |
| 2018 | && !p.close.is_empty() |
| 2019 | && p.open != p.close |
| 2020 | && self.text_before_matches(off, p.open.as_ref()) |
| 2021 | && self.text_after_matches(off, p.close.as_ref()) |
| 2022 | }); |
| 2023 | if is_pair { |
| 2024 | // Base indent: leading whitespace only. |
| 2025 | let line_end_affinity = self.line_end_affinity_at(off); |
| 2026 | let line_start = self.start_of_line_at(off, line_end_affinity); |
| 2027 | let mut indent = String::new(); |
| 2028 | for c in self.text.slice(line_start..).chars() { |
| 2029 | if !c.is_whitespace() || c == '\n' || c == '\r' { |
| 2030 | break; |
| 2031 | } |
| 2032 | indent.push(c); |
| 2033 | } |
| 2034 | // Extra level only with smart indent enabled. |
| 2035 | let mut inner = indent.clone(); |
| 2036 | if self.mode.is_smart_indent() { |
| 2037 | let tab = self.mode.tab_size(); |
| 2038 | if tab.hard_tabs { |
| 2039 | inner.push('\t'); |
| 2040 | } else { |
| 2041 | for _ in 0..tab.tab_size { |
| 2042 | inner.push(' '); |
| 2043 | } |
| 2044 | } |
| 2045 | } |
| 2046 | let new_line_text = format!("\n{inner}\n{indent}"); |
| 2047 | self.replace_text_in_range_silent(None, &new_line_text, window, cx); |
| 2048 | self.set_cursor_to(off + 1 + inner.len()); |
| 2049 | self.update_preferred_column(); |
| 2050 | let cursors = self.selections.iter().copied().collect::<Vec<_>>(); |
| 2051 | self.undo_manager |
| 2052 | .record_selections(cursors.clone(), cursors); |
| 2053 | self.pause_blink_cursor(cx); |
| 2054 | split = true; |
| 2055 | } |
| 2056 | } |
| 2057 | } |
| 2058 | } |
| 2059 | if !split { |
| 2060 | // Get current line indent |
| 2061 | let indent = if self.is_code_editor() { |
| 2062 | self.indent_of_next_line() |
| 2063 | } else { |
| 2064 | "".to_string() |
| 2065 | }; |
| 2066 | |
| 2067 | // Add newline and indent |
| 2068 | let new_line_text = format!("\n{}", indent); |
| 2069 | self.replace_text_in_range_silent(None, &new_line_text, window, cx); |
| 2070 | self.pause_blink_cursor(cx); |
| 2071 | } |
| 2072 | } |
| 2073 | } else { |
| 2074 | // Single line input or submit-on-enter: just emit the event |
| 2075 | // (e.g.: in a dialog to confirm, or a chat textarea to send). |
| 2076 | self.undo_manager.break_transaction_coalescing(); |
| 2077 | cx.propagate(); |
| 2078 | } |
| 2079 | |
| 2080 | cx.emit(InputEvent::PressEnter { |
| 2081 | secondary: action.secondary, |
| 2082 | shift: action.shift, |
| 2083 | }); |
| 2084 | } |
| 2085 | |
| 2086 | pub fn clean(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 2087 | self.replace_text("", window, cx); |
| 2088 | self.set_selection(0, 0); |
| 2089 | self.scroll_to(0, None, cx); |
| 2090 | } |
| 2091 | |
| 2092 | pub(super) fn escape(&mut self, action: &Escape, window: &mut Window, cx: &mut Context<Self>) { |
| 2093 | if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) { |
| 2094 | return; |
| 2095 | } |
| 2096 | |
| 2097 | // Escape also dismisses a request whose popup has not arrived yet. |
| 2098 | M::hide_context_menu(self, cx); |
| 2099 | |
| 2100 | // Collapse extra cursors back to the active one first. |
| 2101 | if !self.selections.is_single() { |
| 2102 | self.undo_manager.break_transaction_coalescing(); |
| 2103 | self.selections.remove_all_but_active(); |
| 2104 | cx.notify(); |
| 2105 | return; |
| 2106 | } |
| 2107 | |
| 2108 | // Clear inline completion on escape |
| 2109 | if M::has_inline_completion(self) { |
| 2110 | M::clear_inline_completion(self, cx); |
| 2111 | return; // Consume the escape, don't propagate |
| 2112 | } |
| 2113 | M::clear_inline_completion(self, cx); |
| 2114 | |
| 2115 | // The handles and the edit menu are the topmost surface to dismiss. |
| 2116 | if self.touch_selection().is_some() { |
| 2117 | self.dismiss_touch_selection(cx); |
| 2118 | return; |
| 2119 | } |
| 2120 | |
| 2121 | if self.ime_marked_range.is_some() { |
| 2122 | self.unmark_text(window, cx); |
| 2123 | } |
| 2124 | |
| 2125 | if self.clean_on_escape { |
| 2126 | return self.clean(window, cx); |
| 2127 | } |
| 2128 | |
| 2129 | cx.propagate(); |
| 2130 | } |
| 2131 | |
| 2132 | /// Show the right-click context menu as a native OS menu. |
| 2133 | pub(crate) fn handle_right_click_menu( |
| 2134 | &mut self, |
| 2135 | position: Point<Pixels>, |
| 2136 | offset: usize, |
| 2137 | window: &mut Window, |
| 2138 | cx: &mut Context<Self>, |
| 2139 | ) { |
| 2140 | if self.disabled { |
| 2141 | return; |
| 2142 | } |
| 2143 | if crate::GlobalState::is_in_deferred_context(cx) { |
| 2144 | return; |
| 2145 | } |
| 2146 | |
| 2147 | if !self.active_selection().contains(offset) { |
| 2148 | self.move_to(offset, None, cx); |
| 2149 | } |
| 2150 | |
| 2151 | if self.is_code_editor() { |
| 2152 | M::on_hover_definition(self, offset, window, cx); |
| 2153 | } |
| 2154 | |
| 2155 | if let Some(handler) = self.context_menu_handler.clone() { |
| 2156 | let capabilities = self.context_menu_capabilities(); |
| 2157 | cx.defer_in(window, move |_, window, cx| { |
| 2158 | handler(NativeMenu::new(), capabilities, position, window, cx); |
| 2159 | }); |
| 2160 | } |
| 2161 | } |
| 2162 | |
| 2163 | pub(super) fn add_cursor_above( |
| 2164 | &mut self, |
| 2165 | _: &AddCursorAbove, |
| 2166 | _: &mut Window, |
| 2167 | cx: &mut Context<Self>, |
| 2168 | ) { |
| 2169 | self.add_cursor_vertical(-1, cx); |
| 2170 | } |
| 2171 | |
| 2172 | pub(super) fn add_cursor_below( |
| 2173 | &mut self, |
| 2174 | _: &AddCursorBelow, |
| 2175 | _: &mut Window, |
| 2176 | cx: &mut Context<Self>, |
| 2177 | ) { |
| 2178 | self.add_cursor_vertical(1, cx); |
| 2179 | } |
| 2180 | |
| 2181 | /// Add a new cursor one display line above (`move_lines < 0`) or below each |
| 2182 | /// existing cursor, preserving the column. Cursors that would not move (at |
| 2183 | /// the first/last display row) or that would duplicate an existing cursor |
| 2184 | /// are skipped. |
| 2185 | fn add_cursor_vertical(&mut self, move_lines: isize, cx: &mut Context<Self>) { |
| 2186 | if !self.is_multi_line() { |
| 2187 | return; |
| 2188 | } |
| 2189 | |
| 2190 | self.pause_blink_cursor(cx); |
| 2191 | // Changing the cursor set ends the editing gesture that came before it. |
| 2192 | self.undo_manager.break_transaction_coalescing(); |
| 2193 | |
| 2194 | let sources: Vec<(usize, Option<(Pixels, usize)>, bool)> = self |
| 2195 | .selections |
| 2196 | .iter() |
| 2197 | .map(|sel| { |
| 2198 | ( |
| 2199 | sel.cursor_offset(), |
| 2200 | sel.column_anchor, |
| 2201 | self.line_end_affinity_for(sel), |
| 2202 | ) |
| 2203 | }) |
| 2204 | .collect(); |
| 2205 | let mut offsets: std::collections::HashSet<usize> = |
| 2206 | sources.iter().map(|(offset, _, _)| *offset).collect(); |
| 2207 | |
| 2208 | let mut newest: Option<usize> = None; |
| 2209 | for (offset, anchor, line_end_affinity) in sources { |
| 2210 | let anchor = anchor.or_else(|| self.preferred_column_for(offset)); |
| 2211 | let (target, _) = self.vertical_target(offset, anchor, line_end_affinity, move_lines); |
| 2212 | if target == offset || offsets.contains(&target) { |
| 2213 | continue; |
| 2214 | } |
| 2215 | offsets.insert(target); |
| 2216 | let id = self.selections.generate_id(); |
| 2217 | let mut cursor = CursorSelection::new(id, target, target); |
| 2218 | cursor.column_anchor = anchor; |
| 2219 | self.selections.add(cursor); |
| 2220 | newest = Some(target); |
| 2221 | } |
| 2222 | |
| 2223 | if let Some(newest) = newest { |
| 2224 | self.scroll_to(newest, None, cx); |
| 2225 | } |
| 2226 | cx.notify(); |
| 2227 | } |
| 2228 | |
| 2229 | /// Add an additional collapsed cursor at `offset`. |
| 2230 | /// |
| 2231 | /// Rejected when `offset` lands inside an existing selection or exactly on |
| 2232 | /// an existing cursor. |
| 2233 | pub(super) fn add_cursor_at(&mut self, offset: usize, cx: &mut Context<Self>) { |
| 2234 | if !self.is_multi_line() { |
| 2235 | return; |
| 2236 | } |
| 2237 | |
| 2238 | for sel in self.selections.iter() { |
| 2239 | if sel.contains(offset) { |
| 2240 | return; |
| 2241 | } |
| 2242 | if sel.is_collapsed() && sel.cursor_offset() == offset { |
| 2243 | return; |
| 2244 | } |
| 2245 | } |
| 2246 | |
| 2247 | self.undo_manager.break_transaction_coalescing(); |
| 2248 | let id = self.selections.generate_id(); |
| 2249 | let mut selection = CursorSelection::new(id, offset, offset); |
| 2250 | selection.column_anchor = self.preferred_column_for(offset); |
| 2251 | self.selections.add(selection); |
| 2252 | cx.notify(); |
| 2253 | } |
| 2254 | |
| 2255 | /// Build a columnar (block) selection spanning the rows between the two |
| 2256 | /// points, one selection per display row at the same column span. |
| 2257 | /// |
| 2258 | /// The span keeps the columns the pointer sat past the end of a short row, so a row |
| 2259 | /// that runs out of text does not narrow the block for the rows that do reach that |
| 2260 | /// far. Each row is then clipped to its own end, selecting as much of the span as it |
| 2261 | /// actually has. |
| 2262 | pub(super) fn build_columnar_selection( |
| 2263 | &mut self, |
| 2264 | start: ColumnarPoint, |
| 2265 | end: ColumnarPoint, |
| 2266 | cx: &mut Context<Self>, |
| 2267 | ) { |
| 2268 | if !self.is_multi_line() { |
| 2269 | return; |
| 2270 | } |
| 2271 | |
| 2272 | self.undo_manager.break_transaction_coalescing(); |
| 2273 | |
| 2274 | let (start_row, start_col) = self.columnar_row_column(start); |
| 2275 | let (end_row, end_col) = self.columnar_row_column(end); |
| 2276 | let (start_row, end_row) = (start_row.min(end_row), start_row.max(end_row)); |
| 2277 | let (start_col, end_col) = (start_col.min(end_col), start_col.max(end_col)); |
| 2278 | |
| 2279 | let mut new_selections = Vec::with_capacity(end_row - start_row + 1); |
| 2280 | for row in start_row..=end_row { |
| 2281 | let sel_start = self |
| 2282 | .display_map |
| 2283 | .display_row_column_to_offset(row, start_col); |
| 2284 | let sel_end = self.display_map.display_row_column_to_offset(row, end_col); |
| 2285 | let id = self.selections.generate_id(); |
| 2286 | let sel_start = self.text.clip_offset(sel_start, Bias::Left); |
| 2287 | let sel_end = self.text.clip_offset(sel_end, Bias::Left); |
| 2288 | new_selections.push(CursorSelection::new(id, sel_start, sel_end)); |
| 2289 | } |
| 2290 | |
| 2291 | self.selections.replace_all(new_selections); |
| 2292 | cx.notify(); |
| 2293 | } |
| 2294 | |
| 2295 | /// Resolve a columnar point to the display row it is on and the column it reaches, |
| 2296 | /// counting the columns beyond the row's end so a short row keeps the full span. |
| 2297 | fn columnar_row_column(&self, point: ColumnarPoint) -> (usize, usize) { |
| 2298 | let display_point = self.display_map.offset_to_wrap_display_point(point.offset); |
| 2299 | let row = self |
| 2300 | .display_map |
| 2301 | .wrap_row_to_display_row(display_point.row) |
| 2302 | .unwrap_or_else(|| { |
| 2303 | self.display_map |
| 2304 | .nearest_visible_display_row(display_point.row) |
| 2305 | }); |
| 2306 | |
| 2307 | (row, display_point.column + point.columns_past_line_end) |
| 2308 | } |
| 2309 | |
| 2310 | pub(super) fn on_mouse_down( |
| 2311 | &mut self, |
| 2312 | event: &MouseDownEvent, |
| 2313 | window: &mut Window, |
| 2314 | cx: &mut Context<Self>, |
| 2315 | ) { |
| 2316 | // A token that consumed the press (a double click selecting it) must |
| 2317 | // not also place the caret. |
| 2318 | if window.default_prevented() { |
| 2319 | return; |
| 2320 | } |
| 2321 | self.undo_manager.break_transaction_coalescing(); |
| 2322 | // Input has its own text selection; suppress the window-level text |
| 2323 | // selection (Root) so it does not start a drag from here. |
| 2324 | crate::global_state::GlobalState::suppress_text_selection(cx); |
| 2325 | |
| 2326 | // Clear inline completion on any mouse interaction |
| 2327 | M::clear_inline_completion(self, cx); |
| 2328 | // A tap on the touch selection asks for its menu back. Any other press |
| 2329 | // places the caret or starts a new drag, and the handles and the menu |
| 2330 | // no longer belong to what is selected. |
| 2331 | if event.button == MouseButton::Left |
| 2332 | && event.click_count == 1 |
| 2333 | && self.reopen_edit_menu_at(event.position, cx) |
| 2334 | { |
| 2335 | return; |
| 2336 | } |
| 2337 | self.dismiss_touch_selection(cx); |
| 2338 | |
| 2339 | // If there have IME marked range and is empty (Means pressed Esc to abort IME typing) |
| 2340 | // Clear the marked range. |
| 2341 | if let Some(ime_marked_range) = &self.ime_marked_range { |
| 2342 | if ime_marked_range.len() == 0 { |
| 2343 | self.ime_marked_range = None; |
| 2344 | } |
| 2345 | } |
| 2346 | |
| 2347 | self.selecting = true; |
| 2348 | let (offset, line_end_affinity, columns_past_line_end) = |
| 2349 | self.resolve_mouse_position(event.position); |
| 2350 | |
| 2351 | if M::on_click(self, event, offset, window, cx) { |
| 2352 | return; |
| 2353 | } |
| 2354 | |
| 2355 | // Triple click to select line |
| 2356 | if event.button == MouseButton::Left && event.click_count >= 3 { |
| 2357 | self.select_line(offset, window, cx); |
| 2358 | return; |
| 2359 | } |
| 2360 | |
| 2361 | // Double click to select word |
| 2362 | if event.button == MouseButton::Left && event.click_count == 2 { |
| 2363 | self.select_word(offset, window, cx); |
| 2364 | // A double tap is touch's other way to select a word, and it |
| 2365 | // gets the handles and the menu like a long press does. |
| 2366 | if crate::GlobalState::is_touch_press(cx) { |
| 2367 | self.keep_touch_selection(cx); |
| 2368 | } |
| 2369 | return; |
| 2370 | } |
| 2371 | |
| 2372 | // Show Mouse context menu |
| 2373 | if event.button == MouseButton::Right { |
| 2374 | if self.enable_context_menu { |
| 2375 | if !self.active_selection().contains(offset) { |
| 2376 | self.move_to(offset, None, cx); |
| 2377 | } |
| 2378 | self.pending_context_menu = Some((event.position, offset)); |
| 2379 | } |
| 2380 | return; |
| 2381 | } |
| 2382 | |
| 2383 | // Multi-cursor placement, multi-line only. |
| 2384 | if self.is_multi_line() && event.button == MouseButton::Left { |
| 2385 | if event.modifiers.alt |
| 2386 | && (event.modifiers.shift || (cfg!(target_os = "linux") && event.modifiers.control)) |
| 2387 | { |
| 2388 | // Alt+Shift starts a block; Linux also accepts Ghostty's Ctrl+Alt. |
| 2389 | // Mark selecting so the drag handler extends the block. |
| 2390 | self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end)); |
| 2391 | self.selecting = true; |
| 2392 | self.move_to_with_affinity(offset, None, line_end_affinity, cx); |
| 2393 | return; |
| 2394 | } else if event.modifiers.alt { |
| 2395 | self.add_cursor_at(offset, cx); |
| 2396 | // Keep click-to-add behavior, but use this press as the block |
| 2397 | // anchor if the user continues dragging with the left button. |
| 2398 | self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end)); |
| 2399 | return; |
| 2400 | } |
| 2401 | } |
| 2402 | |
| 2403 | if event.modifiers.shift { |
| 2404 | self.select_to_with_affinity(offset, line_end_affinity, cx); |
| 2405 | } else { |
| 2406 | self.move_to_with_affinity(offset, None, line_end_affinity, cx) |
| 2407 | } |
| 2408 | } |
| 2409 | |
| 2410 | pub(super) fn on_mouse_up( |
| 2411 | &mut self, |
| 2412 | event: &MouseUpEvent, |
| 2413 | window: &mut Window, |
| 2414 | cx: &mut Context<Self>, |
| 2415 | ) { |
| 2416 | if event.button == MouseButton::Right { |
| 2417 | if let Some((position, offset)) = self.pending_context_menu.take() { |
| 2418 | self.handle_right_click_menu(position, offset, window, cx); |
| 2419 | } |
| 2420 | } |
| 2421 | if self.active_selection().is_empty() { |
| 2422 | self.active_selection_mut().reversed = false; |
| 2423 | } |
| 2424 | self.selecting = false; |
| 2425 | self.selected_word_range = None; |
| 2426 | self.column_select_start = None; |
| 2427 | self.auto_scroll.stop(); |
| 2428 | } |
| 2429 | |
| 2430 | pub(super) fn on_mouse_move( |
| 2431 | &mut self, |
| 2432 | event: &MouseMoveEvent, |
| 2433 | window: &mut Window, |
| 2434 | cx: &mut Context<Self>, |
| 2435 | ) { |
| 2436 | // Check if mouse is within bounds |
| 2437 | let within_bounds = self |
| 2438 | .last_bounds |
| 2439 | .as_ref() |
| 2440 | .map(|bounds| bounds.contains(&event.position)) |
| 2441 | .unwrap_or(false); |
| 2442 | |
| 2443 | if !within_bounds { |
| 2444 | // Clear hover when mouse leaves the input |
| 2445 | M::clear_hover_state(self, cx); |
| 2446 | return; |
| 2447 | } |
| 2448 | |
| 2449 | // Show diagnostic popover on mouse move |
| 2450 | let (offset, _) = self.index_for_mouse_position(event.position); |
| 2451 | M::on_mouse_move(self, offset, event, window, cx); |
| 2452 | |
| 2453 | if self.is_code_editor() { |
| 2454 | // Keep the current popover while the pointer stays on the same |
| 2455 | // diagnostic, so moving over a squiggle neither repaints nor |
| 2456 | // rebuilds the popover. |
| 2457 | match self |
| 2458 | .mode |
| 2459 | .diagnostics() |
| 2460 | .and_then(|set| set.for_offset(offset)) |
| 2461 | { |
| 2462 | Some(diagnostic) => { |
| 2463 | if self.diagnostic_popover.as_deref() != Some(diagnostic) { |
| 2464 | self.diagnostic_popover = Some(Rc::new(diagnostic.clone())); |
| 2465 | cx.notify(); |
| 2466 | } |
| 2467 | } |
| 2468 | None => { |
| 2469 | if self.diagnostic_popover.take().is_some() { |
| 2470 | cx.notify(); |
| 2471 | } |
| 2472 | } |
| 2473 | } |
| 2474 | } |
| 2475 | } |
| 2476 | |
| 2477 | pub(super) fn on_scroll_wheel( |
| 2478 | &mut self, |
| 2479 | event: &ScrollWheelEvent, |
| 2480 | window: &mut Window, |
| 2481 | cx: &mut Context<Self>, |
| 2482 | ) { |
| 2483 | let line_height = self |
| 2484 | .last_layout |
| 2485 | .as_ref() |
| 2486 | .map(|layout| layout.line_height) |
| 2487 | .unwrap_or(window.line_height()); |
| 2488 | let delta = event.delta.pixel_delta(line_height); |
| 2489 | |
| 2490 | let old_offset = self.scroll_handle.offset(); |
| 2491 | self.update_scroll_offset(Some(old_offset + delta), cx); |
| 2492 | |
| 2493 | // Only stop propagation if the offset actually changed |
| 2494 | if self.scroll_handle.offset() != old_offset { |
| 2495 | cx.stop_propagation(); |
| 2496 | } |
| 2497 | |
| 2498 | if self.diagnostic_popover.take().is_some() { |
| 2499 | cx.notify(); |
| 2500 | } |
| 2501 | // The handles follow the text; the menu would sit over whatever |
| 2502 | // scrolls underneath it, so it steps aside until the finger lifts. |
| 2503 | self.edit_menu_on_scroll(event.touch_phase, cx); |
| 2504 | } |
| 2505 | |
| 2506 | pub(super) fn update_scroll_offset( |
| 2507 | &mut self, |
| 2508 | offset: Option<Point<Pixels>>, |
| 2509 | cx: &mut Context<Self>, |
| 2510 | ) { |
| 2511 | let mut offset = offset.unwrap_or(self.scroll_handle.offset()); |
| 2512 | let safe_y_range = |
| 2513 | (-self.scroll_size.height + self.input_bounds.size.height).min(px(0.0))..px(0.); |
| 2514 | |
| 2515 | offset.y = if self.is_single_line() { |
| 2516 | px(0.) |
| 2517 | } else { |
| 2518 | offset.y.clamp(safe_y_range.start, safe_y_range.end) |
| 2519 | }; |
| 2520 | offset.x = clamp_horizontal_scroll_offset( |
| 2521 | offset.x, |
| 2522 | self.scroll_size.width, |
| 2523 | self.input_bounds.size.width, |
| 2524 | self.text_align, |
| 2525 | ); |
| 2526 | if self.scroll_handle.offset() != offset { |
| 2527 | self.scroll_handle.set_offset(offset); |
| 2528 | cx.notify(); |
| 2529 | } |
| 2530 | } |
| 2531 | |
| 2532 | /// Scroll to make the given offset visible. |
| 2533 | /// |
| 2534 | /// If `direction` is Some, will keep edges at the same side. |
| 2535 | pub(crate) fn scroll_to( |
| 2536 | &mut self, |
| 2537 | offset: usize, |
| 2538 | direction: Option<MoveDirection>, |
| 2539 | cx: &mut Context<Self>, |
| 2540 | ) { |
| 2541 | let padding = if direction.is_some() { |
| 2542 | ScrollPadding::SurroundingLines |
| 2543 | } else { |
| 2544 | ScrollPadding::Minimal |
| 2545 | }; |
| 2546 | self.scroll_to_with_padding(offset, direction, padding, cx); |
| 2547 | } |
| 2548 | |
| 2549 | /// Reveal an offset with independently chosen direction restriction and padding. |
| 2550 | /// Search uses surrounding lines without restricting movement to match order. |
| 2551 | pub(crate) fn scroll_to_with_padding( |
| 2552 | &mut self, |
| 2553 | offset: usize, |
| 2554 | direction: Option<MoveDirection>, |
| 2555 | padding: ScrollPadding, |
| 2556 | cx: &mut Context<Self>, |
| 2557 | ) { |
| 2558 | let Some(last_layout) = self.last_layout.as_ref() else { |
| 2559 | return; |
| 2560 | }; |
| 2561 | let Some(bounds) = self.last_bounds.as_ref() else { |
| 2562 | return; |
| 2563 | }; |
| 2564 | |
| 2565 | let mut scroll_offset = self.scroll_handle.offset(); |
| 2566 | let was_offset = scroll_offset; |
| 2567 | let line_height = last_layout.line_height; |
| 2568 | |
| 2569 | let point = self.text.offset_to_point(offset); |
| 2570 | |
| 2571 | let row = point.row; |
| 2572 | |
| 2573 | // Resolve the wrapped row even when the target is outside the last layout. |
| 2574 | let display_pos = self |
| 2575 | .display_map |
| 2576 | .buffer_pos_to_display_pos(crate::input::BufferPoint::new(row, point.column)); |
| 2577 | let row_offset_y = self.display_map.row_top(display_pos.row, line_height); |
| 2578 | let row_extra = self.display_map.row_height(display_pos.row, line_height) - line_height; |
| 2579 | |
| 2580 | // For Right alignment use 0 margin: the cursor indicator is clamped inside bounds |
| 2581 | // in layout_cursors, so shifting the text here would cause a first-click visual jump. |
| 2582 | let safety_margin = match last_layout.text_align { |
| 2583 | TextAlign::Left => RIGHT_MARGIN, |
| 2584 | TextAlign::Right => px(0.), |
| 2585 | TextAlign::Center => CURSOR_WIDTH, |
| 2586 | }; |
| 2587 | if let Some(vi) = last_layout |
| 2588 | .visible_buffer_lines |
| 2589 | .iter() |
| 2590 | .position(|&line| line == row) |
| 2591 | { |
| 2592 | let line = &last_layout.lines[vi]; |
| 2593 | let local_offset = offset.saturating_sub(last_layout.visible_line_byte_offsets[vi]); |
| 2594 | if let Some(pos) = line.position_for_index(local_offset, last_layout, false) { |
| 2595 | let bounds_width = bounds.size.width - last_layout.line_number_width; |
| 2596 | let col_offset_x = pos.x; |
| 2597 | if col_offset_x - safety_margin < -scroll_offset.x { |
| 2598 | // If the position is out of the visible area, scroll to make it visible |
| 2599 | scroll_offset.x = -col_offset_x + safety_margin; |
| 2600 | } else if col_offset_x + safety_margin > -scroll_offset.x + bounds_width { |
| 2601 | scroll_offset.x = -(col_offset_x - bounds_width + safety_margin); |
| 2602 | } |
| 2603 | } |
| 2604 | } |
| 2605 | |
| 2606 | // Scroll the row into view. Use the same edge clearance helper as |
| 2607 | // `TextElement::layout_cursors` so both scroll-into-view paths agree |
| 2608 | // (a mismatch flickered on `Down` at end-of-buffer with a small |
| 2609 | // `cursor_surrounding_lines` override). |
| 2610 | let edge_height = |
| 2611 | if matches!(padding, ScrollPadding::SurroundingLines) && self.is_code_editor() { |
| 2612 | super::element::cursor_surrounding_padding( |
| 2613 | self.mode.is_auto_grow(), |
| 2614 | self.cursor_surrounding_lines, |
| 2615 | super::element::viewport_visible_lines(bounds.size.height, line_height), |
| 2616 | line_height, |
| 2617 | ) |
| 2618 | } else { |
| 2619 | line_height |
| 2620 | }; |
| 2621 | if row_offset_y - edge_height + line_height < -scroll_offset.y { |
| 2622 | // Scroll up |
| 2623 | scroll_offset.y = -row_offset_y + edge_height - line_height; |
| 2624 | } else if row_offset_y + row_extra + edge_height > -scroll_offset.y + bounds.size.height { |
| 2625 | // Scroll down |
| 2626 | scroll_offset.y = -(row_offset_y + row_extra - bounds.size.height + edge_height); |
| 2627 | } |
| 2628 | |
| 2629 | // Avoid necessary scroll, when it was already in the correct position. |
| 2630 | if direction == Some(MoveDirection::Up) { |
| 2631 | scroll_offset.y = scroll_offset.y.max(was_offset.y); |
| 2632 | } else if direction == Some(MoveDirection::Down) { |
| 2633 | scroll_offset.y = scroll_offset.y.min(was_offset.y); |
| 2634 | } |
| 2635 | |
| 2636 | // Clamp the deferred target into the same safe range that |
| 2637 | // `update_scroll_offset` enforces on persist, so paint never shows an |
| 2638 | // over-scrolled frame before the post-paint clamp pulls it back. |
| 2639 | let safe_y_min = (-self.scroll_size.height + self.input_bounds.size.height).min(px(0.)); |
| 2640 | scroll_offset.x = scroll_offset.x.min(px(0.)); |
| 2641 | scroll_offset.y = scroll_offset.y.clamp(safe_y_min, px(0.)); |
| 2642 | self.deferred_scroll_offset = Some(scroll_offset); |
| 2643 | cx.notify(); |
| 2644 | } |
| 2645 | |
| 2646 | pub(super) fn show_character_palette( |
| 2647 | &mut self, |
| 2648 | _: &ShowCharacterPalette, |
| 2649 | window: &mut Window, |
| 2650 | _: &mut Context<Self>, |
| 2651 | ) { |
| 2652 | window.show_character_palette(); |
| 2653 | } |
| 2654 | |
| 2655 | /// The text of every non-empty selection, in document order. |
| 2656 | fn selected_texts(&self) -> Vec<String> { |
| 2657 | let mut selections: Vec<CursorSelection> = self |
| 2658 | .selections |
| 2659 | .iter() |
| 2660 | .copied() |
| 2661 | .filter(|sel| !sel.is_empty()) |
| 2662 | .collect(); |
| 2663 | selections.sort_by_key(|sel| sel.start); |
| 2664 | selections |
| 2665 | .iter() |
| 2666 | .map(|sel| self.text.slice(*sel).to_string()) |
| 2667 | .collect() |
| 2668 | } |
| 2669 | |
| 2670 | pub(super) fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) { |
| 2671 | if !self.is_copyable() { |
| 2672 | return; |
| 2673 | } |
| 2674 | |
| 2675 | let texts = self.selected_texts(); |
| 2676 | |
| 2677 | cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n"))); |
| 2678 | } |
| 2679 | |
| 2680 | pub(super) fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) { |
| 2681 | if !self.is_copyable() { |
| 2682 | return; |
| 2683 | } |
| 2684 | |
| 2685 | let texts = self.selected_texts(); |
| 2686 | |
| 2687 | cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n"))); |
| 2688 | |
| 2689 | self.undo_manager.set_pending_intent(EditIntent::Atomic); |
| 2690 | self.replace_text_in_range_silent(None, "", window, cx); |
| 2691 | } |
| 2692 | |
| 2693 | pub(super) fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) { |
| 2694 | if !self.is_editable() { |
| 2695 | return; |
| 2696 | } |
| 2697 | if let Some(clipboard) = cx.read_from_clipboard() { |
| 2698 | self.insert_clipboard(clipboard, window, cx); |
| 2699 | return; |
| 2700 | } |
| 2701 | // The synchronous read is empty on platforms whose clipboard is |
| 2702 | // asynchronous and permission-gated (the web), so fall back to the |
| 2703 | // real read. It has to start here, still inside the user activation |
| 2704 | // that dispatched `Paste`, or the browser refuses the read. |
| 2705 | let read = cx.read_from_clipboard_async(); |
| 2706 | let target = self.paste_target(); |
| 2707 | cx.spawn_in(window, async move |this, cx| match read.await { |
| 2708 | Ok(Some(clipboard)) => { |
| 2709 | this.update_in(cx, |this, window, cx| { |
| 2710 | // The read can sit behind a permission prompt for as |
| 2711 | // long as the user likes. If they edited, moved the |
| 2712 | // caret or left the input meanwhile, the paste would |
| 2713 | // land where they no longer mean it to; drop it, as the |
| 2714 | // browser's own paste event only reaches the focused |
| 2715 | // input too. |
| 2716 | if this.is_editable() |
| 2717 | && this.focus_handle.is_focused(window) |
| 2718 | && this.paste_target() == target |
| 2719 | { |
| 2720 | this.insert_clipboard(clipboard, window, cx); |
| 2721 | } |
| 2722 | }) |
| 2723 | .ok(); |
| 2724 | } |
| 2725 | Ok(None) => {} |
| 2726 | Err(error) => tracing::warn!("failed to read the clipboard for paste: {error}"), |
| 2727 | }) |
| 2728 | .detach(); |
| 2729 | } |
| 2730 | |
| 2731 | /// Where a paste would go right now: the document as edited so far and |
| 2732 | /// the selections it would replace. Two equal targets mean an edit made |
| 2733 | /// for one still applies to the other. |
| 2734 | fn paste_target(&self) -> PasteTarget { |
| 2735 | PasteTarget { |
| 2736 | document_revision: self.document_revision, |
| 2737 | selections: self.selections.iter().copied().collect(), |
| 2738 | } |
| 2739 | } |
| 2740 | |
| 2741 | /// Inserts the clipboard text the way `Paste` does: one atomic edit, |
| 2742 | /// newlines dropped on a single-line input, one line per selection when |
| 2743 | /// the counts match on a multi-line one. A clipboard without text (an |
| 2744 | /// image, say) is left alone rather than replacing the selection with |
| 2745 | /// nothing. |
| 2746 | fn insert_clipboard( |
| 2747 | &mut self, |
| 2748 | clipboard: ClipboardItem, |
| 2749 | window: &mut Window, |
| 2750 | cx: &mut Context<Self>, |
| 2751 | ) { |
| 2752 | let Some(mut new_text) = clipboard.text().filter(|text| !text.is_empty()) else { |
| 2753 | return; |
| 2754 | }; |
| 2755 | // A paste is one atomic edit, never part of a typing run. |
| 2756 | self.undo_manager.set_pending_intent(EditIntent::Atomic); |
| 2757 | |
| 2758 | if !self.is_multi_line() { |
| 2759 | new_text = new_text.replace('\n', ""); |
| 2760 | self.replace_text_in_range_silent(None, &new_text, window, cx); |
| 2761 | self.scroll_to(self.cursor(), None, cx); |
| 2762 | return; |
| 2763 | } |
| 2764 | |
| 2765 | // Distribute one clipboard line per selection when the counts match. |
| 2766 | // Otherwise insert the whole clipboard text at each cursor. |
| 2767 | if !self.selections.is_single() { |
| 2768 | self.selections.merge_overlapping(); |
| 2769 | } |
| 2770 | let lines: Vec<String> = new_text.split('\n').map(|s| s.to_string()).collect(); |
| 2771 | let count = self.selections.len(); |
| 2772 | if count > 1 && lines.len() == count { |
| 2773 | let mut selections: Vec<CursorSelection> = self.selections.iter().copied().collect(); |
| 2774 | selections.sort_by_key(|sel| sel.start); |
| 2775 | let edits: Vec<(Range<usize>, String)> = selections |
| 2776 | .iter() |
| 2777 | .zip(lines) |
| 2778 | .map(|(sel, line)| (sel.start..sel.end, line)) |
| 2779 | .collect(); |
| 2780 | self.replace_text_in_ranges(&edits, window, cx); |
| 2781 | } else { |
| 2782 | self.replace_text_in_range_silent(None, &new_text, window, cx); |
| 2783 | } |
| 2784 | self.scroll_to(self.cursor(), None, cx); |
| 2785 | } |
| 2786 | |
| 2787 | /// The intent of a batch the caller did not label: inserting text at |
| 2788 | /// collapsed cursors is typing, anything else stands on its own. |
| 2789 | fn typing_intent(&self, edits: &[(Range<usize>, String)], new_text: &str) -> EditIntent { |
| 2790 | if !new_text.is_empty() |
| 2791 | && !new_text.contains(['\n', '\r']) |
| 2792 | && edits.iter().all(|(range, _)| range.is_empty()) |
| 2793 | { |
| 2794 | EditIntent::Typing |
| 2795 | } else { |
| 2796 | EditIntent::Atomic |
| 2797 | } |
| 2798 | } |
| 2799 | |
| 2800 | /// Where a cursor stood before an edit made with this intent. |
| 2801 | /// |
| 2802 | /// Backspace and forward delete expand a collapsed cursor over the text |
| 2803 | /// they are about to remove, so the recorded cursor has to collapse back to |
| 2804 | /// the side it came from for undo to restore it where the user left it. |
| 2805 | fn collapse_for_intent( |
| 2806 | intent: EditIntent, |
| 2807 | mut selection: CursorSelection, |
| 2808 | range: &Range<usize>, |
| 2809 | ) -> CursorSelection { |
| 2810 | match intent { |
| 2811 | EditIntent::Backspace => selection.place_at(range.end, None), |
| 2812 | EditIntent::DeleteForward => selection.place_at(range.start, None), |
| 2813 | EditIntent::Typing | EditIntent::Atomic => {} |
| 2814 | } |
| 2815 | selection |
| 2816 | } |
| 2817 | |
| 2818 | /// Whether an edit rewrites the character before a collapsed cursor, as the |
| 2819 | /// macOS Korean IME does on each keystroke instead of marking text. |
| 2820 | fn rewrites_typed_char( |
| 2821 | &self, |
| 2822 | selection: CursorSelection, |
| 2823 | range: &Range<usize>, |
| 2824 | old_text: &str, |
| 2825 | new_text: &str, |
| 2826 | ) -> bool { |
| 2827 | !self.silent_replace_text |
| 2828 | && selection.is_collapsed() |
| 2829 | && selection.cursor_offset() == range.end |
| 2830 | && old_text.chars().count() == 1 |
| 2831 | && !old_text.contains(['\n', '\r']) |
| 2832 | && !new_text.contains(['\n', '\r']) |
| 2833 | } |
| 2834 | |
| 2835 | fn push_history( |
| 2836 | &mut self, |
| 2837 | text: &Rope, |
| 2838 | range: &Range<usize>, |
| 2839 | new_text: &str, |
| 2840 | requested_intent: Option<EditIntent>, |
| 2841 | selection_before: CursorSelection, |
| 2842 | selection_after: Option<CursorSelection>, |
| 2843 | ) -> bool { |
| 2844 | self.document_revision = self.document_revision.wrapping_add(1); |
| 2845 | let token_delta = self.edit_tokens(range, new_text.len()); |
| 2846 | if self.undo_manager.is_ignoring() { |
| 2847 | return false; |
| 2848 | } |
| 2849 | |
| 2850 | let range = |
| 2851 | text.clip_offset(range.start, Bias::Left)..text.clip_offset(range.end, Bias::Right); |
| 2852 | let old_text = text.slice(range.clone()).to_string(); |
| 2853 | let new_range = range.start..range.start + new_text.len(); |
| 2854 | |
| 2855 | let intent = requested_intent.unwrap_or_else(|| { |
| 2856 | if range.is_empty() |
| 2857 | && old_text.is_empty() |
| 2858 | && !new_text.is_empty() |
| 2859 | && !new_text.contains(['\n', '\r']) |
| 2860 | || self.rewrites_typed_char(selection_before, &range, &old_text, new_text) |
| 2861 | { |
| 2862 | EditIntent::Typing |
| 2863 | } else { |
| 2864 | EditIntent::Atomic |
| 2865 | } |
| 2866 | }); |
| 2867 | |
| 2868 | let selection_before = Self::collapse_for_intent(intent, selection_before, &range); |
| 2869 | let selection_after = |
| 2870 | selection_after.unwrap_or_else(|| (new_range.end..new_range.end).into()); |
| 2871 | |
| 2872 | let open_transaction = self.undo_manager.has_open_transaction(); |
| 2873 | let mut change = Change::new(range, &old_text, new_range, new_text); |
| 2874 | change.token_delta = token_delta; |
| 2875 | let recorded = self.undo_manager.record_transaction(change, intent); |
| 2876 | // A batch records its own cursor sets. This covers a change that is a |
| 2877 | // transaction on its own. |
| 2878 | if recorded && !open_transaction { |
| 2879 | self.undo_manager |
| 2880 | .record_selections(vec![selection_before], vec![selection_after]); |
| 2881 | } |
| 2882 | recorded |
| 2883 | } |
| 2884 | |
| 2885 | pub(super) fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) { |
| 2886 | self.replay_history(true, window, cx); |
| 2887 | } |
| 2888 | |
| 2889 | pub(super) fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) { |
| 2890 | self.replay_history(false, window, cx); |
| 2891 | } |
| 2892 | |
| 2893 | fn replay_history(&mut self, undo: bool, window: &mut Window, cx: &mut Context<Self>) { |
| 2894 | if !self.is_editable() { |
| 2895 | return; |
| 2896 | } |
| 2897 | let replay = if undo { |
| 2898 | self.undo_manager.undo() |
| 2899 | } else { |
| 2900 | self.undo_manager.redo() |
| 2901 | }; |
| 2902 | let Some(replay) = replay else { |
| 2903 | return; |
| 2904 | }; |
| 2905 | let token_aware = self.inline_tokens.is_some() |
| 2906 | || replay |
| 2907 | .changes |
| 2908 | .iter() |
| 2909 | .any(|change| change.token_delta.is_some()); |
| 2910 | let emit_events = self.emit_events; |
| 2911 | if token_aware { |
| 2912 | self.emit_events = false; |
| 2913 | } |
| 2914 | self.replaying_history = token_aware; |
| 2915 | self.undo_manager.set_ignoring(true); |
| 2916 | for change in &replay.changes { |
| 2917 | let (range, text) = if undo { |
| 2918 | (change.new_range.into(), &change.old_text) |
| 2919 | } else { |
| 2920 | (change.old_range.into(), &change.new_text) |
| 2921 | }; |
| 2922 | let range_utf16 = self.range_to_utf16(&range); |
| 2923 | self.replace_text_in_range_silent(Some(range_utf16), text, window, cx); |
| 2924 | self.replay_tokens(&range, text.len(), change.token_delta.as_deref(), undo); |
| 2925 | } |
| 2926 | self.restore_selections(replay.selections); |
| 2927 | self.mode |
| 2928 | .restore_auto_closed_pairs(replay.auto_closed_pairs.unwrap_or_default()); |
| 2929 | if token_aware { |
| 2930 | // Token replay bypasses IME normalization; a stale marked range |
| 2931 | // would otherwise describe text that no longer exists. |
| 2932 | self.ime_marked_range = None; |
| 2933 | } |
| 2934 | self.undo_manager.set_ignoring(false); |
| 2935 | self.replaying_history = false; |
| 2936 | self.emit_events = emit_events; |
| 2937 | if token_aware && emit_events { |
| 2938 | cx.emit(InputEvent::Change); |
| 2939 | } |
| 2940 | cx.notify(); |
| 2941 | } |
| 2942 | |
| 2943 | /// Restore a set of selections captured in a transaction, clamping offsets |
| 2944 | /// to the current text length. `None` leaves the current selections as the |
| 2945 | /// replay left them. |
| 2946 | fn restore_selections(&mut self, selections: Option<Vec<CursorSelection>>) { |
| 2947 | let Some(selections) = selections else { |
| 2948 | return; |
| 2949 | }; |
| 2950 | |
| 2951 | let len = self.text.len(); |
| 2952 | let restored: Vec<CursorSelection> = selections |
| 2953 | .into_iter() |
| 2954 | .map(|mut sel| { |
| 2955 | sel.start = sel.start.min(len); |
| 2956 | sel.end = sel.end.min(len); |
| 2957 | sel |
| 2958 | }) |
| 2959 | .collect(); |
| 2960 | self.selections.replace_all(restored); |
| 2961 | self.selections.merge_overlapping(); |
| 2962 | } |
| 2963 | |
| 2964 | /// Get byte offset of the cursor. |
| 2965 | /// |
| 2966 | /// The offset is the UTF-8 offset. |
| 2967 | pub fn cursor(&self) -> usize { |
| 2968 | if let Some(ime_marked_range) = &self.ime_marked_range { |
| 2969 | return ime_marked_range.end; |
| 2970 | } |
| 2971 | |
| 2972 | self.selections.active().cursor_offset() |
| 2973 | } |
| 2974 | |
| 2975 | /// Returns the active selection. |
| 2976 | pub(super) fn active_selection(&self) -> &CursorSelection { |
| 2977 | self.selections.active() |
| 2978 | } |
| 2979 | |
| 2980 | /// Returns a mutable reference to the active selection. |
| 2981 | pub(super) fn active_selection_mut(&mut self) -> &mut CursorSelection { |
| 2982 | self.selections.active_mut() |
| 2983 | } |
| 2984 | |
| 2985 | /// Sets the active selection to the given range, keeping its `reversed` |
| 2986 | /// and `column_anchor` state untouched. |
| 2987 | pub(super) fn set_selection(&mut self, start: usize, end: usize) { |
| 2988 | let range = self.normalize_token_range(start..end); |
| 2989 | let (start, end) = (range.start, range.end); |
| 2990 | let active = self.active_selection_mut(); |
| 2991 | active.start = start; |
| 2992 | active.end = end; |
| 2993 | } |
| 2994 | |
| 2995 | /// Collapses the active selection to a cursor at the given offset, |
| 2996 | /// clearing `reversed`. |
| 2997 | pub(super) fn set_cursor_to(&mut self, offset: usize) { |
| 2998 | let offset = self.token_boundary(offset, Bias::Right); |
| 2999 | let active = self.active_selection_mut(); |
| 3000 | active.start = offset; |
| 3001 | active.end = offset; |
| 3002 | active.reversed = false; |
| 3003 | } |
| 3004 | |
| 3005 | /// Visible row range in the last laid-out viewport, `None` before first layout. |
| 3006 | pub fn visible_row_range(&self) -> Option<std::ops::Range<usize>> { |
| 3007 | self.last_layout.as_ref().map(|l| l.visible_range.clone()) |
| 3008 | } |
| 3009 | |
| 3010 | /// Current scroll offset of the editor viewport. |
| 3011 | pub fn scroll_offset(&self) -> gpui::Point<gpui::Pixels> { |
| 3012 | self.scroll_handle.offset() |
| 3013 | } |
| 3014 | |
| 3015 | /// Set scroll offset of the editor viewport. |
| 3016 | /// |
| 3017 | /// The offset will be clamped to the valid range, and applied after the next layout. |
| 3018 | pub fn set_scroll_offset(&mut self, offset: gpui::Point<gpui::Pixels>, cx: &mut Context<Self>) { |
| 3019 | self.deferred_scroll_offset = Some(offset); |
| 3020 | cx.notify(); |
| 3021 | } |
| 3022 | |
| 3023 | /// Laid-out line height; `None` before first layout. |
| 3024 | pub fn line_height(&self) -> Option<gpui::Pixels> { |
| 3025 | self.last_layout.as_ref().map(|l| l.line_height) |
| 3026 | } |
| 3027 | |
| 3028 | /// Returns the active selection as a byte range into the text. |
| 3029 | /// |
| 3030 | /// With multiple cursors, this reads only the active selection. |
| 3031 | /// |
| 3032 | /// The range is empty (`start == end`) when no text is selected; in |
| 3033 | /// that case the offset equals `cursor()`. Byte offsets are measured |
| 3034 | /// in the underlying rope's byte units. |
| 3035 | pub fn selected_range(&self) -> std::ops::Range<usize> { |
| 3036 | (*self.selections.active()).into() |
| 3037 | } |
| 3038 | |
| 3039 | pub fn select_all(&mut self, _: &mut Window, cx: &mut Context<Self>) { |
| 3040 | self.undo_manager.break_transaction_coalescing(); |
| 3041 | self.selections.remove_all_but_active(); |
| 3042 | self.set_selection(0, self.text.len()); |
| 3043 | cx.notify(); |
| 3044 | } |
| 3045 | |
| 3046 | /// Set the selected range using UTF-8 byte offsets, removing additional cursors. |
| 3047 | /// |
| 3048 | /// Non-empty ranges expand to character boundaries. Empty ranges remain empty and are |
| 3049 | /// clipped to the preceding character boundary. |
| 3050 | pub fn set_selected_range(&mut self, range: Range<usize>, cx: &mut Context<Self>) { |
| 3051 | let range = self.normalize_token_range(range); |
| 3052 | let end_bias = if range.start == range.end { |
| 3053 | Bias::Left |
| 3054 | } else { |
| 3055 | Bias::Right |
| 3056 | }; |
| 3057 | let start = self.text.clip_offset(range.start, Bias::Left); |
| 3058 | let end = self.text.clip_offset(range.end, end_bias); |
| 3059 | |
| 3060 | self.move_to(start, None, cx); |
| 3061 | self.active_selection_mut().reversed = false; |
| 3062 | self.selected_word_range = None; |
| 3063 | self.select_to(end, cx); |
| 3064 | } |
| 3065 | |
| 3066 | /// Resolve a mouse position to a byte offset in the text. |
| 3067 | /// |
| 3068 | /// Also reports the caret's line-end affinity for that offset: `true` when the position |
| 3069 | /// landed on the wrap boundary of a non-final visual row, meaning the caret belongs at the |
| 3070 | /// end of that row rather than at the start of the next one. Callers that place or extend a |
| 3071 | /// selection must pass it on, or clicking past the last glyph of a wrapped row leaves a |
| 3072 | /// caret one row below the pointer. |
| 3073 | pub(crate) fn index_for_mouse_position(&self, position: Point<Pixels>) -> (usize, bool) { |
| 3074 | let (offset, line_end_affinity, _) = self.resolve_mouse_position(position); |
| 3075 | (offset, line_end_affinity) |
| 3076 | } |
| 3077 | |
| 3078 | /// Resolve a mouse position to a text offset, the caret affinity to use for it, and |
| 3079 | /// how many columns the pointer sits past the end of that row. |
| 3080 | /// |
| 3081 | /// Only a columnar selection needs the third value; everywhere else a position past |
| 3082 | /// the end of a row means the end of that row, and |
| 3083 | /// [`Self::index_for_mouse_position`] is the call to make. |
| 3084 | pub(super) fn resolve_mouse_position(&self, position: Point<Pixels>) -> (usize, bool, usize) { |
| 3085 | // If the text is empty, always return 0 |
| 3086 | if self.text.len() == 0 { |
| 3087 | return (0, false, 0); |
| 3088 | } |
| 3089 | |
| 3090 | let (Some(bounds), Some(last_layout)) = |
| 3091 | (self.last_bounds.as_ref(), self.last_layout.as_ref()) |
| 3092 | else { |
| 3093 | return (0, false, 0); |
| 3094 | }; |
| 3095 | |
| 3096 | let line_height = last_layout.line_height; |
| 3097 | let line_number_width = last_layout.line_number_width; |
| 3098 | |
| 3099 | // TIP: About the IBeam cursor |
| 3100 | // |
| 3101 | // If cursor style is IBeam, the mouse mouse position is in the middle of the cursor (This is special in OS) |
| 3102 | |
| 3103 | // The position is relative to the bounds of the text input |
| 3104 | // |
| 3105 | // bounds.origin: |
| 3106 | // |
| 3107 | // - included the input padding. |
| 3108 | // - included the scroll offset. |
| 3109 | let inner_position = position - bounds.origin - point(line_number_width, px(0.)); |
| 3110 | |
| 3111 | let mut y_offset = last_layout.visible_top; |
| 3112 | // Position relative to the last line walked, kept for a pointer that ends up |
| 3113 | // below every line. |
| 3114 | let mut last_line_pos = None; |
| 3115 | |
| 3116 | // Traverse visible buffer lines (compact, no hidden entries) |
| 3117 | for (vi, (line_layout, _buffer_line)) in last_layout |
| 3118 | .lines |
| 3119 | .iter() |
| 3120 | .zip(last_layout.visible_buffer_lines.iter()) |
| 3121 | .enumerate() |
| 3122 | { |
| 3123 | let line_start_offset = last_layout.visible_line_byte_offsets[vi]; |
| 3124 | |
| 3125 | // Calculate line origin for this display row |
| 3126 | let line_origin = point(px(0.), y_offset); |
| 3127 | let pos = inner_position - line_origin; |
| 3128 | |
| 3129 | // Return offset by use closest_index_for_x if is single line mode. |
| 3130 | if self.is_single_line() { |
| 3131 | let local_index = line_layout.closest_index_for_x(pos.x, last_layout); |
| 3132 | // A single line never wraps, so there is no boundary to disambiguate. |
| 3133 | return ( |
| 3134 | self.resolve_index(line_start_offset + local_index), |
| 3135 | false, |
| 3136 | 0, |
| 3137 | ); |
| 3138 | } |
| 3139 | |
| 3140 | // Check if mouse is in this line's bounds |
| 3141 | if let Some((local_index, line_end_affinity)) = |
| 3142 | line_layout.closest_index_for_position(pos, last_layout) |
| 3143 | { |
| 3144 | return ( |
| 3145 | self.resolve_index(line_start_offset + local_index), |
| 3146 | line_end_affinity, |
| 3147 | line_layout.columns_past_line_end(pos, last_layout), |
| 3148 | ); |
| 3149 | } else if pos.y < px(0.) { |
| 3150 | // Mouse is above this line, return start of this line |
| 3151 | return (self.resolve_index(line_start_offset), false, 0); |
| 3152 | } |
| 3153 | |
| 3154 | y_offset += line_layout.size(line_height).height; |
| 3155 | last_line_pos = Some(pos); |
| 3156 | } |
| 3157 | |
| 3158 | // Clamp to the last laid-out row. Returning the end of the whole document |
| 3159 | // would select unseen text before drag autoscroll has reached it. |
| 3160 | let last_position = last_layout |
| 3161 | .lines |
| 3162 | .last() |
| 3163 | .zip(last_line_pos) |
| 3164 | .zip(last_layout.visible_line_byte_offsets.last()) |
| 3165 | .map(|((line_layout, pos), line_start)| { |
| 3166 | let last_row_top = line_layout.row_top( |
| 3167 | line_layout.wrapped_lines.len().saturating_sub(1), |
| 3168 | line_height, |
| 3169 | ); |
| 3170 | let pos = point(pos.x, last_row_top); |
| 3171 | ( |
| 3172 | self.resolve_index(line_start + line_layout.len()), |
| 3173 | false, |
| 3174 | line_layout.columns_past_line_end(pos, last_layout), |
| 3175 | ) |
| 3176 | }); |
| 3177 | |
| 3178 | last_position.unwrap_or((self.text.len(), false, 0)) |
| 3179 | } |
| 3180 | |
| 3181 | /// Map a display byte index back to a text offset, undoing the mask expansion when the input |
| 3182 | /// is masked. |
| 3183 | fn resolve_index(&self, index: usize) -> usize { |
| 3184 | if self.masked { |
| 3185 | self.text.char_index_to_offset(index / MASK_CHAR.len_utf8()) |
| 3186 | } else { |
| 3187 | index.min(self.text.len()) |
| 3188 | } |
| 3189 | } |
| 3190 | |
| 3191 | /// Returns a y offsetted point for the line origin. |
| 3192 | /// Select the text from the current cursor position to the given offset. |
| 3193 | /// |
| 3194 | /// The offset is the UTF-8 offset. |
| 3195 | /// |
| 3196 | /// Ensure the offset use self.next_boundary or self.previous_boundary to get the correct offset. |
| 3197 | /// Extend a single selection so its moving end lands at `offset`, flipping |
| 3198 | /// `reversed` when the ends cross. When a sticky `word_range` is given the |
| 3199 | /// selection is kept covering it. |
| 3200 | fn extend_selection( |
| 3201 | sel: &mut CursorSelection, |
| 3202 | offset: usize, |
| 3203 | word_range: Option<CursorSelection>, |
| 3204 | ) { |
| 3205 | if sel.reversed { |
| 3206 | sel.start = offset; |
| 3207 | } else { |
| 3208 | sel.end = offset; |
| 3209 | } |
| 3210 | |
| 3211 | if sel.end < sel.start { |
| 3212 | sel.reversed = !sel.reversed; |
| 3213 | std::mem::swap(&mut sel.start, &mut sel.end); |
| 3214 | } |
| 3215 | |
| 3216 | if let Some(word_range) = word_range { |
| 3217 | if sel.start > word_range.start { |
| 3218 | sel.start = word_range.start; |
| 3219 | } |
| 3220 | if sel.end < word_range.end { |
| 3221 | sel.end = word_range.end; |
| 3222 | } |
| 3223 | } |
| 3224 | } |
| 3225 | |
| 3226 | /// Extend only the active selection to `offset`. Used by mouse drag. |
| 3227 | pub(crate) fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) { |
| 3228 | self.select_to_with_affinity(offset, false, cx); |
| 3229 | } |
| 3230 | |
| 3231 | /// Like [`Self::select_to`], but also carries the caret's line-end affinity. |
| 3232 | /// |
| 3233 | /// See [`Self::move_to_with_affinity`] for why the affinity travels with the offset. Note |
| 3234 | /// that plain [`Self::select_to`] clears the affinity: every offset it is given came from |
| 3235 | /// the text rather than from a visual position, so the caret has no reason to keep sticking |
| 3236 | /// to the end of a wrapped row. |
| 3237 | pub(crate) fn select_to_with_affinity( |
| 3238 | &mut self, |
| 3239 | offset: usize, |
| 3240 | line_end_affinity: bool, |
| 3241 | cx: &mut Context<Self>, |
| 3242 | ) { |
| 3243 | M::clear_inline_completion(self, cx); |
| 3244 | |
| 3245 | self.cursor_line_end_affinity = line_end_affinity; |
| 3246 | let offset = self.cursor_boundary(offset, Bias::Left); |
| 3247 | let word_range = self.selected_word_range; |
| 3248 | Self::extend_selection(self.active_selection_mut(), offset, word_range); |
| 3249 | let range = self.normalize_token_range(self.selected_range()); |
| 3250 | self.set_selection(range.start, range.end); |
| 3251 | |
| 3252 | if self.active_selection().is_empty() { |
| 3253 | self.update_preferred_column(); |
| 3254 | } |
| 3255 | cx.notify() |
| 3256 | } |
| 3257 | |
| 3258 | /// Extend every selection to the offset produced by `f`, then merge any |
| 3259 | /// selections that now overlap. Used by keyboard selection commands. |
| 3260 | fn select_all_cursors_to( |
| 3261 | &mut self, |
| 3262 | f: impl Fn(&Self, &CursorSelection) -> usize, |
| 3263 | cx: &mut Context<Self>, |
| 3264 | ) { |
| 3265 | self.select_all_cursors_to_with_affinity(|s, sel| (f(s, sel), false), false, cx); |
| 3266 | } |
| 3267 | |
| 3268 | /// Extend selections with caret affinity, preserving their column anchors even |
| 3269 | /// when vertical movement collapses a selection to a cursor. |
| 3270 | fn select_all_cursors_to_with_affinity( |
| 3271 | &mut self, |
| 3272 | f: impl Fn(&Self, &CursorSelection) -> (usize, bool), |
| 3273 | preserve_column: bool, |
| 3274 | cx: &mut Context<Self>, |
| 3275 | ) { |
| 3276 | self.pause_blink_cursor(cx); |
| 3277 | self.undo_manager.break_transaction_coalescing(); |
| 3278 | M::clear_inline_completion(self, cx); |
| 3279 | |
| 3280 | let mut active_affinity = false; |
| 3281 | let new_selections: Vec<CursorSelection> = self |
| 3282 | .selections |
| 3283 | .iter() |
| 3284 | .map(|sel| { |
| 3285 | let (offset, affinity) = f(self, sel); |
| 3286 | if sel.id == self.active_selection().id { |
| 3287 | active_affinity = affinity; |
| 3288 | } |
| 3289 | let offset = self.cursor_boundary(offset, Bias::Left); |
| 3290 | let mut new_sel = *sel; |
| 3291 | Self::extend_selection(&mut new_sel, offset, None); |
| 3292 | let range = self.normalize_token_range(new_sel.start..new_sel.end); |
| 3293 | new_sel.start = range.start; |
| 3294 | new_sel.end = range.end; |
| 3295 | if !preserve_column { |
| 3296 | new_sel.column_anchor = |
| 3297 | self.preferred_column_for_with_affinity(new_sel.cursor_offset(), affinity); |
| 3298 | } else if new_sel.column_anchor.is_none() { |
| 3299 | new_sel.column_anchor = self.preferred_column_for_with_affinity( |
| 3300 | sel.cursor_offset(), |
| 3301 | self.line_end_affinity_for(sel), |
| 3302 | ); |
| 3303 | } |
| 3304 | new_sel |
| 3305 | }) |
| 3306 | .collect(); |
| 3307 | self.cursor_line_end_affinity = active_affinity; |
| 3308 | self.selections.replace_all(new_selections); |
| 3309 | self.selections.merge_overlapping(); |
| 3310 | |
| 3311 | self.scroll_to(self.cursor(), None, cx); |
| 3312 | cx.notify() |
| 3313 | } |
| 3314 | |
| 3315 | /// Unselects the currently selected text. |
| 3316 | pub fn unselect(&mut self, _: &mut Window, cx: &mut Context<Self>) { |
| 3317 | self.undo_manager.break_transaction_coalescing(); |
| 3318 | let offset = self.cursor(); |
| 3319 | self.set_cursor_to(offset); |
| 3320 | cx.notify() |
| 3321 | } |
| 3322 | |
| 3323 | #[inline] |
| 3324 | pub(super) fn offset_from_utf16(&self, offset: usize) -> usize { |
| 3325 | self.text.offset_utf16_to_offset(offset) |
| 3326 | } |
| 3327 | |
| 3328 | #[inline] |
| 3329 | pub(super) fn offset_to_utf16(&self, offset: usize) -> usize { |
| 3330 | self.text.offset_to_offset_utf16(offset) |
| 3331 | } |
| 3332 | |
| 3333 | #[inline] |
| 3334 | pub(crate) fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> { |
| 3335 | self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end) |
| 3336 | } |
| 3337 | |
| 3338 | #[inline] |
| 3339 | pub(super) fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> { |
| 3340 | self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end) |
| 3341 | } |
| 3342 | |
| 3343 | /// If offset falls on a hidden (folded) line, clamp backward to the end of |
| 3344 | /// the fold header line (last visible position before the fold). |
| 3345 | fn clamp_offset_to_visible_backward(&self, offset: usize) -> usize { |
| 3346 | let line = self.text.offset_to_point(offset).row; |
| 3347 | if self.display_map.is_buffer_line_hidden(line) { |
| 3348 | for fold in self.display_map.folded_ranges() { |
| 3349 | if line > fold.start_line && line <= fold.end_line { |
| 3350 | return self.text.line_end_offset(fold.start_line); |
| 3351 | } |
| 3352 | } |
| 3353 | } |
| 3354 | offset |
| 3355 | } |
| 3356 | |
| 3357 | /// If offset falls on a hidden (folded) line, clamp forward to the start of |
| 3358 | /// the fold end line (first visible position after the fold). |
| 3359 | fn clamp_offset_to_visible_forward(&self, offset: usize) -> usize { |
| 3360 | let line = self.text.offset_to_point(offset).row; |
| 3361 | if self.display_map.is_buffer_line_hidden(line) { |
| 3362 | for fold in self.display_map.folded_ranges() { |
| 3363 | if line > fold.start_line && line <= fold.end_line { |
| 3364 | return self.text.line_start_offset(fold.end_line); |
| 3365 | } |
| 3366 | } |
| 3367 | } |
| 3368 | offset |
| 3369 | } |
| 3370 | |
| 3371 | /// Clip a cursor/selection offset without splitting a CRLF newline. This does |
| 3372 | /// not alter the rope or its byte/UTF-16 conversion used for exact source APIs. |
| 3373 | pub(super) fn cursor_boundary(&self, offset: usize, bias: Bias) -> usize { |
| 3374 | let offset = self.token_boundary(self.text.clip_offset(offset, bias), bias); |
| 3375 | if offset > 0 |
| 3376 | && self.text.char_at(offset - 1) == Some('\r') |
| 3377 | && self.text.char_at(offset) == Some('\n') |
| 3378 | { |
| 3379 | if bias == Bias::Left { |
| 3380 | offset - 1 |
| 3381 | } else { |
| 3382 | offset + 1 |
| 3383 | } |
| 3384 | } else { |
| 3385 | offset |
| 3386 | } |
| 3387 | } |
| 3388 | |
| 3389 | pub(super) fn previous_boundary(&self, offset: usize) -> usize { |
| 3390 | let offset = self.cursor_boundary(offset.saturating_sub(1), Bias::Left); |
| 3391 | self.clamp_offset_to_visible_backward(offset) |
| 3392 | } |
| 3393 | |
| 3394 | pub(super) fn next_boundary(&self, offset: usize) -> usize { |
| 3395 | let offset = self.cursor_boundary(offset.saturating_add(1), Bias::Right); |
| 3396 | self.clamp_offset_to_visible_forward(offset) |
| 3397 | } |
| 3398 | |
| 3399 | /// Returns the true to let InputElement to render cursor, when Input is focused and current BlinkCursor is visible. |
| 3400 | pub(crate) fn show_cursor(&self, window: &Window, cx: &App) -> bool { |
| 3401 | (self.focus_handle.is_focused(window) || M::is_context_menu_open(self, cx)) |
| 3402 | && !self.disabled |
| 3403 | && self.blink_cursor.read(cx).visible() |
| 3404 | && window.is_window_active() |
| 3405 | } |
| 3406 | |
| 3407 | fn on_focus(&mut self, _: &mut Window, cx: &mut Context<Self>) { |
| 3408 | self.blink_cursor.update(cx, |cursor, cx| { |
| 3409 | cursor.start(cx); |
| 3410 | }); |
| 3411 | cx.emit(InputEvent::Focus); |
| 3412 | } |
| 3413 | |
| 3414 | fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 3415 | if M::is_context_menu_open(self, cx) { |
| 3416 | return; |
| 3417 | } |
| 3418 | |
| 3419 | M::hide_context_menu(self, cx); |
| 3420 | self.undo_manager.break_transaction_coalescing(); |
| 3421 | |
| 3422 | // NOTE: Do not cancel select, when blur. |
| 3423 | // Because maybe user want to copy the selected text by AppMenuBar (will take focus handle). |
| 3424 | |
| 3425 | M::clear_hover_state(self, cx); |
| 3426 | self.diagnostic_popover = None; |
| 3427 | M::clear_inline_completion(self, cx); |
| 3428 | self.dismiss_touch_selection(cx); |
| 3429 | self.blink_cursor.update(cx, |cursor, cx| { |
| 3430 | cursor.stop(cx); |
| 3431 | }); |
| 3432 | self.clamp_number_value(window, cx); |
| 3433 | cx.emit(InputEvent::Blur); |
| 3434 | cx.notify(); |
| 3435 | } |
| 3436 | |
| 3437 | /// Clamp the number value to the `min`/`max` range, used on blur. |
| 3438 | /// |
| 3439 | /// Out-of-range values are allowed while typing (e.g. `1` is an |
| 3440 | /// intermediate state of `15` when min is 10), and clamped on blur. |
| 3441 | fn clamp_number_value(&mut self, window: &mut Window, cx: &mut Context<Self>) { |
| 3442 | if !self.is_single_line() { |
| 3443 | return; |
| 3444 | } |
| 3445 | if !matches!(self.mask_pattern, MaskPattern::Number { .. }) { |
| 3446 | return; |
| 3447 | } |
| 3448 | if self.number_min.is_none() && self.number_max.is_none() { |
| 3449 | return; |
| 3450 | } |
| 3451 | |
| 3452 | let Ok(value) = self.unmask_value().parse::<f64>() else { |
| 3453 | return; |
| 3454 | }; |
| 3455 | |
| 3456 | let clamped = match (self.number_min, self.number_max) { |
| 3457 | (Some(min), _) if value < min => min, |
| 3458 | (_, Some(max)) if value > max => max, |
| 3459 | _ => return, |
| 3460 | }; |
| 3461 | |
| 3462 | // The clamped value must pass the `pattern`/`validate` check, |
| 3463 | // otherwise keep the value as is. |
| 3464 | let new_text = clamped.to_string(); |
| 3465 | if !self.is_valid_input(&new_text, cx) { |
| 3466 | return; |
| 3467 | } |
| 3468 | |
| 3469 | let range = self.range_to_utf16(&(0..self.text.len())); |
| 3470 | self.replace_text_in_range_silent(Some(range), &new_text, window, cx); |
| 3471 | } |
| 3472 | |
| 3473 | pub(super) fn pause_blink_cursor(&mut self, cx: &mut Context<Self>) { |
| 3474 | self.blink_cursor.update(cx, |cursor, cx| { |
| 3475 | cursor.pause(cx); |
| 3476 | }); |
| 3477 | } |
| 3478 | |
| 3479 | pub(super) fn on_drag_move( |
| 3480 | &mut self, |
| 3481 | event: &MouseMoveEvent, |
| 3482 | window: &mut Window, |
| 3483 | cx: &mut Context<Self>, |
| 3484 | ) { |
| 3485 | if self.text.len() == 0 { |
| 3486 | return; |
| 3487 | } |
| 3488 | |
| 3489 | if self.last_layout.is_none() { |
| 3490 | return; |
| 3491 | } |
| 3492 | |
| 3493 | if !self.focus_handle.is_focused(window) { |
| 3494 | return; |
| 3495 | } |
| 3496 | |
| 3497 | if !self.selecting { |
| 3498 | return; |
| 3499 | } |
| 3500 | |
| 3501 | self.auto_scroll.last_drag_position = Some(event.position); |
| 3502 | let (offset, line_end_affinity, columns_past_line_end) = |
| 3503 | self.resolve_mouse_position(event.position); |
| 3504 | if let Some(start) = self.column_select_start { |
| 3505 | let end = ColumnarPoint::new(offset, columns_past_line_end); |
| 3506 | self.build_columnar_selection(start, end, cx); |
| 3507 | } else { |
| 3508 | self.select_to_with_affinity(offset, line_end_affinity, cx); |
| 3509 | } |
| 3510 | |
| 3511 | if !self.is_single_line() { |
| 3512 | let delta = AutoScroll::compute_delta(event.position.y, self.input_bounds); |
| 3513 | // Input's ScrollHandle uses negative-y-is-down; negate the positive-towards-bottom delta. |
| 3514 | let scroll_delta = delta.map(|d| -d); |
| 3515 | self.auto_scroll.set(scroll_delta, cx, |delta, state, cx| { |
| 3516 | let current = state.scroll_handle.offset(); |
| 3517 | state.update_scroll_offset(Some(point(current.x, current.y + delta)), cx); |
| 3518 | if let Some(pos) = state.auto_scroll.last_drag_position { |
| 3519 | let (offset, line_end_affinity, columns_past_line_end) = |
| 3520 | state.resolve_mouse_position(pos); |
| 3521 | if let Some(start) = state.column_select_start { |
| 3522 | let end = ColumnarPoint::new(offset, columns_past_line_end); |
| 3523 | state.build_columnar_selection(start, end, cx); |
| 3524 | } else { |
| 3525 | state.select_to_with_affinity(offset, line_end_affinity, cx); |
| 3526 | } |
| 3527 | } |
| 3528 | }); |
| 3529 | } |
| 3530 | } |
| 3531 | |
| 3532 | /// Normalize the inserted text before applying it to the input. |
| 3533 | /// |
| 3534 | /// For number inputs (with [`MaskPattern::Number`]), this converts |
| 3535 | /// full-width number characters into their ASCII equivalents, |
| 3536 | /// e.g. `12。5` -> `12.5`. |
| 3537 | pub(super) fn normalize_input<'a>(&self, new_text: &'a str) -> Cow<'a, str> { |
| 3538 | let normalized = if matches!(self.mask_pattern, MaskPattern::Number { .. }) { |
| 3539 | normalize_number_input(new_text) |
| 3540 | } else { |
| 3541 | Cow::Borrowed(new_text) |
| 3542 | }; |
| 3543 | |
| 3544 | if self.is_single_line() && normalized.contains(['\n', '\r']) { |
| 3545 | Cow::Owned(normalized.replace(['\n', '\r'], "")) |
| 3546 | } else { |
| 3547 | normalized |
| 3548 | } |
| 3549 | } |
| 3550 | |
| 3551 | pub(crate) fn is_valid_input(&self, new_text: &str, cx: &mut Context<Self>) -> bool { |
| 3552 | if new_text.is_empty() { |
| 3553 | return true; |
| 3554 | } |
| 3555 | |
| 3556 | if let Some(validate) = &self.validate { |
| 3557 | if !validate(new_text, cx) { |
| 3558 | return false; |
| 3559 | } |
| 3560 | } |
| 3561 | |
| 3562 | if !self.mask_pattern.is_valid(new_text) { |
| 3563 | return false; |
| 3564 | } |
| 3565 | |
| 3566 | let Some(pattern) = &self.pattern else { |
| 3567 | return true; |
| 3568 | }; |
| 3569 | |
| 3570 | pattern.is_match(new_text) |
| 3571 | } |
| 3572 | |
| 3573 | /// Set the mask pattern for formatting the input text. |
| 3574 | /// |
| 3575 | /// The pattern can contain: |
| 3576 | /// - 9: Any digit or dot |
| 3577 | /// - A: Any letter |
| 3578 | /// - *: Any character |
| 3579 | /// - Other characters will be treated as literal mask characters |
| 3580 | /// |
| 3581 | /// Example: "(999)999-999" for phone numbers |
| 3582 | pub fn mask_pattern(mut self, pattern: impl Into<MaskPattern>) -> Self { |
| 3583 | self.mask_pattern = pattern.into(); |
| 3584 | self.mask_pattern_set = true; |
| 3585 | if let Some(placeholder) = self.mask_pattern.placeholder() { |
| 3586 | self.placeholder = placeholder.into(); |
| 3587 | } |
| 3588 | self |
| 3589 | } |
| 3590 | |
| 3591 | pub fn set_mask_pattern( |
| 3592 | &mut self, |
| 3593 | pattern: impl Into<MaskPattern>, |
| 3594 | _: &mut Window, |
| 3595 | cx: &mut Context<Self>, |
| 3596 | ) { |
| 3597 | self.mask_pattern = pattern.into(); |
| 3598 | self.mask_pattern_set = true; |
| 3599 | if let Some(placeholder) = self.mask_pattern.placeholder() { |
| 3600 | self.placeholder = placeholder.into(); |
| 3601 | } |
| 3602 | cx.notify(); |
| 3603 | } |
| 3604 | |
| 3605 | /// Apply the default numeric mask unless the caller explicitly selected a mask. |
| 3606 | pub fn ensure_number_mask(&mut self) { |
| 3607 | if self.mask_pattern_set { |
| 3608 | return; |
| 3609 | } |
| 3610 | self.mask_pattern = MaskPattern::Number { |
| 3611 | separator: None, |
| 3612 | fraction: None, |
| 3613 | }; |
| 3614 | } |
| 3615 | |
| 3616 | pub(super) fn set_input_bounds(&mut self, new_bounds: Bounds<Pixels>, cx: &mut Context<Self>) { |
| 3617 | let wrap_width_changed = self.input_bounds.size.width != new_bounds.size.width; |
| 3618 | self.input_bounds = new_bounds; |
| 3619 | |
| 3620 | // Update display_map wrap_width if changed. |
| 3621 | if let Some(last_layout) = self.last_layout.as_ref() { |
| 3622 | if wrap_width_changed { |
| 3623 | let wrap_width = if !self.soft_wrap { |
| 3624 | // None to disable wrapping (will use Pixels::MAX) |
| 3625 | None |
| 3626 | } else { |
| 3627 | last_layout.wrap_width |
| 3628 | }; |
| 3629 | |
| 3630 | self.display_map.on_layout_changed(wrap_width, cx); |
| 3631 | if self.is_multi_line() { |
| 3632 | self.mode |
| 3633 | .update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.))); |
| 3634 | } |
| 3635 | cx.notify(); |
| 3636 | } |
| 3637 | } |
| 3638 | } |
| 3639 | |
| 3640 | /// Return the active selection's text, borrowed out of the [`Rope`] |
| 3641 | /// the state owns. |
| 3642 | /// |
| 3643 | /// See [`Self::selected_value`] when an owned string is wanted. |
| 3644 | pub fn selected_text(&self) -> RopeSlice<'_> { |
| 3645 | let range_utf16 = self.range_to_utf16(&self.selected_range()); |
| 3646 | let range = self.range_from_utf16(&range_utf16); |
| 3647 | self.text.slice(range) |
| 3648 | } |
| 3649 | |
| 3650 | /// Return the rendered bounds for a UTF-8 byte range in the current input contents. |
| 3651 | /// |
| 3652 | /// Returns `None` when the requested range is not currently laid out or visible. |
| 3653 | pub fn range_to_bounds(&self, range: &Range<usize>) -> Option<Bounds<Pixels>> { |
| 3654 | let Some(last_layout) = self.last_layout.as_ref() else { |
| 3655 | return None; |
| 3656 | }; |
| 3657 | |
| 3658 | let Some(last_bounds) = self.last_bounds else { |
| 3659 | return None; |
| 3660 | }; |
| 3661 | |
| 3662 | let (_, _, start_pos) = self.line_and_position_for_offset(range.start); |
| 3663 | let (_, _, end_pos) = self.line_and_position_for_offset(range.end); |
| 3664 | |
| 3665 | let Some(start_pos) = start_pos else { |
| 3666 | return None; |
| 3667 | }; |
| 3668 | let Some(end_pos) = end_pos else { |
| 3669 | return None; |
| 3670 | }; |
| 3671 | |
| 3672 | Some(Bounds::from_corners( |
| 3673 | last_bounds.origin + start_pos, |
| 3674 | last_bounds.origin + end_pos + point(px(0.), last_layout.line_height), |
| 3675 | )) |
| 3676 | } |
| 3677 | |
| 3678 | /// Replace text in range in silent. |
| 3679 | /// |
| 3680 | /// This will not trigger any UI interaction, such as auto-completion. |
| 3681 | pub(crate) fn replace_text_in_range_silent( |
| 3682 | &mut self, |
| 3683 | range_utf16: Option<Range<usize>>, |
| 3684 | new_text: &str, |
| 3685 | window: &mut Window, |
| 3686 | cx: &mut Context<Self>, |
| 3687 | ) { |
| 3688 | self.silent_replace_text = true; |
| 3689 | self.replace_text_in_range(range_utf16, new_text, window, cx); |
| 3690 | self.silent_replace_text = false; |
| 3691 | } |
| 3692 | |
| 3693 | /// Apply a batch of edits as one atomic history transaction. |
| 3694 | /// |
| 3695 | /// `edits` are `(byte range in the current pre-edit document, replacement)` |
| 3696 | /// pairs. |
| 3697 | pub(crate) fn replace_text_in_ranges( |
| 3698 | &mut self, |
| 3699 | edits: &[(Range<usize>, String)], |
| 3700 | window: &mut Window, |
| 3701 | cx: &mut Context<Self>, |
| 3702 | ) { |
| 3703 | if !self.is_editable() || edits.is_empty() { |
| 3704 | return; |
| 3705 | } |
| 3706 | |
| 3707 | // Every edit invalidates provider responses for the previous document, |
| 3708 | // including deletion and indentation which do not trigger completion. |
| 3709 | M::hide_context_menu(self, cx); |
| 3710 | M::clear_inline_completion(self, cx); |
| 3711 | |
| 3712 | // Sort descending by start so applying front-of-vec first edits the |
| 3713 | // highest offsets first, leaving lower offsets unchanged. |
| 3714 | let mut sorted: Vec<(Range<usize>, &str)> = edits |
| 3715 | .iter() |
| 3716 | .map(|(range, text)| (self.normalize_token_range(range.clone()), text.as_str())) |
| 3717 | .collect(); |
| 3718 | sorted.sort_by_key(|edit| std::cmp::Reverse(edit.0.start)); |
| 3719 | if !self.token_spans().is_empty() { |
| 3720 | let mut merged: Vec<(Range<usize>, &str)> = Vec::with_capacity(sorted.len()); |
| 3721 | for (range, text) in sorted { |
| 3722 | if let Some(last) = merged |
| 3723 | .last_mut() |
| 3724 | .filter(|last| range.end > last.0.start || range == last.0) |
| 3725 | { |
| 3726 | last.0.start = range.start.min(last.0.start); |
| 3727 | last.0.end = range.end.max(last.0.end); |
| 3728 | } else { |
| 3729 | merged.push((range, text)); |
| 3730 | } |
| 3731 | } |
| 3732 | sorted = merged; |
| 3733 | } |
| 3734 | |
| 3735 | #[cfg(debug_assertions)] |
| 3736 | for pair in sorted.windows(2) { |
| 3737 | debug_assert!( |
| 3738 | pair[1].0.end <= pair[0].0.start, |
| 3739 | "replace_text_in_ranges requires disjoint ranges" |
| 3740 | ); |
| 3741 | } |
| 3742 | |
| 3743 | // Wrap multiple edits in one explicit transaction so they undo as a |
| 3744 | // unit. A single edit records directly, which keeps it eligible for |
| 3745 | // the undo manager's typing coalescing. |
| 3746 | let requested_intent = self.undo_manager.take_pending_intent(); |
| 3747 | let selection_before = *self.active_selection(); |
| 3748 | let original_selections: Vec<CursorSelection> = self.selections.iter().copied().collect(); |
| 3749 | // Snapshot the cursors before applying, so undo can restore them. A |
| 3750 | // delete has already expanded them over the text it removes, so they |
| 3751 | // collapse back to where the user left them. |
| 3752 | let selections_before: Vec<CursorSelection> = self |
| 3753 | .selections |
| 3754 | .iter() |
| 3755 | .map(|selection| { |
| 3756 | Self::collapse_for_intent( |
| 3757 | requested_intent.unwrap_or(EditIntent::Atomic), |
| 3758 | *selection, |
| 3759 | &(selection.start..selection.end), |
| 3760 | ) |
| 3761 | }) |
| 3762 | .collect(); |
| 3763 | let group = sorted.len() > 1; |
| 3764 | if group { |
| 3765 | self.undo_manager.begin_transaction(); |
| 3766 | } |
| 3767 | |
| 3768 | let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone(); |
| 3769 | let mut recorded = false; |
| 3770 | // Several edits reach the highlighter as one batch, so it reparses |
| 3771 | // once for the change instead of once per edit. |
| 3772 | let mut highlighter_edits = Vec::new(); |
| 3773 | for (range, new_text) in &sorted { |
| 3774 | let old_text = self.text.clone(); |
| 3775 | self.mode.adjust_auto_closed_pair(range, new_text.len()); |
| 3776 | self.text.replace(range.clone(), new_text); |
| 3777 | |
| 3778 | M::adjust_annotations(self, range, new_text.len()); |
| 3779 | recorded |= self.push_history( |
| 3780 | &old_text, |
| 3781 | range, |
| 3782 | new_text, |
| 3783 | requested_intent, |
| 3784 | selection_before, |
| 3785 | None, |
| 3786 | ); |
| 3787 | |
| 3788 | // Incremental, single-range updates must run per edit. |
| 3789 | self.display_map |
| 3790 | .adjust_folds_for_edit(&old_text, range, new_text); |
| 3791 | self.display_map |
| 3792 | .on_text_changed(&self.text, range, &Rope::from(*new_text), cx); |
| 3793 | |
| 3794 | if group { |
| 3795 | if self.is_code_editor() { |
| 3796 | let edit = |
| 3797 | super::mode::replacement_input_edit(&old_text, &self.text, range, new_text); |
| 3798 | highlighter_edits.push((edit, self.text.clone())); |
| 3799 | } |
| 3800 | } else { |
| 3801 | self.mode.update_highlighter( |
| 3802 | super::mode::HighlighterUpdate { |
| 3803 | selected_range: range, |
| 3804 | old_text: &old_text, |
| 3805 | new_text: &self.text, |
| 3806 | change_text: new_text, |
| 3807 | force: true, |
| 3808 | }, |
| 3809 | window, |
| 3810 | cx, |
| 3811 | ); |
| 3812 | |
| 3813 | self.update_fold_candidates_incremental(range, new_text); |
| 3814 | } |
| 3815 | } |
| 3816 | |
| 3817 | if group { |
| 3818 | self.mode |
| 3819 | .update_highlighter_batch::<M>(&highlighter_edits, window, cx); |
| 3820 | |
| 3821 | // Fold candidates are read from the reparsed document, so each |
| 3822 | // edit is located where it ended up once every edit was applied. |
| 3823 | // `sorted` runs from the highest offset down. |
| 3824 | let mut shift = 0isize; |
| 3825 | for (range, new_text) in sorted.iter().rev() { |
| 3826 | let start = (range.start as isize + shift) as usize; |
| 3827 | self.update_fold_candidates_incremental(&(start..start), new_text); |
| 3828 | shift += new_text.len() as isize - range.len() as isize; |
| 3829 | } |
| 3830 | |
| 3831 | self.undo_manager.commit_transaction(); |
| 3832 | } |
| 3833 | |
| 3834 | // One observable update per batch instead of one per edit. |
| 3835 | if let Some(diagnostics) = self.mode.diagnostics_mut() { |
| 3836 | diagnostics.reset(&self.text) |
| 3837 | } |
| 3838 | M::refresh_language_features(self, window, cx); |
| 3839 | self.update_search(cx); |
| 3840 | |
| 3841 | // Compute the resulting cursors. |
| 3842 | // One collapsed cursor per edit, at the end of its inserted text. |
| 3843 | let mut ascending: Vec<(Range<usize>, &str)> = sorted.clone(); |
| 3844 | ascending.sort_by_key(|edit| edit.0.start); |
| 3845 | let text_len = self.text.len(); |
| 3846 | let mut delta: isize = 0; |
| 3847 | let mut edit_results = Vec::with_capacity(ascending.len()); |
| 3848 | for (range, new_text) in &ascending { |
| 3849 | let offset = ((range.start as isize + delta) as usize + new_text.len()).min(text_len); |
| 3850 | edit_results.push((range.clone(), offset)); |
| 3851 | delta += new_text.len() as isize - (range.end as isize - range.start as isize); |
| 3852 | } |
| 3853 | |
| 3854 | let mut used = vec![false; edit_results.len()]; |
| 3855 | let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(ascending.len()); |
| 3856 | for selection in original_selections { |
| 3857 | if let Ok(index) = edit_results |
| 3858 | .binary_search_by_key(&(selection.start, selection.end), |(range, _)| { |
| 3859 | (range.start, range.end) |
| 3860 | }) |
| 3861 | && !used[index] |
| 3862 | { |
| 3863 | let offset = edit_results[index].1; |
| 3864 | used[index] = true; |
| 3865 | let mut selection = selection; |
| 3866 | selection.place_at(offset, None); |
| 3867 | new_selections.push(selection); |
| 3868 | } |
| 3869 | } |
| 3870 | for (index, (_, offset)) in edit_results.into_iter().enumerate() { |
| 3871 | if !used[index] { |
| 3872 | new_selections.push(CursorSelection::new( |
| 3873 | self.selections.generate_id(), |
| 3874 | offset, |
| 3875 | offset, |
| 3876 | )); |
| 3877 | } |
| 3878 | } |
| 3879 | self.selections.replace_all(new_selections); |
| 3880 | self.selections.merge_overlapping(); |
| 3881 | |
| 3882 | // Record the cursor snapshots for undo/redo restore. |
| 3883 | let selections_after: Vec<CursorSelection> = self.selections.iter().copied().collect(); |
| 3884 | if recorded { |
| 3885 | self.undo_manager.record_auto_closed_pairs( |
| 3886 | auto_closed_pairs_before, |
| 3887 | self.mode.auto_closed_pairs().clone(), |
| 3888 | ); |
| 3889 | self.undo_manager |
| 3890 | .record_selections(selections_before, selections_after); |
| 3891 | } |
| 3892 | |
| 3893 | self.ime_marked_range.take(); |
| 3894 | self.update_preferred_column(); |
| 3895 | self.dismiss_touch_selection(cx); |
| 3896 | if self.is_multi_line() { |
| 3897 | self.mode |
| 3898 | .update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.))); |
| 3899 | } |
| 3900 | if self.emit_events { |
| 3901 | cx.emit(InputEvent::Change); |
| 3902 | } |
| 3903 | cx.notify(); |
| 3904 | } |
| 3905 | |
| 3906 | /// Update fold candidates from tree-sitter syntax tree (full extraction). |
| 3907 | /// Used only on initial load or language changes. |
| 3908 | fn update_fold_candidates(&mut self) { |
| 3909 | if !self.mode.is_folding() { |
| 3910 | return; |
| 3911 | } |
| 3912 | |
| 3913 | let Some(highlighter_rc) = self.mode.highlighter() else { |
| 3914 | return; |
| 3915 | }; |
| 3916 | |
| 3917 | let highlighter = highlighter_rc.borrow(); |
| 3918 | let Some(highlighter) = highlighter.as_ref() else { |
| 3919 | return; |
| 3920 | }; |
| 3921 | |
| 3922 | let fold_ranges = highlighter.fold_ranges(&self.text); |
| 3923 | self.display_map.set_fold_candidates(fold_ranges); |
| 3924 | } |
| 3925 | |
| 3926 | /// Incrementally update fold candidates after a text edit. |
| 3927 | /// Only traverses the edited region of the syntax tree instead of the full tree. |
| 3928 | fn update_fold_candidates_incremental(&mut self, edit_range: &Range<usize>, new_text: &str) { |
| 3929 | if !self.mode.is_folding() { |
| 3930 | return; |
| 3931 | } |
| 3932 | |
| 3933 | let Some(highlighter_rc) = self.mode.highlighter() else { |
| 3934 | return; |
| 3935 | }; |
| 3936 | |
| 3937 | let highlighter = highlighter_rc.borrow(); |
| 3938 | let Some(highlighter) = highlighter.as_ref() else { |
| 3939 | return; |
| 3940 | }; |
| 3941 | |
| 3942 | // The new byte range in the updated text after the edit |
| 3943 | let new_end = edit_range.start + new_text.len(); |
| 3944 | self.display_map.update_fold_candidates_for_edit( |
| 3945 | |range, text| highlighter.fold_ranges_for_edit(range, text), |
| 3946 | edit_range.start..new_end, |
| 3947 | &self.text, |
| 3948 | ); |
| 3949 | } |
| 3950 | } |
| 3951 | |
| 3952 | impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> { |
| 3953 | fn text_for_range( |
| 3954 | &mut self, |
| 3955 | range_utf16: Range<usize>, |
| 3956 | adjusted_range: &mut Option<Range<usize>>, |
| 3957 | _window: &mut Window, |
| 3958 | _cx: &mut Context<Self>, |
| 3959 | ) -> Option<String> { |
| 3960 | let range = self.range_from_utf16(&range_utf16); |
| 3961 | adjusted_range.replace(self.range_to_utf16(&range)); |
| 3962 | Some(self.text.slice(range).to_string()) |
| 3963 | } |
| 3964 | |
| 3965 | fn selected_text_range( |
| 3966 | &mut self, |
| 3967 | _ignore_disabled_input: bool, |
| 3968 | _window: &mut Window, |
| 3969 | _cx: &mut Context<Self>, |
| 3970 | ) -> Option<UTF16Selection> { |
| 3971 | Some(UTF16Selection { |
| 3972 | range: self.range_to_utf16(&self.selected_range()), |
| 3973 | reversed: self.active_selection().reversed, |
| 3974 | }) |
| 3975 | } |
| 3976 | |
| 3977 | fn marked_text_range( |
| 3978 | &self, |
| 3979 | _window: &mut Window, |
| 3980 | _cx: &mut Context<Self>, |
| 3981 | ) -> Option<Range<usize>> { |
| 3982 | self.ime_marked_range |
| 3983 | .map(|range| self.range_to_utf16(&range.into())) |
| 3984 | } |
| 3985 | |
| 3986 | fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) { |
| 3987 | self.ime_marked_range = None; |
| 3988 | self.undo_manager.commit_transaction(); |
| 3989 | } |
| 3990 | |
| 3991 | /// Replace text in range. |
| 3992 | /// |
| 3993 | /// - If the new text is invalid, it will not be replaced. |
| 3994 | /// - If `range_utf16` is not provided, the current selected range will be used. |
| 3995 | fn replace_text_in_range( |
| 3996 | &mut self, |
| 3997 | range_utf16: Option<Range<usize>>, |
| 3998 | new_text: &str, |
| 3999 | window: &mut Window, |
| 4000 | cx: &mut Context<Self>, |
| 4001 | ) { |
| 4002 | let requested_intent = self.undo_manager.take_pending_intent(); |
| 4003 | if !self.is_editable() { |
| 4004 | return; |
| 4005 | } |
| 4006 | let selection_before = *self.active_selection(); |
| 4007 | // Committing a composition ends the transaction it opened, whether or |
| 4008 | // not the platform follows up with `unmark_text`. |
| 4009 | let ends_composition = self.ime_marked_range.is_some(); |
| 4010 | |
| 4011 | self.pause_blink_cursor(cx); |
| 4012 | |
| 4013 | // NOTE: The normalization keeps the UTF-16 length, but may change the |
| 4014 | // UTF-8 byte length, so all the byte-offset calculations below must |
| 4015 | // use the normalized text. |
| 4016 | let new_text = if self.replaying_history { |
| 4017 | Cow::Borrowed(new_text) |
| 4018 | } else { |
| 4019 | self.normalize_input(new_text) |
| 4020 | }; |
| 4021 | let new_text: &str = &new_text; |
| 4022 | |
| 4023 | let range = range_utf16 |
| 4024 | .as_ref() |
| 4025 | .map(|range_utf16| self.range_from_utf16(range_utf16)) |
| 4026 | .or(self.ime_marked_range.map(|range| { |
| 4027 | let range = self.range_to_utf16(&(range.start..range.end)); |
| 4028 | self.range_from_utf16(&range) |
| 4029 | })) |
| 4030 | .unwrap_or(self.selected_range()); |
| 4031 | let range = self.normalize_token_range(range); |
| 4032 | |
| 4033 | // Skip-over as a pure cursor move: a typed closer that already follows |
| 4034 | // the cursor moves past it without touching text or history, so Undo |
| 4035 | // never exposes a transient duplicate. Only for interactive single |
| 4036 | // keystrokes (current selection, no IME mark, not silent replays). |
| 4037 | // `take_pending_intent` above already consumed any request. |
| 4038 | if range.is_empty() |
| 4039 | && range.start == self.cursor() |
| 4040 | && self.ime_marked_range.is_none() |
| 4041 | && !self.silent_replace_text |
| 4042 | && self.is_code_editor() |
| 4043 | && self.selections.is_single() |
| 4044 | && self.active_selection().is_empty() |
| 4045 | { |
| 4046 | if let Some(target) = self.skip_over_target(new_text) { |
| 4047 | self.set_cursor_to(target); |
| 4048 | self.update_preferred_column(); |
| 4049 | cx.notify(); |
| 4050 | return; |
| 4051 | } |
| 4052 | } |
| 4053 | |
| 4054 | if self.is_multi_line() { |
| 4055 | let multi_cursor = range_utf16.is_none() |
| 4056 | && self.ime_marked_range.is_none() |
| 4057 | && !self.selections.is_single(); |
| 4058 | if multi_cursor { |
| 4059 | self.selections.merge_overlapping(); |
| 4060 | let mut edits: Vec<(Range<usize>, String)> = self |
| 4061 | .selections |
| 4062 | .iter() |
| 4063 | .map(|sel| (sel.start..sel.end, new_text.to_string())) |
| 4064 | .collect(); |
| 4065 | edits.sort_by_key(|(range, _)| range.start); |
| 4066 | // One keystroke across several cursors is one batch, committed |
| 4067 | // with the intent of the keystroke so a run of them coalesces |
| 4068 | // into one undo just like single-cursor typing. |
| 4069 | let intent = |
| 4070 | requested_intent.unwrap_or_else(|| self.typing_intent(&edits, new_text)); |
| 4071 | self.undo_manager.begin_transaction_with(intent); |
| 4072 | self.undo_manager.set_pending_intent(intent); |
| 4073 | self.replace_text_in_ranges(&edits, window, cx); |
| 4074 | self.undo_manager.commit_transaction(); |
| 4075 | } else { |
| 4076 | if range_utf16.is_some() { |
| 4077 | self.selections.remove_all_but_active(); |
| 4078 | } |
| 4079 | if let Some(intent) = requested_intent { |
| 4080 | self.undo_manager.set_pending_intent(intent); |
| 4081 | } |
| 4082 | if let Some((open_len, closer)) = self.auto_close_target(&range, new_text) { |
| 4083 | // One edit keeps the pair atomic even at undo coalescing limits. |
| 4084 | let replacement = format!("{new_text}{closer}"); |
| 4085 | self.replace_text_in_ranges(&[(range.clone(), replacement)], window, cx); |
| 4086 | let cursor = range.start + new_text.len(); |
| 4087 | self.mode.track_auto_closed_pair( |
| 4088 | cursor - open_len..cursor, |
| 4089 | cursor..cursor + closer.len(), |
| 4090 | ); |
| 4091 | self.undo_manager |
| 4092 | .record_auto_closed_pairs_after(self.mode.auto_closed_pairs().clone()); |
| 4093 | self.set_cursor_to(cursor); |
| 4094 | self.update_preferred_column(); |
| 4095 | self.undo_manager.record_selections( |
| 4096 | vec![selection_before], |
| 4097 | self.selections.iter().copied().collect(), |
| 4098 | ); |
| 4099 | } else { |
| 4100 | self.replace_text_in_ranges( |
| 4101 | &[(range.clone(), new_text.to_string())], |
| 4102 | window, |
| 4103 | cx, |
| 4104 | ); |
| 4105 | } |
| 4106 | } |
| 4107 | if ends_composition { |
| 4108 | self.undo_manager.commit_transaction(); |
| 4109 | } |
| 4110 | |
| 4111 | if !self.silent_replace_text { |
| 4112 | M::on_text_typed(self, &range, new_text, window, cx); |
| 4113 | } |
| 4114 | return; |
| 4115 | } |
| 4116 | |
| 4117 | // Single-line path |
| 4118 | let old_text = self.text.clone(); |
| 4119 | self.mode.adjust_auto_closed_pair(&range, new_text.len()); |
| 4120 | self.text.replace(range.clone(), new_text); |
| 4121 | |
| 4122 | let mut new_offset = (range.start + new_text.len()).min(self.text.len()); |
| 4123 | |
| 4124 | // True if the mask has changed the text, e.g. regrouping the |
| 4125 | // separators or completing a leading dot. |
| 4126 | let mut mask_changed = false; |
| 4127 | |
| 4128 | if self.is_single_line() { |
| 4129 | let pending_text = self.text.to_string(); |
| 4130 | // Check if the new text is valid. |
| 4131 | // |
| 4132 | // Only reject the edit if the old text was valid, to avoid |
| 4133 | // trapping a pre-existing invalid text (e.g. a `default_value` |
| 4134 | // that does not conform), the user can still edit to fix it. |
| 4135 | if !self.replaying_history |
| 4136 | && !self.validated_token_edit |
| 4137 | && !self.is_valid_input(&pending_text, cx) |
| 4138 | && self.is_valid_input(&old_text.to_string(), cx) |
| 4139 | { |
| 4140 | self.text = old_text; |
| 4141 | return; |
| 4142 | } |
| 4143 | |
| 4144 | if !self.replaying_history && !self.mask_pattern.is_none() { |
| 4145 | let mask_text = self.mask_pattern.mask(&pending_text); |
| 4146 | mask_changed = mask_text.as_str() != pending_text; |
| 4147 | self.text = Rope::from(mask_text.as_str()); |
| 4148 | let new_text_len = |
| 4149 | (new_text.len() + mask_text.len()).saturating_sub(pending_text.len()); |
| 4150 | new_offset = (range.start + new_text_len).min(mask_text.len()); |
| 4151 | } |
| 4152 | } |
| 4153 | |
| 4154 | if mask_changed { |
| 4155 | // Masking rewrites the whole document, so ranges recorded against |
| 4156 | // the old text no longer point at anything. |
| 4157 | M::reset_annotations(self); |
| 4158 | } else { |
| 4159 | M::adjust_annotations(self, &range, new_text.len()); |
| 4160 | } |
| 4161 | if mask_changed { |
| 4162 | // A segment-based history entry no longer matches the masked |
| 4163 | // document, record a whole-document change instead, so that |
| 4164 | // undo/redo can restore the text exactly. |
| 4165 | self.push_history( |
| 4166 | &old_text, |
| 4167 | &(0..old_text.len()), |
| 4168 | &self.text.to_string(), |
| 4169 | Some(EditIntent::Atomic), |
| 4170 | selection_before, |
| 4171 | Some((new_offset..new_offset).into()), |
| 4172 | ); |
| 4173 | } else { |
| 4174 | self.push_history( |
| 4175 | &old_text, |
| 4176 | &range, |
| 4177 | &new_text, |
| 4178 | requested_intent, |
| 4179 | selection_before, |
| 4180 | None, |
| 4181 | ); |
| 4182 | } |
| 4183 | if let Some(diagnostics) = self.mode.diagnostics_mut() { |
| 4184 | diagnostics.reset(&self.text) |
| 4185 | } |
| 4186 | // Adjust folds before updating wrap map: remove overlapping folds and shift others |
| 4187 | self.display_map |
| 4188 | .adjust_folds_for_edit(&old_text, &range, new_text); |
| 4189 | self.display_map |
| 4190 | .on_text_changed(&self.text, &range, &Rope::from(new_text), cx); |
| 4191 | |
| 4192 | self.mode.update_highlighter::<M>( |
| 4193 | super::mode::HighlighterUpdate { |
| 4194 | selected_range: &range, |
| 4195 | old_text: &old_text, |
| 4196 | new_text: &self.text, |
| 4197 | change_text: &new_text, |
| 4198 | force: true, |
| 4199 | }, |
| 4200 | window, |
| 4201 | cx, |
| 4202 | ); |
| 4203 | |
| 4204 | self.update_fold_candidates_incremental(&range, new_text); |
| 4205 | M::refresh_language_features(self, window, cx); |
| 4206 | self.set_cursor_to(new_offset); |
| 4207 | self.ime_marked_range.take(); |
| 4208 | // A commit ends the IME composition: macOS delivers `insertText:` for |
| 4209 | // the confirmed candidate without a following `unmarkText`, so close |
| 4210 | // the transaction here. Leaving it open would keep merging every later |
| 4211 | // edit into the same change, which then carries the text and selection |
| 4212 | // of the first composition. |
| 4213 | if ends_composition { |
| 4214 | self.undo_manager |
| 4215 | .record_selections(vec![selection_before], vec![*self.active_selection()]); |
| 4216 | self.undo_manager.commit_transaction(); |
| 4217 | } |
| 4218 | self.update_preferred_column(); |
| 4219 | self.update_search(cx); |
| 4220 | self.dismiss_touch_selection(cx); |
| 4221 | if self.is_multi_line() { |
| 4222 | self.mode |
| 4223 | .update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.))); |
| 4224 | } |
| 4225 | if !self.silent_replace_text { |
| 4226 | M::on_text_typed(self, &range, &new_text, window, cx); |
| 4227 | } |
| 4228 | if self.emit_events { |
| 4229 | cx.emit(InputEvent::Change); |
| 4230 | } |
| 4231 | cx.notify(); |
| 4232 | } |
| 4233 | |
| 4234 | /// Mark text is the IME temporary insert on typing. |
| 4235 | fn replace_and_mark_text_in_range( |
| 4236 | &mut self, |
| 4237 | range_utf16: Option<Range<usize>>, |
| 4238 | new_text: &str, |
| 4239 | new_selected_range_utf16: Option<Range<usize>>, |
| 4240 | window: &mut Window, |
| 4241 | cx: &mut Context<Self>, |
| 4242 | ) { |
| 4243 | let requested_intent = self.undo_manager.take_pending_intent(); |
| 4244 | if !self.is_editable() { |
| 4245 | return; |
| 4246 | } |
| 4247 | let selection_before = *self.active_selection(); |
| 4248 | |
| 4249 | let starts_composition = self.ime_marked_range.is_none(); |
| 4250 | if starts_composition { |
| 4251 | // Even a canceled preedit separates the typing gestures on either |
| 4252 | // side; its no-op transaction must not reconnect those gestures. |
| 4253 | self.undo_manager.break_transaction_coalescing(); |
| 4254 | self.undo_manager.begin_transaction(); |
| 4255 | } |
| 4256 | |
| 4257 | // Collapse any extra cursors so we never leave stale secondary cursors behind. |
| 4258 | self.selections.remove_all_but_active(); |
| 4259 | |
| 4260 | M::reset_language_features(self); |
| 4261 | |
| 4262 | // See the same NOTE in `replace_text_in_range`. |
| 4263 | let new_text = if self.replaying_history { |
| 4264 | Cow::Borrowed(new_text) |
| 4265 | } else { |
| 4266 | self.normalize_input(new_text) |
| 4267 | }; |
| 4268 | let new_text: &str = &new_text; |
| 4269 | |
| 4270 | let range = range_utf16 |
| 4271 | .as_ref() |
| 4272 | .map(|range_utf16| self.range_from_utf16(range_utf16)) |
| 4273 | .or(self.ime_marked_range.map(|range| { |
| 4274 | let range = self.range_to_utf16(&(range.start..range.end)); |
| 4275 | self.range_from_utf16(&range) |
| 4276 | })) |
| 4277 | .unwrap_or(self.selected_range()); |
| 4278 | let range = self.normalize_token_range(range); |
| 4279 | |
| 4280 | let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone(); |
| 4281 | let old_text = self.text.clone(); |
| 4282 | self.mode.adjust_auto_closed_pair(&range, new_text.len()); |
| 4283 | self.text.replace(range.clone(), new_text); |
| 4284 | |
| 4285 | if self.is_single_line() { |
| 4286 | let pending_text = self.text.to_string(); |
| 4287 | // See the same NOTE in `replace_text_in_range`. |
| 4288 | if !self.replaying_history |
| 4289 | && !self.validated_token_edit |
| 4290 | && !self.is_valid_input(&pending_text, cx) |
| 4291 | && self.is_valid_input(&old_text.to_string(), cx) |
| 4292 | { |
| 4293 | self.text = old_text; |
| 4294 | if starts_composition { |
| 4295 | self.undo_manager.commit_transaction(); |
| 4296 | } |
| 4297 | return; |
| 4298 | } |
| 4299 | } |
| 4300 | |
| 4301 | M::adjust_annotations(self, &range, new_text.len()); |
| 4302 | if let Some(diagnostics) = self.mode.diagnostics_mut() { |
| 4303 | diagnostics.reset(&self.text) |
| 4304 | } |
| 4305 | // Adjust folds before updating wrap map: remove overlapping folds and shift others |
| 4306 | self.display_map |
| 4307 | .adjust_folds_for_edit(&old_text, &range, new_text); |
| 4308 | self.display_map |
| 4309 | .on_text_changed(&self.text, &range, &Rope::from(new_text), cx); |
| 4310 | |
| 4311 | self.mode.update_highlighter::<M>( |
| 4312 | super::mode::HighlighterUpdate { |
| 4313 | selected_range: &range, |
| 4314 | old_text: &old_text, |
| 4315 | new_text: &self.text, |
| 4316 | change_text: &new_text, |
| 4317 | force: true, |
| 4318 | }, |
| 4319 | window, |
| 4320 | cx, |
| 4321 | ); |
| 4322 | |
| 4323 | self.update_fold_candidates_incremental(&range, new_text); |
| 4324 | M::refresh_language_features(self, window, cx); |
| 4325 | if new_text.is_empty() { |
| 4326 | // Cancel selection, when cancel IME input. |
| 4327 | self.set_cursor_to(range.start); |
| 4328 | self.ime_marked_range = None; |
| 4329 | } else { |
| 4330 | self.ime_marked_range = Some((range.start..range.start + new_text.len()).into()); |
| 4331 | let new_range = new_selected_range_utf16 |
| 4332 | .as_ref() |
| 4333 | .map(|range_utf16| { |
| 4334 | let new_text = Rope::from(new_text); |
| 4335 | range.start + new_text.offset_utf16_to_offset(range_utf16.start) |
| 4336 | ..range.start + new_text.offset_utf16_to_offset(range_utf16.end) |
| 4337 | }) |
| 4338 | .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len()); |
| 4339 | self.set_selection(new_range.start, new_range.end); |
| 4340 | } |
| 4341 | if self.is_multi_line() { |
| 4342 | self.mode |
| 4343 | .update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.))); |
| 4344 | } |
| 4345 | if self.push_history( |
| 4346 | &old_text, |
| 4347 | &range, |
| 4348 | new_text, |
| 4349 | requested_intent, |
| 4350 | selection_before, |
| 4351 | Some(*self.active_selection()), |
| 4352 | ) { |
| 4353 | self.undo_manager |
| 4354 | .record_selections(vec![selection_before], vec![*self.active_selection()]); |
| 4355 | self.undo_manager.record_auto_closed_pairs( |
| 4356 | auto_closed_pairs_before, |
| 4357 | self.mode.auto_closed_pairs().clone(), |
| 4358 | ); |
| 4359 | } |
| 4360 | if new_text.is_empty() { |
| 4361 | self.undo_manager.commit_transaction(); |
| 4362 | } |
| 4363 | cx.notify(); |
| 4364 | } |
| 4365 | |
| 4366 | /// Used to position IME candidates. |
| 4367 | fn bounds_for_range( |
| 4368 | &mut self, |
| 4369 | range_utf16: Range<usize>, |
| 4370 | bounds: Bounds<Pixels>, |
| 4371 | _window: &mut Window, |
| 4372 | _cx: &mut Context<Self>, |
| 4373 | ) -> Option<Bounds<Pixels>> { |
| 4374 | let last_layout = self.last_layout.as_ref()?; |
| 4375 | let line_height = last_layout.line_height; |
| 4376 | let line_number_width = last_layout.line_number_width; |
| 4377 | let range = self.range_from_utf16(&range_utf16); |
| 4378 | |
| 4379 | let mut start_origin = None; |
| 4380 | let mut start_height = line_height; |
| 4381 | let mut end_origin = None; |
| 4382 | let line_number_origin = point(line_number_width, px(0.)); |
| 4383 | let mut y_offset = last_layout.visible_top; |
| 4384 | |
| 4385 | for (vi, line) in last_layout.lines.iter().enumerate() { |
| 4386 | if start_origin.is_some() && end_origin.is_some() { |
| 4387 | break; |
| 4388 | } |
| 4389 | |
| 4390 | let index_offset = last_layout.visible_line_byte_offsets[vi]; |
| 4391 | |
| 4392 | if start_origin.is_none() { |
| 4393 | if let Some(p) = line.position_for_index( |
| 4394 | range.start.saturating_sub(index_offset), |
| 4395 | last_layout, |
| 4396 | false, |
| 4397 | ) { |
| 4398 | start_origin = Some(p + point(px(0.), y_offset)); |
| 4399 | start_height = line |
| 4400 | .row_at_y(p.y, line_height) |
| 4401 | .map_or(line_height, |ix| line.row_height(ix, line_height)); |
| 4402 | } |
| 4403 | } |
| 4404 | |
| 4405 | if end_origin.is_none() { |
| 4406 | if let Some(p) = line.position_for_index( |
| 4407 | range.end.saturating_sub(index_offset), |
| 4408 | last_layout, |
| 4409 | false, |
| 4410 | ) { |
| 4411 | end_origin = Some(p + point(px(0.), y_offset)); |
| 4412 | } |
| 4413 | } |
| 4414 | |
| 4415 | y_offset += line.size(line_height).height; |
| 4416 | } |
| 4417 | |
| 4418 | let start_origin = start_origin.or_else(|| { |
| 4419 | let offset = self.last_cursor.or(Some(self.cursor()))?; |
| 4420 | let (_, _, origin) = self.line_and_position_for_offset(offset); |
| 4421 | origin.map(|origin| origin - line_number_origin) |
| 4422 | })?; |
| 4423 | let mut end_origin = end_origin.unwrap_or(start_origin); |
| 4424 | // Ensure at same line. |
| 4425 | end_origin.y = start_origin.y; |
| 4426 | |
| 4427 | Some(Bounds::from_corners( |
| 4428 | bounds.origin + line_number_origin + start_origin, |
| 4429 | // + row height for show IME panel under the cursor line. |
| 4430 | bounds.origin + line_number_origin + point(end_origin.x, end_origin.y + start_height), |
| 4431 | )) |
| 4432 | } |
| 4433 | |
| 4434 | fn character_index_for_point( |
| 4435 | &mut self, |
| 4436 | point: gpui::Point<Pixels>, |
| 4437 | _window: &mut Window, |
| 4438 | _cx: &mut Context<Self>, |
| 4439 | ) -> Option<usize> { |
| 4440 | let last_layout = self.last_layout.as_ref()?; |
| 4441 | let line_point = self.last_bounds?.localize(&point)?; |
| 4442 | |
| 4443 | for (vi, line) in last_layout.lines.iter().enumerate() { |
| 4444 | let offset = last_layout.visible_line_byte_offsets[vi]; |
| 4445 | if let Some(utf8_index) = line.index_for_position(line_point, last_layout) { |
| 4446 | return Some(self.offset_to_utf16(offset + utf8_index)); |
| 4447 | } |
| 4448 | } |
| 4449 | |
| 4450 | None |
| 4451 | } |
| 4452 | } |
| 4453 | |
| 4454 | impl<M: InputModeKind> Focusable for InputBaseState<M> { |
| 4455 | fn focus_handle(&self, _cx: &App) -> FocusHandle { |
| 4456 | self.focus_handle.clone() |
| 4457 | } |
| 4458 | } |
| 4459 | |
| 4460 | impl<M: InputModeKind> Render for InputBaseState<M> { |
| 4461 | fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 4462 | // Before anything reads it: the element resolves this style during |
| 4463 | // layout and paint, and both happen after this call in the same frame. |
| 4464 | self.editor_style = self |
| 4465 | .projected_editor_style |
| 4466 | .resolved(&crate::Theme::global(cx).tokens); |
| 4467 | let entity = cx.entity(); |
| 4468 | if self._pending_update { |
| 4469 | self.mode.update_highlighter::<M>( |
| 4470 | super::mode::HighlighterUpdate { |
| 4471 | selected_range: &(0..0), |
| 4472 | old_text: &self.text, |
| 4473 | new_text: &self.text, |
| 4474 | change_text: "", |
| 4475 | force: false, |
| 4476 | }, |
| 4477 | window, |
| 4478 | cx, |
| 4479 | ); |
| 4480 | |
| 4481 | self.update_fold_candidates(); |
| 4482 | M::refresh_language_features(self, window, cx); |
| 4483 | self._pending_update = false; |
| 4484 | } |
| 4485 | |
| 4486 | let element = div() |
| 4487 | .id("input-state") |
| 4488 | .key_context(CONTEXT) |
| 4489 | .track_focus(&self.focus_handle) |
| 4490 | .when(self.is_editable(), |this| { |
| 4491 | this.on_action(window.listener_for(&entity, InputBaseState::backspace)) |
| 4492 | .on_action(window.listener_for(&entity, InputBaseState::delete)) |
| 4493 | .on_action( |
| 4494 | window.listener_for(&entity, InputBaseState::delete_to_beginning_of_line), |
| 4495 | ) |
| 4496 | .on_action(window.listener_for(&entity, InputBaseState::delete_to_end_of_line)) |
| 4497 | .on_action(window.listener_for(&entity, InputBaseState::delete_previous_word)) |
| 4498 | .on_action(window.listener_for(&entity, InputBaseState::delete_next_word)) |
| 4499 | .on_action(window.listener_for(&entity, InputBaseState::enter)) |
| 4500 | .on_action(window.listener_for(&entity, InputBaseState::escape)) |
| 4501 | .on_action(window.listener_for(&entity, InputBaseState::paste)) |
| 4502 | .on_action(window.listener_for(&entity, InputBaseState::cut)) |
| 4503 | .on_action(window.listener_for(&entity, InputBaseState::undo)) |
| 4504 | .on_action(window.listener_for(&entity, InputBaseState::redo)) |
| 4505 | .when(self.is_multi_line(), |this| { |
| 4506 | this.on_action(window.listener_for(&entity, InputBaseState::indent_inline)) |
| 4507 | .on_action(window.listener_for(&entity, InputBaseState::outdent_inline)) |
| 4508 | .on_action(window.listener_for(&entity, InputBaseState::indent_block)) |
| 4509 | .on_action(window.listener_for(&entity, InputBaseState::outdent_block)) |
| 4510 | }) |
| 4511 | }) |
| 4512 | .on_action(window.listener_for(&entity, InputBaseState::left)) |
| 4513 | .on_action(window.listener_for(&entity, InputBaseState::right)) |
| 4514 | .on_action(window.listener_for(&entity, InputBaseState::select_left)) |
| 4515 | .on_action(window.listener_for(&entity, InputBaseState::select_right)) |
| 4516 | .when(self.is_multi_line(), |this| { |
| 4517 | this.on_action(window.listener_for(&entity, InputBaseState::up)) |
| 4518 | .on_action(window.listener_for(&entity, InputBaseState::down)) |
| 4519 | .on_action(window.listener_for(&entity, InputBaseState::select_up)) |
| 4520 | .on_action(window.listener_for(&entity, InputBaseState::select_down)) |
| 4521 | .on_action(window.listener_for(&entity, InputBaseState::page_up)) |
| 4522 | .on_action(window.listener_for(&entity, InputBaseState::page_down)) |
| 4523 | .on_action(window.listener_for(&entity, InputBaseState::add_cursor_above)) |
| 4524 | .on_action(window.listener_for(&entity, InputBaseState::add_cursor_below)) |
| 4525 | }) |
| 4526 | .on_action(window.listener_for(&entity, InputBaseState::on_action_select_all)) |
| 4527 | .on_action(window.listener_for(&entity, InputBaseState::select_to_start_of_line)) |
| 4528 | .on_action(window.listener_for(&entity, InputBaseState::select_to_end_of_line)) |
| 4529 | .on_action(window.listener_for(&entity, InputBaseState::select_to_previous_word)) |
| 4530 | .on_action(window.listener_for(&entity, InputBaseState::select_to_next_word)) |
| 4531 | .on_action(window.listener_for(&entity, InputBaseState::home)) |
| 4532 | .on_action(window.listener_for(&entity, InputBaseState::end)) |
| 4533 | .on_action(window.listener_for(&entity, InputBaseState::move_to_start)) |
| 4534 | .on_action(window.listener_for(&entity, InputBaseState::move_to_end)) |
| 4535 | .on_action(window.listener_for(&entity, InputBaseState::move_to_previous_word)) |
| 4536 | .on_action(window.listener_for(&entity, InputBaseState::move_to_next_word)) |
| 4537 | .on_action(window.listener_for(&entity, InputBaseState::select_to_start)) |
| 4538 | .on_action(window.listener_for(&entity, InputBaseState::select_to_end)) |
| 4539 | .on_action(window.listener_for(&entity, InputBaseState::show_character_palette)) |
| 4540 | .on_action({ |
| 4541 | let entity = entity.clone(); |
| 4542 | move |_: &ActivateToken, window, cx| { |
| 4543 | let state = entity.read(cx); |
| 4544 | let activation = state |
| 4545 | .token_spans() |
| 4546 | .iter() |
| 4547 | .find(|span| span.range() == state.selected_range()) |
| 4548 | .and_then(|span| { |
| 4549 | state.range_to_bounds(&span.range()).and_then(|bounds| { |
| 4550 | state.token_activation( |
| 4551 | span.range().start, |
| 4552 | bounds, |
| 4553 | gpui::ClickEvent::Keyboard(gpui::KeyboardClickEvent { |
| 4554 | bounds, |
| 4555 | ..Default::default() |
| 4556 | }), |
| 4557 | ) |
| 4558 | }) |
| 4559 | }); |
| 4560 | if let Some((listener, event)) = activation { |
| 4561 | listener(&event, window, cx); |
| 4562 | } |
| 4563 | } |
| 4564 | }) |
| 4565 | .on_action(window.listener_for(&entity, InputBaseState::copy)) |
| 4566 | .on_action(window.listener_for(&entity, InputBaseState::on_action_search)) |
| 4567 | .on_action(window.listener_for(&entity, InputBaseState::on_action_replace)) |
| 4568 | .on_mouse_down( |
| 4569 | MouseButton::Left, |
| 4570 | window.listener_for(&entity, InputBaseState::on_mouse_down), |
| 4571 | ) |
| 4572 | .on_mouse_down( |
| 4573 | MouseButton::Right, |
| 4574 | window.listener_for(&entity, InputBaseState::on_mouse_down), |
| 4575 | ) |
| 4576 | .on_mouse_up( |
| 4577 | MouseButton::Left, |
| 4578 | window.listener_for(&entity, InputBaseState::on_mouse_up), |
| 4579 | ) |
| 4580 | .on_mouse_up( |
| 4581 | MouseButton::Right, |
| 4582 | window.listener_for(&entity, InputBaseState::on_mouse_up), |
| 4583 | ) |
| 4584 | .on_mouse_move(window.listener_for(&entity, InputBaseState::on_mouse_move)) |
| 4585 | .on_scroll_wheel(window.listener_for(&entity, InputBaseState::on_scroll_wheel)) |
| 4586 | .when(self.is_multi_line() && !self.disabled, |this| { |
| 4587 | this.on_modifiers_changed(cx.listener(|_, _, _, cx| cx.notify())) |
| 4588 | }) |
| 4589 | .when(!self.disabled, |this| { |
| 4590 | if self.is_multi_line() && window.modifiers().alt { |
| 4591 | this.cursor_crosshair() |
| 4592 | } else { |
| 4593 | this.cursor_text() |
| 4594 | } |
| 4595 | }) |
| 4596 | .flex_1() |
| 4597 | // A single line fills the frame and sits at its vertical center, |
| 4598 | // so the frame needs no layout of its own to hold it. It is never |
| 4599 | // shorter than its line, though: this root clips (overflow-x |
| 4600 | // hidden clips both axes), and a frame whose padding leaves less |
| 4601 | // than a line, like Component's Input, would cut off descenders. |
| 4602 | .map(|this| { |
| 4603 | if self.is_multi_line() { |
| 4604 | this.h_full() |
| 4605 | } else { |
| 4606 | this.min_h_full().flex().items_center() |
| 4607 | } |
| 4608 | }) |
| 4609 | .flex_grow_1() |
| 4610 | .overflow_x_hidden() |
| 4611 | .when(self.is_multi_line(), |this| { |
| 4612 | this.pt(self.editor_paddings.top) |
| 4613 | .pr(self.editor_paddings.right) |
| 4614 | .pb(self.editor_paddings.bottom) |
| 4615 | .pl(self.editor_paddings.left) |
| 4616 | }) |
| 4617 | .child(TextElement::new(entity.clone()).placeholder(self.placeholder.clone())) |
| 4618 | .when(self.shows_scrollbar(), |this| { |
| 4619 | this.child(EditorScrollbar::new(entity.clone())) |
| 4620 | }); |
| 4621 | |
| 4622 | // Actions only one mode handles are registered by that mode, where |
| 4623 | // `Self` is concrete enough to name its own entity type. |
| 4624 | M::register_actions(element, &entity, window) |
| 4625 | } |
| 4626 | } |
| 4627 | |
| 4628 | #[cfg(test)] |
| 4629 | mod tests { |
| 4630 | use super::*; |
| 4631 | |
| 4632 | #[gpui::test] |
| 4633 | fn test_multicursor_unicode_completion_uses_post_edit_start(cx: &mut TestAppContext) { |
| 4634 | use crate::input::{CompletionProvider, EditorState}; |
| 4635 | use gpui::Task; |
| 4636 | use lsp_types::{CompletionContext, CompletionResponse}; |
| 4637 | use std::cell::RefCell; |
| 4638 | |
| 4639 | #[derive(Default)] |
| 4640 | struct Provider { |
| 4641 | starts: RefCell<Vec<usize>>, |
| 4642 | queries: RefCell<Vec<(usize, String)>>, |
| 4643 | } |
| 4644 | |
| 4645 | impl CompletionProvider for Provider { |
| 4646 | fn is_completion_trigger(&self, offset: usize, _: &str, _: &mut App) -> bool { |
| 4647 | self.starts.borrow_mut().push(offset); |
| 4648 | true |
| 4649 | } |
| 4650 | |
| 4651 | fn completions( |
| 4652 | &self, |
| 4653 | _: &Rope, |
| 4654 | offset: usize, |
| 4655 | trigger: CompletionContext, |
| 4656 | _: &mut Window, |
| 4657 | _: &mut App, |
| 4658 | ) -> Task<anyhow::Result<CompletionResponse>> { |
| 4659 | self.queries |
| 4660 | .borrow_mut() |
| 4661 | .push((offset, trigger.trigger_character.unwrap())); |
| 4662 | Task::ready(Ok(CompletionResponse::Array(vec![]))) |
| 4663 | } |
| 4664 | } |
| 4665 | |
| 4666 | cx.update(crate::init); |
| 4667 | let mut editor = None; |
| 4668 | let window = cx.open_window(size(px(400.), px(100.)), |window, cx| { |
| 4669 | editor = Some(cx.new(|cx| EditorState::new(window, cx).default_value("aa"))); |
| 4670 | gpui::EmptyView |
| 4671 | }); |
| 4672 | let editor = editor.unwrap(); |
| 4673 | let provider = Rc::new(Provider::default()); |
| 4674 | window |
| 4675 | .update(cx, |_, window, cx| { |
| 4676 | editor.update(cx, |state, cx| { |
| 4677 | state.extras.lsp.completion_provider = Some(provider.clone()); |
| 4678 | state |
| 4679 | .extras |
| 4680 | .context_menu_content |
| 4681 | .completion |
| 4682 | .trigger_start_offset = Some(0); |
| 4683 | state.extras.context_menu_content.completion.query = "aa".into(); |
| 4684 | state.set_cursor_to(1); |
| 4685 | state.add_cursor_at(0, cx); |
| 4686 | |
| 4687 | state.replace_text_in_range(None, "中", window, cx); |
| 4688 | |
| 4689 | assert_eq!(state.value(), "中a中a"); |
| 4690 | assert_eq!(provider.starts.borrow().as_slice(), &[4]); |
| 4691 | assert_eq!(provider.queries.borrow().as_slice(), &[(7, "中".into())]); |
| 4692 | }); |
| 4693 | }) |
| 4694 | .unwrap(); |
| 4695 | } |
| 4696 | |
| 4697 | #[gpui::test] |
| 4698 | fn test_inline_token_wrap_and_size_refresh(cx: &mut TestAppContext) { |
| 4699 | use crate::input::{InlineToken, InlineTokenPresentation}; |
| 4700 | let width = Rc::new(Cell::new(4000.)); |
| 4701 | let render_width = width.clone(); |
| 4702 | let view = InputView::build_textarea(cx, |state| state.rows(4).default_value("@a@b")); |
| 4703 | view.window_handle |
| 4704 | .update(cx, |_, window, cx| { |
| 4705 | view.input.update(cx, |state, cx| { |
| 4706 | state |
| 4707 | .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx) |
| 4708 | .unwrap(); |
| 4709 | state |
| 4710 | .replace_range_with_token(2..4, InlineToken::new("b", "@b"), window, cx) |
| 4711 | .unwrap(); |
| 4712 | state.set_token_presentation( |
| 4713 | InlineTokenPresentation::default() |
| 4714 | .token(move |_, _, _| div().w(px(render_width.get()))), |
| 4715 | ); |
| 4716 | }); |
| 4717 | }) |
| 4718 | .unwrap(); |
| 4719 | let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx); |
| 4720 | visual.update(|window, cx| window.draw(cx).clear(cx)); |
| 4721 | view.input.read_with(&visual, |state, _| { |
| 4722 | assert_eq!(state.display_map.wrap_row_count(), 2); |
| 4723 | let first = state.range_to_bounds(&(0..2)).unwrap(); |
| 4724 | let second = state.range_to_bounds(&(2..4)).unwrap(); |
| 4725 | assert!(second.origin.y > first.origin.y); |
| 4726 | assert_eq!( |
| 4727 | state.last_layout.as_ref().unwrap().lines[0].wrapped_lines[0].len, |
| 4728 | 2 |
| 4729 | ); |
| 4730 | }); |
| 4731 | width.set(100.); |
| 4732 | view.input.update(&mut visual, |_, cx| cx.notify()); |
| 4733 | visual.update(|window, cx| window.draw(cx).clear(cx)); |
| 4734 | view.input.read_with(&visual, |state, _| { |
| 4735 | assert_eq!(state.display_map.wrap_row_count(), 1) |
| 4736 | }); |
| 4737 | } |
| 4738 | |
| 4739 | fn build_block_view( |
| 4740 | cx: &mut TestAppContext, |
| 4741 | value: &'static str, |
| 4742 | token_range: Range<usize>, |
| 4743 | ) -> (InputView<TextareaMode>, VisualTestContext) { |
| 4744 | use crate::input::{InlineToken, InlineTokenPresentation}; |
| 4745 | let view = |
| 4746 | InputView::build_textarea(cx, move |state| state.auto_grow(1, 40).default_value(value)); |
| 4747 | view.window_handle |
| 4748 | .update(cx, |_, window, cx| { |
| 4749 | view.input.update(cx, |state, cx| { |
| 4750 | state.set_token_presentation( |
| 4751 | InlineTokenPresentation::default() |
| 4752 | .token(|_, _, _| div().w(px(200.)).h(px(120.))), |
| 4753 | ); |
| 4754 | state |
| 4755 | .replace_range_with_token( |
| 4756 | token_range, |
| 4757 | InlineToken::new("img", "[img]").block(), |
| 4758 | window, |
| 4759 | cx, |
| 4760 | ) |
| 4761 | .unwrap(); |
| 4762 | }); |
| 4763 | }) |
| 4764 | .unwrap(); |
| 4765 | let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx); |
| 4766 | visual.update(|window, cx| window.draw(cx).clear(cx)); |
| 4767 | visual.update(|window, cx| window.draw(cx).clear(cx)); |
| 4768 | (view, visual) |
| 4769 | } |
| 4770 | |
| 4771 | #[gpui::test] |
| 4772 | fn test_block_token_row_height_feeds_row_top_and_auto_grow(cx: &mut TestAppContext) { |
| 4773 | let (view, visual) = build_block_view(cx, "ab[img]cd", 2..7); |
| 4774 | view.input.read_with(&visual, |state, _| { |
| 4775 | let line_height = state.line_height().unwrap(); |
| 4776 | assert_eq!( |
| 4777 | state.display_map.line(0).unwrap().wrapped_lines.as_slice(), |
| 4778 | [0..2, 2..7, 7..9] |
| 4779 | ); |
| 4780 | assert_eq!( |
| 4781 | state.display_map.row_top(2, line_height), |
| 4782 | line_height + px(120.) |
| 4783 | ); |
| 4784 | assert_eq!( |
| 4785 | state.display_map.content_height(line_height), |
| 4786 | line_height * 2. + px(120.) |
| 4787 | ); |
| 4788 | assert_eq!(state.display_map.row_at_y(px(119.), line_height), 1); |
| 4789 | assert_eq!(state.display_map.row_at_y(px(1000.), line_height), 2); |
| 4790 | assert!(state.mode.rows() > state.display_map.wrap_row_count()); |
| 4791 | assert_eq!( |
| 4792 | state.mode.rows(), |
| 4793 | state.display_map.content_rows(line_height) |
| 4794 | ); |
| 4795 | }); |
| 4796 | } |
| 4797 | |
| 4798 | struct GrowingRoot(Entity<InputBaseState<TextareaMode>>); |
| 4799 | |
| 4800 | impl Render for GrowingRoot { |
| 4801 | fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { |
| 4802 | div() |
| 4803 | .flex() |
| 4804 | .items_end() |
| 4805 | .child(div().w(px(600.)).child(self.0.clone())) |
| 4806 | } |
| 4807 | } |
| 4808 | |
| 4809 | fn build_growing_view( |
| 4810 | cx: &mut TestAppContext, |
| 4811 | max_rows: usize, |
| 4812 | ) -> (Entity<InputBaseState<TextareaMode>>, VisualTestContext) { |
| 4813 | use crate::input::InlineTokenPresentation; |
| 4814 | let mut input = None; |
| 4815 | let window = cx.update(|cx| { |
| 4816 | cx.open_window(Default::default(), |window, cx| { |
| 4817 | cx.set_global(Theme::default()); |
| 4818 | super::super::init(cx); |
| 4819 | let state = cx.new(|cx| { |
| 4820 | let mut state = |
| 4821 | crate::input::TextareaState::new(window, cx).auto_grow(1, max_rows); |
| 4822 | state.set_token_presentation( |
| 4823 | InlineTokenPresentation::default() |
| 4824 | .token(|_, _, _| div().w(px(200.)).h(px(120.))), |
| 4825 | ); |
| 4826 | state |
| 4827 | }); |
| 4828 | input = Some(state.clone()); |
| 4829 | cx.new(|_| GrowingRoot(state)) |
| 4830 | }) |
| 4831 | .unwrap() |
| 4832 | }); |
| 4833 | let mut visual = VisualTestContext::from_window(window.into(), cx); |
| 4834 | visual.update(|window, cx| window.draw(cx).clear(cx)); |
| 4835 | (input.unwrap(), visual) |
| 4836 | } |
| 4837 | |
| 4838 | fn draw_twice(visual: &mut VisualTestContext) { |
| 4839 | visual.update(|window, cx| window.draw(cx).clear(cx)); |
| 4840 | visual.update(|window, cx| window.draw(cx).clear(cx)); |
| 4841 | } |
| 4842 | |
| 4843 | fn load_block_content( |
| 4844 | input: &Entity<InputBaseState<TextareaMode>>, |
| 4845 | visual: &mut VisualTestContext, |
| 4846 | before: &str, |
| 4847 | after: &str, |
| 4848 | ) { |
| 4849 | use crate::input::InlineToken; |
| 4850 | let before = before.to_owned(); |
| 4851 | let after = after.to_owned(); |
| 4852 | visual.update(|window, cx| { |
| 4853 | input.update(cx, |state, cx| { |
| 4854 | let text = format!("{before}[img]{after}"); |
| 4855 | let range = before.len()..before.len() + 5; |
| 4856 | let content = crate::input::InputContent::new(text.clone()) |
| 4857 | .with_token(range, InlineToken::new("img", "[img]").block()) |
| 4858 | .unwrap(); |
| 4859 | state.set_value(content, window, cx); |
| 4860 | state.set_selected_range(text.len()..text.len(), cx); |
| 4861 | }) |
| 4862 | }); |
| 4863 | draw_twice(visual); |
| 4864 | } |
| 4865 | |
| 4866 | fn assert_cursor_row_in_view( |
| 4867 | input: &Entity<InputBaseState<TextareaMode>>, |
| 4868 | visual: &VisualTestContext, |
| 4869 | ) { |
| 4870 | input.read_with(visual, |state, _| { |
| 4871 | let line_height = state.line_height().unwrap(); |
| 4872 | let content = state.display_map.content_height(line_height); |
| 4873 | let viewport = state.input_bounds.size.height; |
| 4874 | assert!( |
| 4875 | content > viewport, |
| 4876 | "content {content:?} viewport {viewport:?}" |
| 4877 | ); |
| 4878 | assert_eq!(state.scroll_handle.offset().y, viewport - content); |
| 4879 | }); |
| 4880 | } |
| 4881 | |
| 4882 | #[gpui::test] |
| 4883 | fn test_typing_after_a_block_token_scrolls_the_cursor_row_into_view(cx: &mut TestAppContext) { |
| 4884 | let (input, mut visual) = build_growing_view(cx, 4); |
| 4885 | load_block_content( |
| 4886 | &input, |
| 4887 | &mut visual, |
| 4888 | "ab\ncd\nef\ngh\nij\nkl\nmn\nop\nqr\n", |
| 4889 | "", |
| 4890 | ); |
| 4891 | for character in ["x", "y"] { |
| 4892 | visual.update(|window, cx| { |
| 4893 | input.update(cx, |state, cx| state.insert(character, window, cx)) |
| 4894 | }); |
| 4895 | } |
| 4896 | draw_twice(&mut visual); |
| 4897 | assert_cursor_row_in_view(&input, &visual); |
| 4898 | } |
| 4899 | |
| 4900 | #[gpui::test] |
| 4901 | fn test_loading_content_with_a_block_token_scrolls_the_cursor_row_into_view( |
| 4902 | cx: &mut TestAppContext, |
| 4903 | ) { |
| 4904 | let (input, mut visual) = build_growing_view(cx, 4); |
| 4905 | load_block_content( |
| 4906 | &input, |
| 4907 | &mut visual, |
| 4908 | "ab\ncd\nef\ngh\nij\nkl\nmn\nop\nqr\n", |
| 4909 | "cd", |
| 4910 | ); |
| 4911 | assert_cursor_row_in_view(&input, &visual); |
| 4912 | } |
| 4913 | |
| 4914 | #[gpui::test] |
| 4915 | fn test_block_tokens_add_their_rows_on_top_of_max_rows_up_to_twice_of_it( |
| 4916 | cx: &mut TestAppContext, |
| 4917 | ) { |
| 4918 | let (input, mut visual) = build_growing_view(cx, 4); |
| 4919 | load_block_content(&input, &mut visual, "ab", "cd"); |
| 4920 | let rows_with_one_image = input.read_with(&visual, |state, _| state.mode.rows()); |
| 4921 | assert!(rows_with_one_image > 4, "{rows_with_one_image}"); |
| 4922 | input.read_with(&visual, |state, _| { |
| 4923 | let line_height = state.line_height().unwrap(); |
| 4924 | assert_eq!( |
| 4925 | state.input_bounds.size.height, |
| 4926 | line_height * rows_with_one_image as f32 |
| 4927 | ); |
| 4928 | assert!( |
| 4929 | state.display_map.content_height(line_height) <= state.input_bounds.size.height |
| 4930 | ); |
| 4931 | }); |
| 4932 | load_block_content( |
| 4933 | &input, |
| 4934 | &mut visual, |
| 4935 | "ab\ncd\nef\ngh\nij\nkl\nmn\nop\nqr\n", |
| 4936 | "cd", |
| 4937 | ); |
| 4938 | assert_eq!(input.read_with(&visual, |state, _| state.mode.rows()), 8); |
| 4939 | } |
| 4940 | |
| 4941 | #[gpui::test] |
| 4942 | fn test_block_token_caret_spans_the_row(cx: &mut TestAppContext) { |
| 4943 | let (view, mut visual) = build_block_view(cx, "ab[img]cd", 2..7); |
| 4944 | view.input.read_with(&visual, |state, _| { |
| 4945 | let line_height = state.line_height().unwrap(); |
| 4946 | let layout = state.last_layout.as_ref().unwrap(); |
| 4947 | let line = &layout.lines[0]; |
| 4948 | let before = line.position_for_index(2, layout, false).unwrap(); |
| 4949 | let after = line.position_for_index(7, layout, true).unwrap(); |
| 4950 | assert_eq!((before.x, after.x), (px(0.), px(200.))); |
| 4951 | assert_eq!(before.y, line.row_top(1, line_height)); |
| 4952 | assert_eq!(after.y, before.y); |
| 4953 | }); |
| 4954 | view.input |
| 4955 | .update(&mut visual, |state, cx| state.set_selected_range(2..2, cx)); |
| 4956 | visual.update(|window, cx| window.draw(cx).clear(cx)); |
| 4957 | let before = view |
| 4958 | .input |
| 4959 | .read_with(&visual, |state, _| state.cursor_layout().unwrap().0); |
| 4960 | assert_eq!(before.size.height, px(120.)); |
| 4961 | view.input.update(&mut visual, |state, cx| { |
| 4962 | state.set_selected_range(7..7, cx); |
| 4963 | state.cursor_line_end_affinity = true; |
| 4964 | }); |
| 4965 | visual.update(|window, cx| window.draw(cx).clear(cx)); |
| 4966 | let after = view |
| 4967 | .input |
| 4968 | .read_with(&visual, |state, _| state.cursor_layout().unwrap().0); |
| 4969 | assert_eq!(after.size.height, px(120.)); |
| 4970 | assert_eq!(after.origin.y, before.origin.y); |
| 4971 | assert_eq!(after.origin.x - before.origin.x, px(200.)); |
| 4972 | } |
| 4973 | |
| 4974 | #[gpui::test] |
| 4975 | fn test_block_token_click_beside_the_image_lands_on_its_edge(cx: &mut TestAppContext) { |
| 4976 | let (view, visual) = build_block_view(cx, "ab[img]cd", 2..7); |
| 4977 | view.input.read_with(&visual, |state, _| { |
| 4978 | let line_height = state.line_height().unwrap(); |
| 4979 | let bounds = state.last_bounds.unwrap(); |
| 4980 | let layout = state.last_layout.as_ref().unwrap(); |
| 4981 | let row_top = layout.visible_top + layout.lines[0].row_top(1, line_height); |
| 4982 | let at = |
| 4983 | |x: f32| bounds.origin + point(layout.line_number_width + px(x), row_top + px(60.)); |
| 4984 | assert_eq!(state.resolve_mouse_position(at(500.)).0, 7); |
| 4985 | assert_eq!(state.resolve_mouse_position(at(150.)).0, 7); |
| 4986 | assert_eq!(state.resolve_mouse_position(at(10.)).0, 2); |
| 4987 | }); |
| 4988 | } |
| 4989 | |
| 4990 | #[gpui::test] |
| 4991 | fn test_block_token_vertical_movement_visits_its_row(cx: &mut TestAppContext) { |
| 4992 | let (view, mut visual) = build_block_view(cx, "ab[img]cd", 2..7); |
| 4993 | let row = |view: &InputView<TextareaMode>, visual: &VisualTestContext| { |
| 4994 | view.input.read_with(visual, |state, _| { |
| 4995 | state |
| 4996 | .display_map |
| 4997 | .offset_to_wrap_display_point_with_affinity( |
| 4998 | state.cursor(), |
| 4999 | state.cursor_line_end_affinity, |
| 5000 | ) |
| 5001 | .row |
| 5002 | }) |
| 5003 | }; |
| 5004 | view.input |
| 5005 | .update(&mut visual, |state, _| state.set_cursor_to(0)); |
| 5006 | for expected_row in [1, 2] { |
| 5007 | visual.update(|window, cx| { |
| 5008 | view.input |
| 5009 | .update(cx, |state, cx| state.down(&MoveDown, window, cx)) |
| 5010 | }); |
| 5011 | assert_eq!(row(&view, &visual), expected_row); |
| 5012 | } |
| 5013 | for expected_row in [1, 0] { |
| 5014 | visual.update(|window, cx| { |
| 5015 | view.input |
| 5016 | .update(cx, |state, cx| state.up(&MoveUp, window, cx)) |
| 5017 | }); |
| 5018 | assert_eq!(row(&view, &visual), expected_row); |
| 5019 | } |
| 5020 | } |
| 5021 | |
| 5022 | #[gpui::test] |
| 5023 | fn test_block_token_scroll_to_brings_its_rows_into_view(cx: &mut TestAppContext) { |
| 5024 | let value: &'static str = |
| 5025 | Box::leak(format!("{}[img]cd", "x\n".repeat(60)).into_boxed_str()); |
| 5026 | let token_start = 120; |
| 5027 | let (view, mut visual) = build_block_view(cx, value, token_start..token_start + 5); |
| 5028 | for (offset, row) in [(token_start, 60), (token_start + 5, 61)] { |
| 5029 | view.input.update(&mut visual, |state, cx| { |
| 5030 | state.scroll_to(offset, None, cx); |
| 5031 | let line_height = state.line_height().unwrap(); |
| 5032 | let scrolled = -state.deferred_scroll_offset.unwrap().y; |
| 5033 | let top = state.display_map.row_top(row, line_height); |
| 5034 | let height = state.display_map.row_height(row, line_height); |
| 5035 | assert!(top >= scrolled, "row {row} top is above the viewport"); |
| 5036 | assert!( |
| 5037 | top + height <= scrolled + state.input_bounds.size.height, |
| 5038 | "row {row} bottom is below the viewport" |
| 5039 | ); |
| 5040 | }); |
| 5041 | } |
| 5042 | } |
| 5043 | |
| 5044 | #[gpui::test] |
| 5045 | fn test_block_token_undo_restores_uniform_rows(cx: &mut TestAppContext) { |
| 5046 | let (view, mut visual) = build_block_view(cx, "ab[img]cd", 2..7); |
| 5047 | visual.update(|window, cx| { |
| 5048 | view.input |
| 5049 | .update(cx, |state, cx| state.undo(&Undo, window, cx)) |
| 5050 | }); |
| 5051 | visual.update(|window, cx| window.draw(cx).clear(cx)); |
| 5052 | view.input.read_with(&visual, |state, _| { |
| 5053 | let line_height = state.line_height().unwrap(); |
| 5054 | assert!(state.tokens().is_empty()); |
| 5055 | assert!(state.display_map.line(0).unwrap().blocks.is_empty()); |
| 5056 | assert_eq!( |
| 5057 | state.display_map.content_height(line_height), |
| 5058 | line_height * state.display_map.wrap_row_count() as f32 |
| 5059 | ); |
| 5060 | assert_eq!(state.mode.rows(), state.display_map.wrap_row_count()); |
| 5061 | }); |
| 5062 | } |
| 5063 | |
| 5064 | #[gpui::test] |
| 5065 | fn test_inline_token_geometry_and_reentrant_activation(cx: &mut TestAppContext) { |
| 5066 | use crate::input::{InlineToken, InlineTokenPresentation}; |
| 5067 | let view = InputView::build(cx, |state| state.default_value("before @alice after")); |
| 5068 | let target = view.input.clone(); |
| 5069 | view.window_handle |
| 5070 | .update(cx, |_, window, cx| { |
| 5071 | view.input.update(cx, |state, cx| { |
| 5072 | state |
| 5073 | .replace_range_with_token( |
| 5074 | 7..13, |
| 5075 | InlineToken::new("a", "@alice"), |
| 5076 | window, |
| 5077 | cx, |
| 5078 | ) |
| 5079 | .unwrap(); |
| 5080 | state.set_token_presentation( |
| 5081 | InlineTokenPresentation::default() |
| 5082 | .token(|_, _, _| div().w(px(100.)).h(px(20.))) |
| 5083 | .on_token_click(move |_, window, cx| { |
| 5084 | target.update(cx, |state, cx| { |
| 5085 | state.set_value("activated", window, cx) |
| 5086 | }) |
| 5087 | }), |
| 5088 | ); |
| 5089 | state.focus(window, cx); |
| 5090 | state.set_selected_range(7..13, cx); |
| 5091 | }); |
| 5092 | }) |
| 5093 | .unwrap(); |
| 5094 | let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx); |
| 5095 | visual.update(|window, cx| window.draw(cx).clear(cx)); |
| 5096 | visual.update(|window, cx| { |
| 5097 | let state = view.input.read(cx); |
| 5098 | let bounds = state.range_to_bounds(&(7..13)).unwrap(); |
| 5099 | assert!((bounds.size.width - px(100.)).abs() < px(1.), "{bounds:?}"); |
| 5100 | let (left, _) = state.index_for_mouse_position(bounds.origin + point(px(10.), px(5.))); |
| 5101 | let (right, _) = state.index_for_mouse_position(bounds.origin + point(px(90.), px(5.))); |
| 5102 | assert_eq!((left, right), (7, 13)); |
| 5103 | window.dispatch_action(Box::new(ActivateToken), cx); |
| 5104 | }); |
| 5105 | visual.run_until_parked(); |
| 5106 | view.input.read_with(&visual, |state, _| { |
| 5107 | assert_eq!(state.value().as_ref(), "activated") |
| 5108 | }); |
| 5109 | } |
| 5110 | |
| 5111 | #[gpui::test] |
| 5112 | fn test_inline_token_click_selects_it(cx: &mut TestAppContext) { |
| 5113 | use crate::input::InlineToken; |
| 5114 | cx.update(crate::init); |
| 5115 | let view = InputView::build(cx, |state| state.default_value("before @alice after")); |
| 5116 | view.window_handle |
| 5117 | .update(cx, |_, window, cx| { |
| 5118 | view.input.update(cx, |state, cx| { |
| 5119 | state |
| 5120 | .replace_range_with_token( |
| 5121 | 7..13, |
| 5122 | InlineToken::new("a", "@alice"), |
| 5123 | window, |
| 5124 | cx, |
| 5125 | ) |
| 5126 | .unwrap(); |
| 5127 | state.set_selected_range(0..0, cx); |
| 5128 | }); |
| 5129 | }) |
| 5130 | .unwrap(); |
| 5131 | let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx); |
| 5132 | visual.update(|window, cx| window.draw(cx).clear(cx)); |
| 5133 | let bounds = view |
| 5134 | .input |
| 5135 | .read_with(&visual, |state, _| state.range_to_bounds(&(7..13)).unwrap()); |
| 5136 | visual.simulate_click(bounds.center(), gpui::Modifiers::default()); |
| 5137 | visual.run_until_parked(); |
| 5138 | view.input.read_with(&visual, |state, _| { |
| 5139 | assert_eq!(state.selected_range(), 7..13, "a click selects the token"); |
| 5140 | }); |
| 5141 | } |
| 5142 | |
| 5143 | #[gpui::test] |
| 5144 | fn test_inline_token_hover_reports_presence_without_selecting(cx: &mut TestAppContext) { |
| 5145 | use crate::input::{InlineToken, InlineTokenPresentation}; |
| 5146 | use gpui::{Bounds, point, px, size}; |
| 5147 | cx.update(crate::init); |
| 5148 | let view = InputView::build(cx, |state| state.default_value("be |
| 5149 | … afgekapt |