| 1 | //! Composer-owned state and behavior. |
| 2 | //! |
| 3 | //! Text editing, cursor movement, selection, paste/scrub handling, input |
| 4 | //! history navigation, and vim modal editing for the composer live here. |
| 5 | //! Methods that only touch composer fields are inherent methods on |
| 6 | //! [`ComposerState`]; methods that also need `App`-level state (redraw |
| 7 | //! flags, status messages, clipboard, workspace) stay on `App` in an |
| 8 | //! extension impl in this module. The `Deref<Target = ComposerState>` |
| 9 | //! bridge on `App` is unchanged. |
| 10 | |
| 11 | use super::*; |
| 12 | |
| 13 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 14 | pub struct ComposerHistorySearch { |
| 15 | pre_search_input: String, |
| 16 | pre_search_cursor: usize, |
| 17 | query: String, |
| 18 | selected: usize, |
| 19 | } |
| 20 | |
| 21 | impl ComposerHistorySearch { |
| 22 | fn new(pre_search_input: String, pre_search_cursor: usize) -> Self { |
| 23 | Self { |
| 24 | pre_search_input, |
| 25 | pre_search_cursor, |
| 26 | query: String::new(), |
| 27 | selected: 0, |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 33 | pub(crate) struct InputHistoryDraft { |
| 34 | input: String, |
| 35 | cursor: usize, |
| 36 | } |
| 37 | |
| 38 | pub(crate) fn char_count(text: &str) -> usize { |
| 39 | text.chars().count() |
| 40 | } |
| 41 | |
| 42 | pub(crate) fn byte_index_at_char(text: &str, char_index: usize) -> usize { |
| 43 | if char_index == 0 { |
| 44 | return 0; |
| 45 | } |
| 46 | text.char_indices() |
| 47 | .nth(char_index) |
| 48 | .map(|(idx, _)| idx) |
| 49 | .unwrap_or_else(|| text.len()) |
| 50 | } |
| 51 | |
| 52 | /// Remove the chars in `[start_char, end_char)`. Returns true when anything |
| 53 | /// was removed. Range endpoints are clamped to the text length. |
| 54 | fn remove_char_range(text: &mut String, start_char: usize, end_char: usize) -> bool { |
| 55 | if start_char >= end_char { |
| 56 | return false; |
| 57 | } |
| 58 | let start = byte_index_at_char(text, start_char); |
| 59 | let end = byte_index_at_char(text, end_char); |
| 60 | if start >= end { |
| 61 | return false; |
| 62 | } |
| 63 | text.replace_range(start..end, ""); |
| 64 | true |
| 65 | } |
| 66 | |
| 67 | /// Char index of the grapheme-cluster boundary at or before `char_index - 1` — |
| 68 | /// i.e. where the cursor lands after one "left" step. Grapheme-aware so a |
| 69 | /// single step never splits a CJK char + combining mark, emoji ZWJ sequence, |
| 70 | /// or flag pair. Returns `0` when `char_index` is `0`. |
| 71 | pub(crate) fn prev_grapheme_boundary(text: &str, char_index: usize) -> usize { |
| 72 | use unicode_segmentation::UnicodeSegmentation; |
| 73 | let mut acc = 0usize; |
| 74 | for g in text.graphemes(true) { |
| 75 | let next = acc + g.chars().count(); |
| 76 | if next >= char_index { |
| 77 | return acc; |
| 78 | } |
| 79 | acc = next; |
| 80 | } |
| 81 | acc |
| 82 | } |
| 83 | |
| 84 | /// Char index of the grapheme-cluster boundary at or before `char_index`: |
| 85 | /// the start of the cluster that contains it. Vim column moves land here so a |
| 86 | /// line change never parks the cursor inside a ZWJ or combining sequence. |
| 87 | pub(crate) fn floor_grapheme_boundary(text: &str, char_index: usize) -> usize { |
| 88 | prev_grapheme_boundary(text, char_index.saturating_add(1)).min(char_index) |
| 89 | } |
| 90 | |
| 91 | /// Char index of the first grapheme-cluster boundary strictly after |
| 92 | /// `char_index` — i.e. where the cursor lands after one "right" step. |
| 93 | /// Returns the total char count when already at or past the end. |
| 94 | pub(crate) fn next_grapheme_boundary(text: &str, char_index: usize) -> usize { |
| 95 | use unicode_segmentation::UnicodeSegmentation; |
| 96 | let mut acc = 0usize; |
| 97 | for g in text.graphemes(true) { |
| 98 | let next = acc + g.chars().count(); |
| 99 | if next > char_index { |
| 100 | return next; |
| 101 | } |
| 102 | acc = next; |
| 103 | } |
| 104 | acc |
| 105 | } |
| 106 | |
| 107 | fn normalize_paste_text(text: &str) -> String { |
| 108 | if text.contains('\r') { |
| 109 | text.replace("\r\n", "\n").replace('\r', "\n") |
| 110 | } else { |
| 111 | text.to_string() |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | fn strip_raw_mouse_report_runs(input: &str, cursor: usize) -> Option<(String, usize)> { |
| 116 | // First pass: strip the well-defined control-sequence fragment |
| 117 | // shapes that crossterm sometimes hands us as `Char(c)` keystrokes |
| 118 | // when its event reader is interrupted mid-sequence during dense |
| 119 | // streaming output (#1915). This covers OSC 8 hyperlink fragments |
| 120 | // (`]8;;URL`, including the closing `]8;;`) and Kitty keyboard |
| 121 | // protocol fragments (`[?…u`, `[>…u`, `[?u`). |
| 122 | let (after_fragments, after_fragments_cursor, fragments_changed) = |
| 123 | strip_control_sequence_fragments(input, cursor); |
| 124 | |
| 125 | // Second pass: the existing run-based filter handles SGR mouse |
| 126 | // reports (`[<35;44;18M`) and the multi-terminator burst shape |
| 127 | // (`5;46;18M;48;18M`) introduced in e63a4ba4a. It operates on a |
| 128 | // narrow char set so it can't be confused with user-typed text. |
| 129 | let chars: Vec<char> = after_fragments.chars().collect(); |
| 130 | let mut output = String::with_capacity(after_fragments.len()); |
| 131 | let mut new_cursor = 0usize; |
| 132 | let mut changed = fragments_changed; |
| 133 | let mut index = 0usize; |
| 134 | |
| 135 | while index < chars.len() { |
| 136 | if is_raw_mouse_report_run_char(chars[index]) { |
| 137 | let start = index; |
| 138 | while index < chars.len() && is_raw_mouse_report_run_char(chars[index]) { |
| 139 | index += 1; |
| 140 | } |
| 141 | let run = &chars[start..index]; |
| 142 | if let Some(keep) = raw_mouse_report_keep_mask(run) { |
| 143 | changed = true; |
| 144 | for (offset, ch) in run.iter().copied().enumerate() { |
| 145 | if !keep[offset] { |
| 146 | continue; |
| 147 | } |
| 148 | if start + offset < cursor { |
| 149 | new_cursor += 1; |
| 150 | } |
| 151 | output.push(ch); |
| 152 | } |
| 153 | continue; |
| 154 | } |
| 155 | for (offset, ch) in run.iter().copied().enumerate() { |
| 156 | if start + offset < after_fragments_cursor { |
| 157 | new_cursor += 1; |
| 158 | } |
| 159 | output.push(ch); |
| 160 | } |
| 161 | continue; |
| 162 | } |
| 163 | |
| 164 | if index < after_fragments_cursor { |
| 165 | new_cursor += 1; |
| 166 | } |
| 167 | output.push(chars[index]); |
| 168 | index += 1; |
| 169 | } |
| 170 | |
| 171 | changed.then(|| { |
| 172 | let cursor = new_cursor.min(char_count(&output)); |
| 173 | (output, cursor) |
| 174 | }) |
| 175 | } |
| 176 | |
| 177 | fn is_raw_mouse_report_run_char(ch: char) -> bool { |
| 178 | matches!(ch, '\x1b' | '[' | '<' | ';' | ':' | 'M' | 'm') || ch.is_ascii_digit() |
| 179 | } |
| 180 | |
| 181 | fn looks_like_raw_mouse_report_run(run: &[char]) -> bool { |
| 182 | if run.len() < 5 { |
| 183 | return false; |
| 184 | } |
| 185 | let has_separator = run.iter().any(|ch| matches!(ch, ';' | ':')); |
| 186 | let terminators = run.iter().filter(|ch| matches!(ch, 'M' | 'm')).count(); |
| 187 | if !has_separator || terminators == 0 { |
| 188 | return false; |
| 189 | } |
| 190 | has_sgr_mouse_marker(run) || terminators >= 2 |
| 191 | } |
| 192 | |
| 193 | fn has_sgr_mouse_marker(run: &[char]) -> bool { |
| 194 | run.windows(2).any(|window| window == ['[', '<']) |
| 195 | } |
| 196 | |
| 197 | fn raw_mouse_report_keep_mask(run: &[char]) -> Option<Vec<bool>> { |
| 198 | let mut ranges: Vec<(usize, usize)> = Vec::new(); |
| 199 | let mut index = 0usize; |
| 200 | |
| 201 | while index < run.len() { |
| 202 | let (start, body_start) = if run[index] == '\x1b' |
| 203 | && run.get(index + 1) == Some(&'[') |
| 204 | && run.get(index + 2) == Some(&'<') |
| 205 | { |
| 206 | (index, index + 3) |
| 207 | } else if run[index] == '[' && run.get(index + 1) == Some(&'<') { |
| 208 | (index, index + 2) |
| 209 | } else { |
| 210 | index += 1; |
| 211 | continue; |
| 212 | }; |
| 213 | |
| 214 | let mut end = body_start; |
| 215 | let mut has_digit = false; |
| 216 | let mut has_separator = false; |
| 217 | let mut matched = false; |
| 218 | while end < run.len() { |
| 219 | match run[end] { |
| 220 | '0'..='9' => { |
| 221 | has_digit = true; |
| 222 | end += 1; |
| 223 | } |
| 224 | ';' | ':' => { |
| 225 | has_separator = true; |
| 226 | end += 1; |
| 227 | } |
| 228 | 'M' | 'm' if has_digit && has_separator => { |
| 229 | ranges.push((start, end + 1)); |
| 230 | index = end + 1; |
| 231 | matched = true; |
| 232 | break; |
| 233 | } |
| 234 | _ => break, |
| 235 | } |
| 236 | } |
| 237 | if !matched { |
| 238 | index = index.saturating_add(1); |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | if ranges.is_empty() { |
| 243 | if looks_like_raw_mouse_report_run(run) { |
| 244 | return Some(vec![false; run.len()]); |
| 245 | } |
| 246 | return None; |
| 247 | } |
| 248 | |
| 249 | ranges.sort_unstable_by_key(|(start, _)| *start); |
| 250 | let first_start = ranges[0].0; |
| 251 | let mut prefix_start = first_start; |
| 252 | while prefix_start > 0 && is_raw_mouse_report_fragment_char(run[prefix_start - 1]) { |
| 253 | prefix_start -= 1; |
| 254 | } |
| 255 | if prefix_start < first_start |
| 256 | && looks_like_raw_mouse_report_fragment(&run[prefix_start..first_start]) |
| 257 | { |
| 258 | ranges.push((prefix_start, first_start)); |
| 259 | } |
| 260 | |
| 261 | let last_end = ranges.iter().map(|(_, end)| *end).max().unwrap_or_default(); |
| 262 | if last_end < run.len() && looks_like_raw_mouse_report_fragment(&run[last_end..]) { |
| 263 | ranges.push((last_end, run.len())); |
| 264 | } |
| 265 | |
| 266 | ranges.sort_unstable_by_key(|(start, _)| *start); |
| 267 | let mut keep = vec![true; run.len()]; |
| 268 | for (start, end) in ranges { |
| 269 | for slot in keep.iter_mut().take(end.min(run.len())).skip(start) { |
| 270 | *slot = false; |
| 271 | } |
| 272 | } |
| 273 | Some(keep) |
| 274 | } |
| 275 | |
| 276 | fn is_raw_mouse_report_fragment_char(ch: char) -> bool { |
| 277 | matches!(ch, ';' | ':' | 'M' | 'm') || ch.is_ascii_digit() |
| 278 | } |
| 279 | |
| 280 | fn looks_like_raw_mouse_report_fragment(run: &[char]) -> bool { |
| 281 | if run.len() < 4 { |
| 282 | return false; |
| 283 | } |
| 284 | run.iter().any(|ch| ch.is_ascii_digit()) |
| 285 | && run.iter().any(|ch| matches!(ch, ';' | ':')) |
| 286 | && run.iter().any(|ch| matches!(ch, 'M' | 'm')) |
| 287 | } |
| 288 | |
| 289 | /// Scan `input` for control-sequence fragment shapes (#1915) — OSC 8 |
| 290 | /// hyperlinks and Kitty keyboard protocol responses — and excise each |
| 291 | /// match. Returns `(output, new_cursor, changed)`. Cursor positions |
| 292 | /// inside an excised fragment are moved to the fragment's start. |
| 293 | /// |
| 294 | /// The match shapes are deliberately narrow so legitimate text like |
| 295 | /// `[is this ok?]` or a typed URL survives untouched: |
| 296 | /// |
| 297 | /// - **OSC 8**: `(\x1b?)] 8 ; ...` consuming everything up to the |
| 298 | /// first BEL (`\x07`), `\x1b\\`, lone `\\`, or the next `\x1b]8;` |
| 299 | /// block — terminator characters are optional because crossterm may |
| 300 | /// have already consumed them. |
| 301 | /// - **Kitty CSI**: `(\x1b?) [ (? | > | < | =) ... u` — the |
| 302 | /// private-parameter prefix is what distinguishes a Kitty response |
| 303 | /// from a user-typed `[…u` (which is exceedingly rare and would |
| 304 | /// need an explicit private-parameter byte to be a real CSI). |
| 305 | fn strip_control_sequence_fragments(input: &str, cursor: usize) -> (String, usize, bool) { |
| 306 | let chars: Vec<char> = input.chars().collect(); |
| 307 | let mut output = String::with_capacity(input.len()); |
| 308 | let mut new_cursor = 0usize; |
| 309 | let mut changed = false; |
| 310 | let mut index = 0usize; |
| 311 | |
| 312 | while index < chars.len() { |
| 313 | if let Some(end) = match_osc8_fragment(&chars, index) { |
| 314 | // The excised span contributes nothing to `output`, so |
| 315 | // `new_cursor` simply doesn't tick for any of those |
| 316 | // characters. A cursor that was inside the span ends up at |
| 317 | // the fragment's start position in the rewritten input, |
| 318 | // which matches the existing run-stripper's behavior. |
| 319 | index = end; |
| 320 | changed = true; |
| 321 | continue; |
| 322 | } |
| 323 | |
| 324 | if let Some(end) = match_kitty_csi_fragment(&chars, index) { |
| 325 | index = end; |
| 326 | changed = true; |
| 327 | continue; |
| 328 | } |
| 329 | |
| 330 | if index < cursor { |
| 331 | new_cursor += 1; |
| 332 | } |
| 333 | output.push(chars[index]); |
| 334 | index += 1; |
| 335 | } |
| 336 | |
| 337 | let cursor = new_cursor.min(char_count(&output)); |
| 338 | (output, cursor, changed) |
| 339 | } |
| 340 | |
| 341 | /// If an OSC 8 hyperlink fragment starts at `chars[start]`, return its |
| 342 | /// end index (exclusive). The leading `ESC` is optional because |
| 343 | /// crossterm's event parser often consumes it before reclassifying the |
| 344 | /// tail as keystrokes. |
| 345 | fn match_osc8_fragment(chars: &[char], start: usize) -> Option<usize> { |
| 346 | let body_start = if chars.get(start) == Some(&'\x1b') |
| 347 | && chars.get(start + 1) == Some(&']') |
| 348 | && chars.get(start + 2) == Some(&'8') |
| 349 | && chars.get(start + 3) == Some(&';') |
| 350 | { |
| 351 | start + 4 |
| 352 | } else if chars.get(start) == Some(&']') |
| 353 | && chars.get(start + 1) == Some(&'8') |
| 354 | && chars.get(start + 2) == Some(&';') |
| 355 | { |
| 356 | start + 3 |
| 357 | } else { |
| 358 | return None; |
| 359 | }; |
| 360 | |
| 361 | // After `]8;` we expect the OSC 8 payload: an optional second `;` |
| 362 | // (params separator), then the URL (or empty for the closing |
| 363 | // wrapper), then a terminator. We deliberately stop at the first |
| 364 | // ASCII whitespace so a typed `]8;` followed by real prose can't |
| 365 | // swallow the user's words — real OSC 8 URLs don't contain spaces. |
| 366 | let mut end = body_start; |
| 367 | while end < chars.len() { |
| 368 | let ch = chars[end]; |
| 369 | // BEL terminator. |
| 370 | if ch == '\x07' { |
| 371 | return Some(end + 1); |
| 372 | } |
| 373 | // `ESC \\` string terminator (ST). |
| 374 | if ch == '\x1b' && chars.get(end + 1) == Some(&'\\') { |
| 375 | return Some(end + 2); |
| 376 | } |
| 377 | // Lone `\\` — crossterm sometimes delivers ST with the leading |
| 378 | // ESC already consumed, leaving just `\\` as a Char keystroke. |
| 379 | if ch == '\\' { |
| 380 | return Some(end + 1); |
| 381 | } |
| 382 | // Start of the next OSC 8 wrapper (closing `]8;;` glued to the |
| 383 | // body) — close the current fragment here so the next iteration |
| 384 | // matches that one separately. |
| 385 | if ch == '\x1b' && chars.get(end + 1) == Some(&']') { |
| 386 | return Some(end); |
| 387 | } |
| 388 | if ch == ']' && chars.get(end + 1) == Some(&'8') && chars.get(end + 2) == Some(&';') { |
| 389 | return Some(end); |
| 390 | } |
| 391 | if ch.is_whitespace() { |
| 392 | // We never crossed a terminator, so this isn't a real |
| 393 | // fragment — give up rather than eat user prose. |
| 394 | return None; |
| 395 | } |
| 396 | end += 1; |
| 397 | } |
| 398 | |
| 399 | // Reached end of input without a terminator or whitespace. Treat as |
| 400 | // a fragment in flight (its tail will arrive on a later keystroke |
| 401 | // and get filtered then). |
| 402 | Some(end) |
| 403 | } |
| 404 | |
| 405 | /// If a private-parameter CSI fragment starts at `chars[start]`, return its |
| 406 | /// end index (exclusive). Shape: `(ESC)? [ (? | > | < | =) [0-9;:]* <final>` |
| 407 | /// where `<final>` is any ASCII letter. This covers the Kitty keyboard |
| 408 | /// protocol (`…u`) *and* the DEC private mode set/reset sequences a terminal |
| 409 | /// emits during a session — bracketed paste (`[?2004h`/`[?2004l`), mouse |
| 410 | /// capture (`[?1000h`), focus reporting (`[?1004h`), and synchronized output |
| 411 | /// (`[?2026h`). Those end in `h`/`l`, not `u`, so the old `u`-only terminator |
| 412 | /// let the leading `[` leak into the composer during dense streaming (#2592, |
| 413 | /// regression of #1915). The private-parameter byte (`?`, `>`, `<`, `=`) is |
| 414 | /// what keeps this distinct from text the user might plausibly type. |
| 415 | fn match_kitty_csi_fragment(chars: &[char], start: usize) -> Option<usize> { |
| 416 | let after_csi = if chars.get(start) == Some(&'\x1b') && chars.get(start + 1) == Some(&'[') { |
| 417 | start + 2 |
| 418 | } else if chars.get(start) == Some(&'[') { |
| 419 | start + 1 |
| 420 | } else { |
| 421 | return None; |
| 422 | }; |
| 423 | |
| 424 | let priv_byte = chars.get(after_csi)?; |
| 425 | if !matches!(priv_byte, '?' | '>' | '<' | '=') { |
| 426 | return None; |
| 427 | } |
| 428 | |
| 429 | let mut end = after_csi + 1; |
| 430 | let mut saw_param = false; |
| 431 | while end < chars.len() { |
| 432 | let ch = chars[end]; |
| 433 | if ch.is_ascii_digit() || ch == ';' || ch == ':' { |
| 434 | saw_param = true; |
| 435 | end += 1; |
| 436 | continue; |
| 437 | } |
| 438 | // Final byte. The Kitty keyboard protocol ends in `u` and is valid |
| 439 | // with no parameters (`[?u`). DEC private mode set/reset ends in |
| 440 | // `h`/`l` and always carries a numeric mode — bracketed paste |
| 441 | // (`[?2004h`/`l`), mouse capture (`[?1000h`), focus reporting |
| 442 | // (`[?1004h`), synchronized output (`[?2026h`). Require a parameter |
| 443 | // before `h`/`l` so ordinary text like `[?help]` is left untouched. |
| 444 | return match ch { |
| 445 | 'u' => Some(end + 1), |
| 446 | 'h' | 'l' if saw_param => Some(end + 1), |
| 447 | _ => None, |
| 448 | }; |
| 449 | } |
| 450 | None |
| 451 | } |
| 452 | |
| 453 | pub(crate) const MAX_SUBMITTED_INPUT_CHARS: usize = 16_000; |
| 454 | |
| 455 | /// Bounded preview shown inside the attachment card for a consolidated |
| 456 | /// paste. Small enough to stay a summary, large enough to recognize the |
| 457 | /// content. |
| 458 | const PASTE_ATTACHMENT_PREVIEW_CHARS: usize = 240; |
| 459 | |
| 460 | /// Human-readable submission text for a paste-backed input: a size header, |
| 461 | /// the `@`-mention that attaches the file for the model, and a bounded |
| 462 | /// preview. The mention must survive verbatim — file-mention resolution |
| 463 | /// scans the submitted text for it. |
| 464 | fn paste_attachment_display(reference: &str, full: &str) -> String { |
| 465 | let chars = full.chars().count(); |
| 466 | let preview_lines: Vec<&str> = full.lines().take(3).collect(); |
| 467 | let joined = preview_lines.join("\n"); |
| 468 | let preview: String = joined |
| 469 | .chars() |
| 470 | .take(PASTE_ATTACHMENT_PREVIEW_CHARS) |
| 471 | .collect(); |
| 472 | let elided = if chars > PASTE_ATTACHMENT_PREVIEW_CHARS { |
| 473 | "…" |
| 474 | } else { |
| 475 | "" |
| 476 | }; |
| 477 | format!( |
| 478 | "[Pasted content attached · {chars} chars]\n{reference}\n--- preview ---\n{preview}{elided}" |
| 479 | ) |
| 480 | } |
| 481 | /// Maximum characters displayed in the composer for oversized input. |
| 482 | /// Beyond this, the text is truncated for rendering but the full content |
| 483 | /// is preserved for model submission (#3263). |
| 484 | const MAX_COMPOSER_DISPLAY_CHARS: usize = 4_000; |
| 485 | const MAX_DRAFT_HISTORY: usize = 50; |
| 486 | |
| 487 | impl ComposerState { |
| 488 | /// Re-derive the "this line began as a command" claim from the current |
| 489 | /// composer text (#5925). |
| 490 | /// |
| 491 | /// Called after every composer mutation. A user edit that removes the |
| 492 | /// leading `/` releases the claim — removing it was intentional. Bytes |
| 493 | /// lost between the terminal and the composer never pass through here, |
| 494 | /// which is exactly the difference the submit guard needs: a claim that |
| 495 | /// survives to Enter means the line still starts with `/` and must be |
| 496 | /// dispatched as a command, never re-read as a prose prompt. |
| 497 | pub(crate) fn resync_command_line_claim(&mut self) { |
| 498 | self.line_began_with_slash &= self.input.trim_start().starts_with('/'); |
| 499 | } |
| 500 | |
| 501 | /// Whether this line is claimed as a command: it began with a typed `/` |
| 502 | /// and still starts with one. |
| 503 | pub(crate) fn command_line_claimed(&self) -> bool { |
| 504 | self.line_began_with_slash && looks_like_slash_command_input(&self.input) |
| 505 | } |
| 506 | |
| 507 | /// When the user starts editing a truncated oversized paste, restore the |
| 508 | /// full text so they can see and edit the complete content (#3263). |
| 509 | fn auto_expand_oversized_paste(&mut self) { |
| 510 | if let Some(full) = self.oversized_paste_full_text.take() { |
| 511 | self.input = full; |
| 512 | self.resync_command_line_claim(); |
| 513 | // Clamp cursor to the new length instead of resetting to 0, |
| 514 | // so the user's position in the truncated preview is preserved. |
| 515 | self.cursor_position = self.cursor_position.min(char_count(&self.input)); |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | pub fn composer_attachment_count(&self) -> usize { |
| 520 | codewhale_core::media_attachment_references(&self.input).len() |
| 521 | } |
| 522 | |
| 523 | pub fn selected_composer_attachment_index(&self) -> Option<usize> { |
| 524 | let count = self.composer_attachment_count(); |
| 525 | self.selected_attachment_index |
| 526 | .filter(|index| *index < count) |
| 527 | } |
| 528 | |
| 529 | fn strip_raw_mouse_reports_from_input(&mut self) { |
| 530 | if let Some((input, cursor_position)) = |
| 531 | strip_raw_mouse_report_runs(&self.input, self.cursor_position) |
| 532 | { |
| 533 | self.input = input; |
| 534 | self.resync_command_line_claim(); |
| 535 | self.cursor_position = cursor_position; |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | // === Selection helpers === |
| 540 | /// Return the (start, end) of the active selection, or `None`. |
| 541 | /// `start` is inclusive, `end` is exclusive; both are char indices. |
| 542 | pub fn selection_range(&self) -> Option<(usize, usize)> { |
| 543 | let total = char_count(&self.input); |
| 544 | let anchor = self.selection_anchor?.min(total); |
| 545 | let cursor = self.cursor_position.min(total); |
| 546 | if anchor == cursor { |
| 547 | return None; |
| 548 | } |
| 549 | Some(if anchor < cursor { |
| 550 | (anchor, cursor) |
| 551 | } else { |
| 552 | (cursor, anchor) |
| 553 | }) |
| 554 | } |
| 555 | |
| 556 | /// Return the selected text, or empty string if no selection. |
| 557 | pub fn selected_text(&self) -> String { |
| 558 | self.selection_range() |
| 559 | .map(|(s, e)| { |
| 560 | let sb = byte_index_at_char(&self.input, s); |
| 561 | let eb = byte_index_at_char(&self.input, e); |
| 562 | self.input[sb..eb].to_string() |
| 563 | }) |
| 564 | .unwrap_or_default() |
| 565 | } |
| 566 | |
| 567 | /// Clear the selection without moving the cursor. |
| 568 | pub fn clear_selection(&mut self) { |
| 569 | self.selection_anchor = None; |
| 570 | } |
| 571 | |
| 572 | /// Returns `true` when vim mode is active and the composer is in Normal |
| 573 | /// mode, which means character keys should NOT be inserted as text. |
| 574 | #[must_use] |
| 575 | pub fn vim_is_normal_mode(&self) -> bool { |
| 576 | self.vim_enabled && self.vim_mode == VimMode::Normal |
| 577 | } |
| 578 | |
| 579 | /// Returns `true` when vim mode is active and the composer is in Visual mode. |
| 580 | #[must_use] |
| 581 | pub fn vim_is_visual_mode(&self) -> bool { |
| 582 | self.vim_enabled && self.vim_mode == VimMode::Visual |
| 583 | } |
| 584 | |
| 585 | pub fn stash_current_input_for_recovery(&mut self) { |
| 586 | // Before stashing, expand any truncated paste so the saved draft |
| 587 | // contains the full text, not the truncated preview (#3263). |
| 588 | self.auto_expand_oversized_paste(); |
| 589 | let draft = self.input.clone(); |
| 590 | if draft.trim().is_empty() { |
| 591 | self.clear_undo_buffer = None; |
| 592 | return; |
| 593 | } |
| 594 | self.clear_undo_buffer = Some(draft.clone()); |
| 595 | self.remember_draft_for_recovery(draft); |
| 596 | } |
| 597 | |
| 598 | fn remember_draft_for_recovery(&mut self, draft: String) { |
| 599 | if draft.trim().is_empty() { |
| 600 | return; |
| 601 | } |
| 602 | self.draft_history.retain(|existing| existing != &draft); |
| 603 | self.draft_history.push_back(draft); |
| 604 | while self.draft_history.len() > MAX_DRAFT_HISTORY { |
| 605 | let _ = self.draft_history.pop_front(); |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | pub fn is_history_search_active(&self) -> bool { |
| 610 | self.composer_history_search.is_some() |
| 611 | } |
| 612 | |
| 613 | pub fn history_search_query(&self) -> Option<&str> { |
| 614 | self.composer_history_search |
| 615 | .as_ref() |
| 616 | .map(|search| search.query.as_str()) |
| 617 | } |
| 618 | |
| 619 | pub fn history_search_selected_index(&self) -> usize { |
| 620 | self.composer_history_search |
| 621 | .as_ref() |
| 622 | .map_or(0, |search| search.selected) |
| 623 | } |
| 624 | |
| 625 | pub fn composer_display_input(&self) -> &str { |
| 626 | self.history_search_query().unwrap_or(&self.input) |
| 627 | } |
| 628 | |
| 629 | pub fn composer_display_cursor(&self) -> usize { |
| 630 | self.composer_history_search |
| 631 | .as_ref() |
| 632 | .map_or(self.cursor_position, |search| char_count(&search.query)) |
| 633 | } |
| 634 | |
| 635 | pub fn history_search_matches(&self) -> Vec<String> { |
| 636 | let Some(query) = self.history_search_query() else { |
| 637 | return Vec::new(); |
| 638 | }; |
| 639 | self.history_search_matches_for_query(query) |
| 640 | } |
| 641 | |
| 642 | fn history_search_matches_for_query(&self, query: &str) -> Vec<String> { |
| 643 | let normalized_query = query.trim().to_lowercase(); |
| 644 | let mut seen: HashSet<&str> = HashSet::new(); |
| 645 | let mut matches = Vec::new(); |
| 646 | |
| 647 | for candidate in self |
| 648 | .draft_history |
| 649 | .iter() |
| 650 | .rev() |
| 651 | .chain(self.input_history.iter().rev()) |
| 652 | { |
| 653 | if candidate.trim().is_empty() || !seen.insert(candidate.as_str()) { |
| 654 | continue; |
| 655 | } |
| 656 | if normalized_query.is_empty() || candidate.to_lowercase().contains(&normalized_query) { |
| 657 | matches.push(candidate.clone()); |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | matches |
| 662 | } |
| 663 | |
| 664 | fn clamp_history_search_selection(&mut self) { |
| 665 | let Some(search) = self.composer_history_search.as_ref() else { |
| 666 | return; |
| 667 | }; |
| 668 | let selected = search.selected; |
| 669 | let query = search.query.clone(); |
| 670 | let match_count = self.history_search_matches_for_query(&query).len(); |
| 671 | if let Some(search) = self.composer_history_search.as_mut() { |
| 672 | search.selected = if match_count == 0 { |
| 673 | 0 |
| 674 | } else { |
| 675 | selected.min(match_count.saturating_sub(1)) |
| 676 | }; |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | pub fn history_up(&mut self) { |
| 681 | if self.input_history.is_empty() { |
| 682 | return; |
| 683 | } |
| 684 | if self.history_index.is_none() { |
| 685 | // Expand truncated paste first so the saved draft contains the |
| 686 | // full text instead of the truncated preview (#3263). |
| 687 | self.auto_expand_oversized_paste(); |
| 688 | self.history_navigation_draft = Some(InputHistoryDraft { |
| 689 | input: self.input.clone(), |
| 690 | cursor: self.cursor_position, |
| 691 | }); |
| 692 | } |
| 693 | let new_index = match self.history_index { |
| 694 | None => self.input_history.len().saturating_sub(1), |
| 695 | Some(i) => i.saturating_sub(1), |
| 696 | }; |
| 697 | self.history_index = Some(new_index); |
| 698 | self.input = self.input_history[new_index].clone(); |
| 699 | self.resync_command_line_claim(); |
| 700 | self.cursor_position = char_count(&self.input); |
| 701 | self.selection_anchor = None; |
| 702 | self.selected_attachment_index = None; |
| 703 | self.slash_menu_hidden = false; |
| 704 | self.paste_burst.clear_after_explicit_paste(); |
| 705 | } |
| 706 | |
| 707 | fn clear_input_history_navigation(&mut self) { |
| 708 | self.history_index = None; |
| 709 | self.history_navigation_draft = None; |
| 710 | } |
| 711 | } |
| 712 | |
| 713 | impl App { |
| 714 | pub fn insert_str(&mut self, text: &str) { |
| 715 | if text.is_empty() { |
| 716 | return; |
| 717 | } |
| 718 | // Any edit detaches a recalled history entry (mirrors insert_char): |
| 719 | // without this a paste typed while navigating stays on a stale index |
| 720 | // and the next Up/Down silently discards the pasted text. |
| 721 | self.clear_input_history_navigation(); |
| 722 | self.auto_expand_oversized_paste(); |
| 723 | self.delete_selection(); |
| 724 | self.selected_attachment_index = None; |
| 725 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 726 | let byte_index = byte_index_at_char(&self.input, cursor); |
| 727 | self.input.insert_str(byte_index, text); |
| 728 | self.resync_command_line_claim(); |
| 729 | self.cursor_position = cursor + char_count(text); |
| 730 | self.strip_raw_mouse_reports_from_input(); |
| 731 | self.slash_menu_hidden = false; |
| 732 | self.mention_menu_hidden = false; |
| 733 | self.mention_menu_selected = 0; |
| 734 | self.needs_redraw = true; |
| 735 | } |
| 736 | |
| 737 | pub fn insert_paste_text(&mut self, text: &str) { |
| 738 | if let Some(pending) = self.paste_burst.flush_before_modified_input() { |
| 739 | self.insert_str(&pending); |
| 740 | } |
| 741 | let normalized = normalize_paste_text(text); |
| 742 | if !normalized.is_empty() { |
| 743 | self.insert_str(&normalized); |
| 744 | } |
| 745 | self.paste_burst.clear_after_explicit_paste(); |
| 746 | // Large pasted input stays editable and visible until submit. The |
| 747 | // submit-time safety net consolidates oversized composer content into |
| 748 | // an @paste-...md mention before dispatch, so no path silently |
| 749 | // truncates user input. |
| 750 | // self.consolidate_large_input_if_oversized(); // deferred to submit time |
| 751 | } |
| 752 | |
| 753 | pub fn insert_media_attachment(&mut self, kind: &str, path: &Path, description: Option<&str>) { |
| 754 | let reference = media_attachment_reference(kind, path, description); |
| 755 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 756 | let byte_index = byte_index_at_char(&self.input, cursor); |
| 757 | let needs_prefix_newline = self.input[..byte_index] |
| 758 | .chars() |
| 759 | .last() |
| 760 | .is_some_and(|ch| !ch.is_whitespace()); |
| 761 | let needs_suffix_newline = self.input[byte_index..] |
| 762 | .chars() |
| 763 | .next() |
| 764 | .is_some_and(|ch| !ch.is_whitespace()); |
| 765 | |
| 766 | let mut inserted = String::new(); |
| 767 | if needs_prefix_newline { |
| 768 | inserted.push('\n'); |
| 769 | } |
| 770 | inserted.push_str(&reference); |
| 771 | if needs_suffix_newline || self.input[byte_index..].is_empty() { |
| 772 | inserted.push('\n'); |
| 773 | } |
| 774 | self.insert_str(&inserted); |
| 775 | self.paste_burst.clear_after_explicit_paste(); |
| 776 | } |
| 777 | |
| 778 | pub fn select_previous_composer_attachment(&mut self) -> bool { |
| 779 | let count = self.composer_attachment_count(); |
| 780 | if count == 0 { |
| 781 | self.selected_attachment_index = None; |
| 782 | return false; |
| 783 | } |
| 784 | |
| 785 | let next = self |
| 786 | .selected_composer_attachment_index() |
| 787 | .map_or(count.saturating_sub(1), |index| index.saturating_sub(1)); |
| 788 | self.selected_attachment_index = Some(next); |
| 789 | self.cursor_position = 0; |
| 790 | self.status_message = Some("Attachment selected - Backspace/Delete removes it".to_string()); |
| 791 | self.needs_redraw = true; |
| 792 | true |
| 793 | } |
| 794 | |
| 795 | pub fn select_next_composer_attachment(&mut self) -> bool { |
| 796 | let count = self.composer_attachment_count(); |
| 797 | let Some(index) = self.selected_composer_attachment_index() else { |
| 798 | return false; |
| 799 | }; |
| 800 | if index + 1 < count { |
| 801 | self.selected_attachment_index = Some(index + 1); |
| 802 | self.status_message = |
| 803 | Some("Attachment selected - Backspace/Delete removes it".to_string()); |
| 804 | } else { |
| 805 | self.selected_attachment_index = None; |
| 806 | self.status_message = Some("Composer focused".to_string()); |
| 807 | } |
| 808 | self.needs_redraw = true; |
| 809 | true |
| 810 | } |
| 811 | |
| 812 | pub fn clear_composer_attachment_selection(&mut self) -> bool { |
| 813 | if self.selected_attachment_index.take().is_some() { |
| 814 | self.status_message = Some("Composer focused".to_string()); |
| 815 | self.needs_redraw = true; |
| 816 | true |
| 817 | } else { |
| 818 | false |
| 819 | } |
| 820 | } |
| 821 | |
| 822 | pub fn remove_selected_composer_attachment(&mut self) -> bool { |
| 823 | let references = codewhale_core::media_attachment_references(&self.input); |
| 824 | let Some(index) = self |
| 825 | .selected_composer_attachment_index() |
| 826 | .filter(|index| *index < references.len()) |
| 827 | else { |
| 828 | self.selected_attachment_index = None; |
| 829 | return false; |
| 830 | }; |
| 831 | let reference = references[index].clone(); |
| 832 | let cursor_byte = byte_index_at_char(&self.input, self.cursor_position); |
| 833 | let new_cursor_byte = if cursor_byte <= reference.start_byte { |
| 834 | cursor_byte |
| 835 | } else if cursor_byte >= reference.end_byte { |
| 836 | cursor_byte.saturating_sub(reference.end_byte - reference.start_byte) |
| 837 | } else { |
| 838 | reference.start_byte |
| 839 | }; |
| 840 | |
| 841 | self.input |
| 842 | .replace_range(reference.start_byte..reference.end_byte, ""); |
| 843 | self.cursor_position = self.input[..new_cursor_byte.min(self.input.len())] |
| 844 | .chars() |
| 845 | .count(); |
| 846 | let remaining = self.composer_attachment_count(); |
| 847 | self.selected_attachment_index = if remaining == 0 { |
| 848 | None |
| 849 | } else { |
| 850 | Some(index.min(remaining.saturating_sub(1))) |
| 851 | }; |
| 852 | self.slash_menu_hidden = false; |
| 853 | self.mention_menu_hidden = false; |
| 854 | self.mention_menu_selected = 0; |
| 855 | self.status_message = Some(format!("Removed attachment: {}", reference.path)); |
| 856 | self.needs_redraw = true; |
| 857 | true |
| 858 | } |
| 859 | |
| 860 | #[cfg(test)] |
| 861 | pub fn flush_paste_burst_if_due(&mut self, now: Instant) -> bool { |
| 862 | match self.paste_burst.flush_if_due(now) { |
| 863 | FlushResult::Paste(text) => { |
| 864 | self.insert_str(&text); |
| 865 | true |
| 866 | } |
| 867 | FlushResult::Typed(ch) => { |
| 868 | self.insert_char(ch); |
| 869 | true |
| 870 | } |
| 871 | FlushResult::SuppressionExpired => { |
| 872 | self.needs_redraw = true; |
| 873 | true |
| 874 | } |
| 875 | FlushResult::None => false, |
| 876 | } |
| 877 | } |
| 878 | |
| 879 | pub(crate) fn take_paste_burst_flush_if_enabled(&mut self, now: Instant) -> FlushResult { |
| 880 | if self.use_paste_burst_detection { |
| 881 | self.paste_burst.flush_if_due(now) |
| 882 | } else { |
| 883 | FlushResult::None |
| 884 | } |
| 885 | } |
| 886 | |
| 887 | pub fn paste_burst_next_flush_delay_if_enabled(&self, now: Instant) -> Option<Duration> { |
| 888 | if self.use_paste_burst_detection { |
| 889 | self.paste_burst.next_flush_delay(now) |
| 890 | } else { |
| 891 | None |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | pub fn flush_paste_burst_before_modified_input_if_enabled(&mut self) -> Option<String> { |
| 896 | if self.use_paste_burst_detection { |
| 897 | self.paste_burst.flush_before_modified_input() |
| 898 | } else { |
| 899 | None |
| 900 | } |
| 901 | } |
| 902 | |
| 903 | /// Paste from clipboard into input. |
| 904 | /// |
| 905 | /// Returns whether content was inserted. In SSH sessions without a |
| 906 | /// forwarded graphical display, the terminal client owns paste, so direct |
| 907 | /// clipboard shortcuts surface the local terminal-paste instruction while |
| 908 | /// `Event::Paste` remains the data path. |
| 909 | pub fn paste_from_clipboard(&mut self) -> bool { |
| 910 | if self.clipboard.requires_terminal_paste() { |
| 911 | self.status_message = Some(self.tr(MessageId::ClipboardSshPasteHint).into_owned()); |
| 912 | return false; |
| 913 | } |
| 914 | if let Some(content) = self.clipboard.read_markdown(self.workspace.as_path()) { |
| 915 | self.apply_clipboard_content(content); |
| 916 | return true; |
| 917 | } |
| 918 | // The read cannot tell an empty clipboard from an unreadable one; |
| 919 | // either way the user asked to paste and nothing happened. |
| 920 | self.status_message = Some(self.tr(MessageId::ClipboardNothingToPaste).into_owned()); |
| 921 | false |
| 922 | } |
| 923 | |
| 924 | pub fn apply_clipboard_content(&mut self, content: ClipboardContent) { |
| 925 | match content { |
| 926 | ClipboardContent::Text(text) => { |
| 927 | self.insert_paste_text(&text); |
| 928 | } |
| 929 | ClipboardContent::Image(pasted) => { |
| 930 | let description = format!("{} ({})", pasted.short_label(), pasted.size_label()); |
| 931 | self.insert_media_attachment("image", &pasted.path, Some(&description)); |
| 932 | self.status_message = Some(format!("Attached image: {description}")); |
| 933 | } |
| 934 | } |
| 935 | } |
| 936 | |
| 937 | pub fn insert_char(&mut self, c: char) { |
| 938 | self.acknowledge_sticky_on_composer_activity(); |
| 939 | self.clear_input_history_navigation(); |
| 940 | self.auto_expand_oversized_paste(); |
| 941 | self.delete_selection(); |
| 942 | self.selected_attachment_index = None; |
| 943 | // #5925: a line that starts with a typed `/` is a command from its |
| 944 | // first byte, and stays one until Enter. Recorded here — the only |
| 945 | // place a character reaches the composer by typing — so the submit |
| 946 | // guard can tell a lost `/` from a deleted one. |
| 947 | let starts_line = self.input.trim().is_empty(); |
| 948 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 949 | let byte_index = byte_index_at_char(&self.input, cursor); |
| 950 | self.input.insert(byte_index, c); |
| 951 | if starts_line { |
| 952 | self.line_began_with_slash = c == '/'; |
| 953 | } |
| 954 | self.resync_command_line_claim(); |
| 955 | self.cursor_position = cursor + 1; |
| 956 | self.strip_raw_mouse_reports_from_input(); |
| 957 | self.slash_menu_hidden = false; |
| 958 | self.mention_menu_hidden = false; |
| 959 | self.mention_menu_selected = 0; |
| 960 | self.needs_redraw = true; |
| 961 | } |
| 962 | |
| 963 | pub fn delete_char(&mut self) { |
| 964 | self.clear_input_history_navigation(); |
| 965 | self.auto_expand_oversized_paste(); |
| 966 | if self.delete_selection() { |
| 967 | return; |
| 968 | } |
| 969 | self.selected_attachment_index = None; |
| 970 | if self.cursor_position == 0 { |
| 971 | return; |
| 972 | } |
| 973 | // Grapheme-aware: Backspace removes the whole cluster before the |
| 974 | // cursor (emoji ZWJ sequence, flag pair, CJK char + combining mark), |
| 975 | // never a lone scalar out of the middle of one. |
| 976 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 977 | let target = prev_grapheme_boundary(&self.input, cursor); |
| 978 | let removed = remove_char_range(&mut self.input, target, cursor); |
| 979 | self.resync_command_line_claim(); |
| 980 | if removed { |
| 981 | self.cursor_position = target; |
| 982 | self.slash_menu_hidden = false; |
| 983 | self.mention_menu_hidden = false; |
| 984 | self.mention_menu_selected = 0; |
| 985 | self.needs_redraw = true; |
| 986 | } |
| 987 | } |
| 988 | |
| 989 | pub fn delete_char_forward(&mut self) { |
| 990 | self.clear_input_history_navigation(); |
| 991 | self.auto_expand_oversized_paste(); |
| 992 | if self.delete_selection() { |
| 993 | return; |
| 994 | } |
| 995 | self.selected_attachment_index = None; |
| 996 | if self.input.is_empty() { |
| 997 | return; |
| 998 | } |
| 999 | // Grapheme-aware: forward-delete removes the whole cluster at the |
| 1000 | // cursor rather than a single scalar from inside it. |
| 1001 | let target = self.cursor_position; |
| 1002 | let end = next_grapheme_boundary(&self.input, target); |
| 1003 | let removed = remove_char_range(&mut self.input, target, end); |
| 1004 | self.resync_command_line_claim(); |
| 1005 | if !removed { |
| 1006 | self.cursor_position = char_count(&self.input); |
| 1007 | } |
| 1008 | self.slash_menu_hidden = false; |
| 1009 | self.mention_menu_hidden = false; |
| 1010 | self.mention_menu_selected = 0; |
| 1011 | self.needs_redraw = true; |
| 1012 | } |
| 1013 | |
| 1014 | /// Delete the word before the cursor. |
| 1015 | pub fn delete_word_backward(&mut self) { |
| 1016 | self.clear_input_history_navigation(); |
| 1017 | if self.delete_selection() { |
| 1018 | return; |
| 1019 | } |
| 1020 | self.selected_attachment_index = None; |
| 1021 | if self.cursor_position == 0 { |
| 1022 | return; |
| 1023 | } |
| 1024 | |
| 1025 | let cursor_byte = byte_index_at_char(&self.input, self.cursor_position); |
| 1026 | let mut word_start = cursor_byte; |
| 1027 | |
| 1028 | while word_start > 0 { |
| 1029 | let Some((prev, ch)) = self.input[..word_start].char_indices().next_back() else { |
| 1030 | break; |
| 1031 | }; |
| 1032 | if !ch.is_whitespace() { |
| 1033 | break; |
| 1034 | } |
| 1035 | word_start = prev; |
| 1036 | } |
| 1037 | |
| 1038 | while word_start > 0 { |
| 1039 | let Some((prev, ch)) = self.input[..word_start].char_indices().next_back() else { |
| 1040 | break; |
| 1041 | }; |
| 1042 | if ch.is_whitespace() { |
| 1043 | break; |
| 1044 | } |
| 1045 | word_start = prev; |
| 1046 | } |
| 1047 | |
| 1048 | if word_start < cursor_byte { |
| 1049 | self.input.replace_range(word_start..cursor_byte, ""); |
| 1050 | self.resync_command_line_claim(); |
| 1051 | self.cursor_position = char_count(&self.input[..word_start]); |
| 1052 | self.slash_menu_hidden = false; |
| 1053 | self.mention_menu_hidden = false; |
| 1054 | self.mention_menu_selected = 0; |
| 1055 | self.needs_redraw = true; |
| 1056 | } |
| 1057 | } |
| 1058 | |
| 1059 | /// Delete from the cursor to the start of the line. |
| 1060 | pub fn delete_to_start_of_line(&mut self) { |
| 1061 | self.clear_input_history_navigation(); |
| 1062 | if self.delete_selection() { |
| 1063 | return; |
| 1064 | } |
| 1065 | self.selected_attachment_index = None; |
| 1066 | if self.cursor_position == 0 { |
| 1067 | return; |
| 1068 | } |
| 1069 | |
| 1070 | let cursor_byte = byte_index_at_char(&self.input, self.cursor_position); |
| 1071 | // Find the start of the current line (last newline or start of string) |
| 1072 | let line_start = self.input[..cursor_byte] |
| 1073 | .rfind('\n') |
| 1074 | .map(|idx| idx + 1) |
| 1075 | .unwrap_or(0); |
| 1076 | |
| 1077 | if line_start < cursor_byte { |
| 1078 | self.input.replace_range(line_start..cursor_byte, ""); |
| 1079 | self.resync_command_line_claim(); |
| 1080 | self.cursor_position = char_count(&self.input[..line_start]); |
| 1081 | self.slash_menu_hidden = false; |
| 1082 | self.mention_menu_hidden = false; |
| 1083 | self.mention_menu_selected = 0; |
| 1084 | self.needs_redraw = true; |
| 1085 | } |
| 1086 | } |
| 1087 | |
| 1088 | /// Delete the word after the cursor. |
| 1089 | pub fn delete_word_forward(&mut self) { |
| 1090 | self.clear_input_history_navigation(); |
| 1091 | if self.delete_selection() { |
| 1092 | return; |
| 1093 | } |
| 1094 | self.selected_attachment_index = None; |
| 1095 | let cursor_byte = byte_index_at_char(&self.input, self.cursor_position); |
| 1096 | if cursor_byte >= self.input.len() { |
| 1097 | return; |
| 1098 | } |
| 1099 | |
| 1100 | let mut word_end = cursor_byte; |
| 1101 | while word_end < self.input.len() { |
| 1102 | let Some(ch) = self.input[word_end..].chars().next() else { |
| 1103 | break; |
| 1104 | }; |
| 1105 | if !ch.is_whitespace() { |
| 1106 | break; |
| 1107 | } |
| 1108 | word_end += ch.len_utf8(); |
| 1109 | } |
| 1110 | |
| 1111 | while word_end < self.input.len() { |
| 1112 | let Some(ch) = self.input[word_end..].chars().next() else { |
| 1113 | break; |
| 1114 | }; |
| 1115 | if ch.is_whitespace() { |
| 1116 | break; |
| 1117 | } |
| 1118 | word_end += ch.len_utf8(); |
| 1119 | } |
| 1120 | |
| 1121 | if cursor_byte < word_end { |
| 1122 | self.input.replace_range(cursor_byte..word_end, ""); |
| 1123 | self.resync_command_line_claim(); |
| 1124 | self.slash_menu_hidden = false; |
| 1125 | self.mention_menu_hidden = false; |
| 1126 | self.mention_menu_selected = 0; |
| 1127 | self.needs_redraw = true; |
| 1128 | } |
| 1129 | } |
| 1130 | |
| 1131 | /// Cut from the cursor to the end of the current logical line into the |
| 1132 | /// kill buffer. If the cursor is already at end-of-line and a trailing |
| 1133 | /// newline exists, that newline is consumed so repeated invocations |
| 1134 | /// continue to make progress (matching emacs/codex semantics). |
| 1135 | /// |
| 1136 | /// Returns `true` when bytes were moved into the kill buffer. |
| 1137 | pub fn kill_to_end_of_line(&mut self) -> bool { |
| 1138 | self.clear_input_history_navigation(); |
| 1139 | if let Some((start, end)) = self.selection_range() { |
| 1140 | let sb = byte_index_at_char(&self.input, start); |
| 1141 | let eb = byte_index_at_char(&self.input, end); |
| 1142 | self.kill_buffer = self.input[sb..eb].to_string(); |
| 1143 | self.delete_selection(); |
| 1144 | return true; |
| 1145 | } |
| 1146 | let total_chars = char_count(&self.input); |
| 1147 | let cursor = self.cursor_position.min(total_chars); |
| 1148 | let start_byte = byte_index_at_char(&self.input, cursor); |
| 1149 | |
| 1150 | // Find the byte offset of the next '\n' (relative to the whole string) |
| 1151 | // or the end of the buffer if no newline exists at/after the cursor. |
| 1152 | let eol_byte = self.input[start_byte..] |
| 1153 | .find('\n') |
| 1154 | .map(|rel| start_byte + rel) |
| 1155 | .unwrap_or_else(|| self.input.len()); |
| 1156 | |
| 1157 | let end_byte = if start_byte == eol_byte { |
| 1158 | // Cursor is at EOL — consume the newline itself if one is there. |
| 1159 | if eol_byte < self.input.len() { |
| 1160 | eol_byte + 1 |
| 1161 | } else { |
| 1162 | return false; |
| 1163 | } |
| 1164 | } else { |
| 1165 | eol_byte |
| 1166 | }; |
| 1167 | |
| 1168 | let removed: String = self.input[start_byte..end_byte].to_string(); |
| 1169 | if removed.is_empty() { |
| 1170 | return false; |
| 1171 | } |
| 1172 | |
| 1173 | self.kill_buffer = removed; |
| 1174 | self.input.replace_range(start_byte..end_byte, ""); |
| 1175 | self.resync_command_line_claim(); |
| 1176 | // Cursor stays at the same character index (start of removed range). |
| 1177 | self.cursor_position = cursor; |
| 1178 | self.slash_menu_hidden = false; |
| 1179 | self.mention_menu_hidden = false; |
| 1180 | self.mention_menu_selected = 0; |
| 1181 | self.needs_redraw = true; |
| 1182 | true |
| 1183 | } |
| 1184 | |
| 1185 | /// Insert the contents of the kill buffer at the cursor, advancing it. |
| 1186 | /// The kill buffer is left intact so multiple yanks duplicate the text. |
| 1187 | /// Returns `true` if any text was inserted. |
| 1188 | pub fn yank(&mut self) -> bool { |
| 1189 | if self.kill_buffer.is_empty() { |
| 1190 | return false; |
| 1191 | } |
| 1192 | self.delete_selection(); |
| 1193 | self.clear_input_history_navigation(); |
| 1194 | let text = self.kill_buffer.clone(); |
| 1195 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 1196 | let byte_index = byte_index_at_char(&self.input, cursor); |
| 1197 | self.input.insert_str(byte_index, &text); |
| 1198 | self.resync_command_line_claim(); |
| 1199 | self.cursor_position = cursor + char_count(&text); |
| 1200 | self.slash_menu_hidden = false; |
| 1201 | self.mention_menu_hidden = false; |
| 1202 | self.mention_menu_selected = 0; |
| 1203 | self.needs_redraw = true; |
| 1204 | true |
| 1205 | } |
| 1206 | |
| 1207 | pub fn move_cursor_left(&mut self) { |
| 1208 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 1209 | self.cursor_position = prev_grapheme_boundary(&self.input, cursor); |
| 1210 | self.needs_redraw = true; |
| 1211 | } |
| 1212 | |
| 1213 | pub fn move_cursor_right(&mut self) { |
| 1214 | let total = char_count(&self.input); |
| 1215 | if self.cursor_position < total { |
| 1216 | self.cursor_position = next_grapheme_boundary(&self.input, self.cursor_position); |
| 1217 | self.needs_redraw = true; |
| 1218 | } |
| 1219 | } |
| 1220 | |
| 1221 | pub fn move_cursor_start(&mut self) { |
| 1222 | self.cursor_position = 0; |
| 1223 | self.needs_redraw = true; |
| 1224 | } |
| 1225 | |
| 1226 | pub fn move_cursor_end(&mut self) { |
| 1227 | self.cursor_position = char_count(&self.input); |
| 1228 | self.needs_redraw = true; |
| 1229 | } |
| 1230 | |
| 1231 | /// In a multiline composer, jump to the start of the current line. |
| 1232 | /// On single-line input this is equivalent to `move_cursor_start`. |
| 1233 | pub fn move_cursor_line_start(&mut self) { |
| 1234 | let byte_pos = byte_index_at_char(&self.input, self.cursor_position); |
| 1235 | let before = &self.input[..byte_pos]; |
| 1236 | if let Some(last_nl_byte) = before.rfind('\n') { |
| 1237 | // Position after the '\n' (start of the current line). |
| 1238 | self.cursor_position = char_count(&self.input[..=last_nl_byte]); |
| 1239 | } else { |
| 1240 | self.cursor_position = 0; |
| 1241 | } |
| 1242 | self.needs_redraw = true; |
| 1243 | } |
| 1244 | |
| 1245 | /// In a multiline composer, jump to the end of the current line |
| 1246 | /// (just before the next `\n` or at the end of input). |
| 1247 | /// On single-line input this is equivalent to `move_cursor_end`. |
| 1248 | pub fn move_cursor_line_end(&mut self) { |
| 1249 | let search_start = byte_index_at_char(&self.input, self.cursor_position); |
| 1250 | if let Some(offset) = self.input[search_start..].find('\n') { |
| 1251 | self.cursor_position = char_count(&self.input[..search_start + offset]); |
| 1252 | } else { |
| 1253 | self.cursor_position = char_count(&self.input); |
| 1254 | } |
| 1255 | self.needs_redraw = true; |
| 1256 | } |
| 1257 | |
| 1258 | /// Move forward one word. Skips over the current word then any trailing |
| 1259 | /// whitespace to land on the first character of the next word. |
| 1260 | pub fn move_cursor_word_forward(&mut self) { |
| 1261 | let text = self.input.clone(); |
| 1262 | let total = char_count(&text); |
| 1263 | let mut pos = self.cursor_position; |
| 1264 | if pos >= total { |
| 1265 | return; |
| 1266 | } |
| 1267 | // Skip non-whitespace (current word). |
| 1268 | while pos < total { |
| 1269 | let byte = byte_index_at_char(&text, pos); |
| 1270 | let ch = text[byte..].chars().next().unwrap_or(' '); |
| 1271 | if ch.is_whitespace() { |
| 1272 | break; |
| 1273 | } |
| 1274 | pos += 1; |
| 1275 | } |
| 1276 | // Skip whitespace. |
| 1277 | while pos < total { |
| 1278 | let byte = byte_index_at_char(&text, pos); |
| 1279 | let ch = text[byte..].chars().next().unwrap_or(' '); |
| 1280 | if !ch.is_whitespace() { |
| 1281 | break; |
| 1282 | } |
| 1283 | pos += 1; |
| 1284 | } |
| 1285 | self.cursor_position = pos; |
| 1286 | self.needs_redraw = true; |
| 1287 | } |
| 1288 | |
| 1289 | /// Move backward one word. Skips leading whitespace then the preceding |
| 1290 | /// word to land on its first character. |
| 1291 | pub fn move_cursor_word_backward(&mut self) { |
| 1292 | let text = self.input.clone(); |
| 1293 | let mut pos = self.cursor_position; |
| 1294 | if pos == 0 { |
| 1295 | return; |
| 1296 | } |
| 1297 | // Step back one so we're not already at the word start. |
| 1298 | pos -= 1; |
| 1299 | // Skip whitespace. |
| 1300 | while pos > 0 { |
| 1301 | let byte = byte_index_at_char(&text, pos); |
| 1302 | let ch = text[byte..].chars().next().unwrap_or(' '); |
| 1303 | if !ch.is_whitespace() { |
| 1304 | break; |
| 1305 | } |
| 1306 | pos -= 1; |
| 1307 | } |
| 1308 | // Skip non-whitespace. |
| 1309 | while pos > 0 { |
| 1310 | let byte = byte_index_at_char(&text, pos - 1); |
| 1311 | let ch = text[byte..].chars().next().unwrap_or(' '); |
| 1312 | if ch.is_whitespace() { |
| 1313 | break; |
| 1314 | } |
| 1315 | pos -= 1; |
| 1316 | } |
| 1317 | self.cursor_position = pos; |
| 1318 | self.needs_redraw = true; |
| 1319 | } |
| 1320 | |
| 1321 | /// Select the entire composer contents: anchor at the start, cursor at |
| 1322 | /// the end. Expands an oversized-paste preview first so the selection |
| 1323 | /// covers the real draft, not a truncated placeholder (#3263). |
| 1324 | pub fn select_all(&mut self) { |
| 1325 | self.auto_expand_oversized_paste(); |
| 1326 | if self.input.is_empty() { |
| 1327 | self.selection_anchor = None; |
| 1328 | return; |
| 1329 | } |
| 1330 | self.selection_anchor = Some(0); |
| 1331 | self.cursor_position = char_count(&self.input); |
| 1332 | self.needs_redraw = true; |
| 1333 | } |
| 1334 | |
| 1335 | /// Delete the selected text, place cursor at the start of the deleted range. |
| 1336 | /// Returns true if a selection was deleted. |
| 1337 | /// |
| 1338 | /// When the selection spans the whole draft (e.g. select-all then type or |
| 1339 | /// Backspace), the outgoing text is stashed exactly like `Ctrl+U` so the |
| 1340 | /// destruction is recoverable with `Ctrl+Z` / the draft history. |
| 1341 | pub fn delete_selection(&mut self) -> bool { |
| 1342 | let Some((start, end)) = self.selection_range() else { |
| 1343 | return false; |
| 1344 | }; |
| 1345 | if start == 0 && end == char_count(&self.input) { |
| 1346 | let draft = self.input.clone(); |
| 1347 | if !draft.trim().is_empty() { |
| 1348 | self.clear_undo_buffer = Some(draft.clone()); |
| 1349 | self.remember_draft_for_recovery(draft); |
| 1350 | } |
| 1351 | } |
| 1352 | let sb = byte_index_at_char(&self.input, start); |
| 1353 | let eb = byte_index_at_char(&self.input, end); |
| 1354 | self.input.replace_range(sb..eb, ""); |
| 1355 | self.resync_command_line_claim(); |
| 1356 | self.cursor_position = start; |
| 1357 | self.selection_anchor = None; |
| 1358 | self.clear_input_history_navigation(); |
| 1359 | self.slash_menu_hidden = false; |
| 1360 | self.mention_menu_hidden = false; |
| 1361 | self.mention_menu_selected = 0; |
| 1362 | self.needs_redraw = true; |
| 1363 | true |
| 1364 | } |
| 1365 | |
| 1366 | // === Vim composer mode helpers === |
| 1367 | /// Move the cursor to the start of the current logical line (vim `0`). |
| 1368 | pub fn vim_move_line_start(&mut self) { |
| 1369 | let text = self.input.clone(); |
| 1370 | let cursor_byte = byte_index_at_char(&text, self.cursor_position); |
| 1371 | // Walk backward until we find a newline or the start of the string. |
| 1372 | let line_start_byte = text[..cursor_byte].rfind('\n').map_or(0, |idx| idx + 1); |
| 1373 | self.cursor_position = char_count(&text[..line_start_byte]); |
| 1374 | self.needs_redraw = true; |
| 1375 | } |
| 1376 | |
| 1377 | /// Move the cursor to the end of the current logical line (vim `$`). |
| 1378 | pub fn vim_move_line_end(&mut self) { |
| 1379 | let text = self.input.clone(); |
| 1380 | let cursor_byte = byte_index_at_char(&text, self.cursor_position); |
| 1381 | // Walk forward to the next newline or end-of-string. |
| 1382 | let line_end_char = text[cursor_byte..].find('\n').map_or_else( |
| 1383 | || char_count(&text), |
| 1384 | |rel| char_count(&text[..cursor_byte + rel]), |
| 1385 | ); |
| 1386 | self.cursor_position = line_end_char; |
| 1387 | self.needs_redraw = true; |
| 1388 | } |
| 1389 | |
| 1390 | /// Move forward one word (vim `w`). Skips over the current word then any |
| 1391 | /// trailing whitespace to land on the first character of the next word. |
| 1392 | pub fn vim_move_word_forward(&mut self) { |
| 1393 | self.move_cursor_word_forward(); |
| 1394 | } |
| 1395 | |
| 1396 | /// Move backward one word (vim `b`). Skips leading whitespace then the |
| 1397 | /// preceding word to land on its first character. |
| 1398 | pub fn vim_move_word_backward(&mut self) { |
| 1399 | self.move_cursor_word_backward(); |
| 1400 | } |
| 1401 | |
| 1402 | /// Delete the character under the cursor (vim `x`). |
| 1403 | pub fn vim_delete_char_under_cursor(&mut self) { |
| 1404 | self.auto_expand_oversized_paste(); |
| 1405 | let total = char_count(&self.input); |
| 1406 | if self.cursor_position >= total { |
| 1407 | return; |
| 1408 | } |
| 1409 | let pos = self.cursor_position; |
| 1410 | // Grapheme-aware: `x` deletes the whole cluster under the cursor. |
| 1411 | let end = next_grapheme_boundary(&self.input, pos); |
| 1412 | remove_char_range(&mut self.input, pos, end); |
| 1413 | self.resync_command_line_claim(); |
| 1414 | // Keep cursor in bounds after deletion, on the last cluster's start. |
| 1415 | let new_total = char_count(&self.input); |
| 1416 | if self.cursor_position > 0 && self.cursor_position >= new_total { |
| 1417 | self.cursor_position = prev_grapheme_boundary(&self.input, new_total); |
| 1418 | } |
| 1419 | self.needs_redraw = true; |
| 1420 | } |
| 1421 | |
| 1422 | /// Delete the entire current logical line (vim `dd`). |
| 1423 | pub fn vim_delete_line(&mut self) { |
| 1424 | let text = self.input.clone(); |
| 1425 | let cursor_byte = byte_index_at_char(&text, self.cursor_position); |
| 1426 | let line_start_byte = text[..cursor_byte].rfind('\n').map_or(0, |idx| idx + 1); |
| 1427 | let line_end_byte = text[cursor_byte..] |
| 1428 | .find('\n') |
| 1429 | .map_or(text.len(), |rel| cursor_byte + rel); |
| 1430 | |
| 1431 | // Include the trailing newline if present, or the leading newline for the |
| 1432 | // very last non-terminated line to avoid leaving a dangling newline. |
| 1433 | let (remove_start, remove_end) = if line_end_byte < text.len() { |
| 1434 | // There is a newline after the line — remove it too. |
| 1435 | (line_start_byte, line_end_byte + 1) |
| 1436 | } else if line_start_byte > 0 { |
| 1437 | // Last line without trailing newline — remove the preceding newline. |
| 1438 | (line_start_byte - 1, line_end_byte) |
| 1439 | } else { |
| 1440 | // Only line in the buffer. |
| 1441 | (line_start_byte, line_end_byte) |
| 1442 | }; |
| 1443 | |
| 1444 | self.input.replace_range(remove_start..remove_end, ""); |
| 1445 | self.resync_command_line_claim(); |
| 1446 | self.cursor_position = char_count(&self.input[..remove_start]); |
| 1447 | self.needs_redraw = true; |
| 1448 | } |
| 1449 | |
| 1450 | /// Enter insert mode at the cursor (vim `i`). |
| 1451 | pub fn vim_enter_insert(&mut self) { |
| 1452 | self.vim_mode = VimMode::Insert; |
| 1453 | self.needs_redraw = true; |
| 1454 | } |
| 1455 | |
| 1456 | /// Enter insert mode after the cursor (vim `a`). |
| 1457 | pub fn vim_enter_append(&mut self) { |
| 1458 | let total = char_count(&self.input); |
| 1459 | if self.cursor_position < total { |
| 1460 | // After the whole cluster under the cursor, not one scalar in. |
| 1461 | self.cursor_position = next_grapheme_boundary(&self.input, self.cursor_position); |
| 1462 | } |
| 1463 | self.vim_mode = VimMode::Insert; |
| 1464 | self.needs_redraw = true; |
| 1465 | } |
| 1466 | |
| 1467 | /// Open a new line below and enter insert mode (vim `o`). |
| 1468 | pub fn vim_open_line_below(&mut self) { |
| 1469 | // Move to end of line, then insert a newline. |
| 1470 | self.vim_move_line_end(); |
| 1471 | self.insert_char('\n'); |
| 1472 | self.vim_mode = VimMode::Insert; |
| 1473 | } |
| 1474 | |
| 1475 | /// Return to Normal mode from Insert or Visual (vim `Esc`). |
| 1476 | pub fn vim_enter_normal(&mut self) { |
| 1477 | self.vim_mode = VimMode::Normal; |
| 1478 | self.vim_pending_d = false; |
| 1479 | // In Normal mode the cursor sits on a character, not after the last |
| 1480 | // one: on the last grapheme cluster's start (U01-m4). |
| 1481 | let total = char_count(&self.input); |
| 1482 | if self.cursor_position > 0 && self.cursor_position >= total { |
| 1483 | self.cursor_position = prev_grapheme_boundary(&self.input, total); |
| 1484 | } |
| 1485 | self.needs_redraw = true; |
| 1486 | } |
| 1487 | |
| 1488 | /// Move the cursor down one logical line within the buffer (vim `j`). |
| 1489 | /// Falls back to history-down when already on the last line. |
| 1490 | pub fn vim_move_down(&mut self) { |
| 1491 | let text = self.input.clone(); |
| 1492 | let total = char_count(&text); |
| 1493 | if self.cursor_position >= total { |
| 1494 | self.history_down(); |
| 1495 | return; |
| 1496 | } |
| 1497 | let cursor_byte = byte_index_at_char(&text, self.cursor_position); |
| 1498 | let rest = &text[cursor_byte..]; |
| 1499 | if let Some(rel_nl) = rest.find('\n') { |
| 1500 | // Column offset on the current line. |
| 1501 | let line_start_byte = text[..cursor_byte].rfind('\n').map_or(0, |i| i + 1); |
| 1502 | let col = char_count(&text[line_start_byte..cursor_byte]); |
| 1503 | let next_line_start = cursor_byte + rel_nl + 1; |
| 1504 | let next_line = &text[next_line_start..]; |
| 1505 | let next_line_len = next_line.find('\n').unwrap_or(next_line.len()); |
| 1506 | let next_line_char_len = |
| 1507 | char_count(&text[next_line_start..next_line_start + next_line_len]); |
| 1508 | let target_col = col.min(next_line_char_len); |
| 1509 | self.cursor_position = |
| 1510 | floor_grapheme_boundary(&text, char_count(&text[..next_line_start]) + target_col); |
| 1511 | self.needs_redraw = true; |
| 1512 | } else { |
| 1513 | self.history_down(); |
| 1514 | } |
| 1515 | } |
| 1516 | |
| 1517 | /// Move the cursor up one logical line within the buffer (vim `k`). |
| 1518 | /// Falls back to history-up when already on the first line. |
| 1519 | pub fn vim_move_up(&mut self) { |
| 1520 | let text = self.input.clone(); |
| 1521 | let cursor_byte = byte_index_at_char(&text, self.cursor_position); |
| 1522 | if let Some(prev_nl) = text[..cursor_byte].rfind('\n') { |
| 1523 | // Column on the current line. |
| 1524 | let line_start_byte = prev_nl + 1; |
| 1525 | let col = char_count(&text[line_start_byte..cursor_byte]); |
| 1526 | // Find start of the previous line. |
| 1527 | let prev_line_end = prev_nl; // byte of the newline itself |
| 1528 | let prev_start = text[..prev_line_end].rfind('\n').map_or(0, |i| i + 1); |
| 1529 | let prev_line_len = char_count(&text[prev_start..prev_line_end]); |
| 1530 | let target_col = col.min(prev_line_len); |
| 1531 | self.cursor_position = |
| 1532 | floor_grapheme_boundary(&text, char_count(&text[..prev_start]) + target_col); |
| 1533 | self.needs_redraw = true; |
| 1534 | } else { |
| 1535 | self.history_up(); |
| 1536 | } |
| 1537 | } |
| 1538 | |
| 1539 | pub fn clear_input(&mut self) { |
| 1540 | self.clear_input_history_navigation(); |
| 1541 | self.input.clear(); |
| 1542 | self.resync_command_line_claim(); |
| 1543 | self.cursor_position = 0; |
| 1544 | // Prevent stale oversized-paste state from leaking when the user |
| 1545 | // clears the composer or navigates to a different input (#3263). |
| 1546 | self.pending_paste_reference = None; |
| 1547 | self.oversized_paste_full_text = None; |
| 1548 | self.selection_anchor = None; |
| 1549 | self.selected_attachment_index = None; |
| 1550 | self.slash_menu_selected = 0; |
| 1551 | self.slash_menu_hidden = false; |
| 1552 | self.paste_burst.clear_after_explicit_paste(); |
| 1553 | self.needs_redraw = true; |
| 1554 | } |
| 1555 | |
| 1556 | pub fn clear_input_recoverable(&mut self) { |
| 1557 | self.stash_current_input_for_recovery(); |
| 1558 | self.clear_input(); |
| 1559 | } |
| 1560 | |
| 1561 | pub fn start_history_search(&mut self) { |
| 1562 | if self.composer_history_search.is_some() { |
| 1563 | return; |
| 1564 | } |
| 1565 | // Expand any truncated paste first so the history search seed |
| 1566 | // contains the full text, not the truncated preview (#3263). |
| 1567 | self.auto_expand_oversized_paste(); |
| 1568 | self.composer_history_search = Some(ComposerHistorySearch::new( |
| 1569 | self.input.clone(), |
| 1570 | self.cursor_position, |
| 1571 | )); |
| 1572 | self.slash_menu_hidden = true; |
| 1573 | self.mention_menu_hidden = true; |
| 1574 | self.paste_burst.clear_after_explicit_paste(); |
| 1575 | self.status_message = Some("History search: type to filter, Enter accepts".to_string()); |
| 1576 | self.needs_redraw = true; |
| 1577 | } |
| 1578 | |
| 1579 | pub fn history_search_insert_char(&mut self, ch: char) { |
| 1580 | if let Some(search) = self.composer_history_search.as_mut() { |
| 1581 | search.query.push(ch); |
| 1582 | search.selected = 0; |
| 1583 | self.status_message = Some("History search: Enter accepts, Esc restores".to_string()); |
| 1584 | self.needs_redraw = true; |
| 1585 | } |
| 1586 | } |
| 1587 | |
| 1588 | pub fn history_search_insert_str(&mut self, text: &str) { |
| 1589 | if text.is_empty() { |
| 1590 | return; |
| 1591 | } |
| 1592 | if let Some(search) = self.composer_history_search.as_mut() { |
| 1593 | search.query.push_str(&normalize_paste_text(text)); |
| 1594 | search.selected = 0; |
| 1595 | self.status_message = Some("History search: Enter accepts, Esc restores".to_string()); |
| 1596 | self.needs_redraw = true; |
| 1597 | } |
| 1598 | } |
| 1599 | |
| 1600 | pub fn history_search_backspace(&mut self) { |
| 1601 | if let Some(search) = self.composer_history_search.as_mut() { |
| 1602 | search.query.pop(); |
| 1603 | search.selected = 0; |
| 1604 | self.needs_redraw = true; |
| 1605 | } |
| 1606 | self.clamp_history_search_selection(); |
| 1607 | } |
| 1608 | |
| 1609 | pub fn history_search_select_previous(&mut self) { |
| 1610 | if let Some(search) = self.composer_history_search.as_mut() { |
| 1611 | search.selected = search.selected.saturating_sub(1); |
| 1612 | self.needs_redraw = true; |
| 1613 | } |
| 1614 | } |
| 1615 | |
| 1616 | pub fn history_search_select_next(&mut self) { |
| 1617 | let Some(search) = self.composer_history_search.as_ref() else { |
| 1618 | return; |
| 1619 | }; |
| 1620 | let query = search.query.clone(); |
| 1621 | let selected = search.selected; |
| 1622 | let match_count = self.history_search_matches_for_query(&query).len(); |
| 1623 | if let Some(search) = self.composer_history_search.as_mut() |
| 1624 | && match_count > 0 |
| 1625 | { |
| 1626 | search.selected = (selected + 1).min(match_count.saturating_sub(1)); |
| 1627 | self.needs_redraw = true; |
| 1628 | } |
| 1629 | } |
| 1630 | |
| 1631 | pub fn accept_history_search(&mut self) -> bool { |
| 1632 | let Some(search) = self.composer_history_search.take() else { |
| 1633 | return false; |
| 1634 | }; |
| 1635 | let matches = self.history_search_matches_for_query(&search.query); |
| 1636 | if let Some(selected) = matches |
| 1637 | .get(search.selected.min(matches.len().saturating_sub(1))) |
| 1638 | .cloned() |
| 1639 | { |
| 1640 | self.input = selected; |
| 1641 | self.resync_command_line_claim(); |
| 1642 | self.cursor_position = char_count(&self.input); |
| 1643 | self.history_index = None; |
| 1644 | self.status_message = Some("History match inserted into composer".to_string()); |
| 1645 | self.needs_redraw = true; |
| 1646 | true |
| 1647 | } else { |
| 1648 | self.composer_history_search = Some(search); |
| 1649 | self.status_message = Some("No history matches".to_string()); |
| 1650 | self.needs_redraw = true; |
| 1651 | false |
| 1652 | } |
| 1653 | } |
| 1654 | |
| 1655 | pub fn cancel_history_search(&mut self) { |
| 1656 | let Some(search) = self.composer_history_search.take() else { |
| 1657 | return; |
| 1658 | }; |
| 1659 | self.input = search.pre_search_input; |
| 1660 | self.resync_command_line_claim(); |
| 1661 | self.cursor_position = search.pre_search_cursor.min(char_count(&self.input)); |
| 1662 | self.status_message = Some("History search canceled".to_string()); |
| 1663 | self.needs_redraw = true; |
| 1664 | } |
| 1665 | |
| 1666 | /// Refuse a submit the shell cannot vouch for, leaving the text exactly |
| 1667 | /// where the user can see it (#5925). |
| 1668 | /// |
| 1669 | /// Never destructive: the composer keeps its content and the next Enter |
| 1670 | /// sends it. The hold exists so a line whose first bytes may be missing |
| 1671 | /// is read by a human before it is read by a model. |
| 1672 | fn hold_unproven_submit(&mut self, reason: &str) { |
| 1673 | self.status_message = Some(reason.to_string()); |
| 1674 | self.push_status_toast(reason, StatusToastLevel::Warning, Some(8_000)); |
| 1675 | self.needs_redraw = true; |
| 1676 | } |
| 1677 | |
| 1678 | pub fn submit_input(&mut self) -> Option<String> { |
| 1679 | if self.input.trim().is_empty() { |
| 1680 | self.paste_burst.clear_after_explicit_paste(); |
| 1681 | return None; |
| 1682 | } |
| 1683 | // #5925: startup consumed bytes it could not replay, so this shell |
| 1684 | // cannot prove it saw the whole line. Keep the text in the composer |
| 1685 | // and let the user look at it rather than sending a line that may be |
| 1686 | // missing its first characters — a truncated `/command` submitted as |
| 1687 | // prose runs with the session's full authority. Cleared here, so the |
| 1688 | // deliberate second Enter sends exactly what is on screen. |
| 1689 | if self.startup_input_unproven { |
| 1690 | self.startup_input_unproven = false; |
| 1691 | self.hold_unproven_submit( |
| 1692 | "Check the line, then press Enter again to send it. \ |
| 1693 | Startup may have missed some characters.", |
| 1694 | ); |
| 1695 | return None; |
| 1696 | } |
| 1697 | // A line that began with `/` stays a command until Enter. If the |
| 1698 | // outgoing text is no longer a command — a submit-time rewrite, or |
| 1699 | // bytes lost after the composer accepted them — never fall through |
| 1700 | // to the prose-prompt branch; hold it instead. |
| 1701 | let claimed_command = self.command_line_claimed(); |
| 1702 | // Safety net: if any earlier path filled the buffer above the |
| 1703 | // safety cap without going through `insert_paste_text`, fold it |
| 1704 | // into a workspace paste file now (#553). Bracketed pastes hit |
| 1705 | // the consolidation in `insert_paste_text` first, so the user |
| 1706 | // sees the @mention in the composer before submission. |
| 1707 | if !self.consolidate_large_input_if_oversized() { |
| 1708 | // The paste file could not be written. Never send a silently |
| 1709 | // truncated prompt: the full text stays in the composer and the |
| 1710 | // error explains why Enter did nothing. |
| 1711 | return None; |
| 1712 | } |
| 1713 | // If consolidation created a paste file, submit only the @-mention so |
| 1714 | // the model reads the full content from the paste file. Sending both |
| 1715 | // the inline text and the file mention duplicates the content in the |
| 1716 | // request and confuses the model. |
| 1717 | let mut input = self.input.clone(); |
| 1718 | if let Some(reference) = self.pending_paste_reference.take() { |
| 1719 | // Drop the oversized inline copy; the paste file is now the |
| 1720 | // single source of truth for this content. The submitted text |
| 1721 | // keeps the @-mention (mention resolution attaches the file for |
| 1722 | // the model) but wraps it in a human-readable attachment card |
| 1723 | // with size and a bounded preview, so the transcript row can |
| 1724 | // never render as a mysterious bare filesystem path (#553 |
| 1725 | // follow-up: "a path is not a message"). |
| 1726 | let full = self.oversized_paste_full_text.take(); |
| 1727 | input = match full { |
| 1728 | Some(full) => paste_attachment_display(&reference, &full), |
| 1729 | None => reference, |
| 1730 | }; |
| 1731 | } else if let Some(full) = self.oversized_paste_full_text.take() { |
| 1732 | input = full; |
| 1733 | } |
| 1734 | if claimed_command && !looks_like_slash_command_input(&input) { |
| 1735 | // The line was a command when the composer accepted it and is |
| 1736 | // not one now. Something rewrote it between Enter and dispatch; |
| 1737 | // the one thing that must never happen is sending it to the |
| 1738 | // model as prose (#5925). Put the text back and say so. |
| 1739 | tracing::warn!( |
| 1740 | target: "startup_input", |
| 1741 | submitted = %input, |
| 1742 | "a command line stopped looking like a command before dispatch; holding it in the composer" |
| 1743 | ); |
| 1744 | self.input = input; |
| 1745 | self.cursor_position = char_count(&self.input); |
| 1746 | self.line_began_with_slash = false; |
| 1747 | self.hold_unproven_submit( |
| 1748 | "That line started as a command but no longer reads as one. \ |
| 1749 | Check it and press Enter again to send it as shown.", |
| 1750 | ); |
| 1751 | return None; |
| 1752 | } |
| 1753 | crate::composer_history::push_history_entry(&mut self.input_history, &input); |
| 1754 | if self.max_input_history == 0 { |
| 1755 | self.input_history.clear(); |
| 1756 | } else if self.input_history.len() > self.max_input_history { |
| 1757 | let excess = self.input_history.len() - self.max_input_history; |
| 1758 | self.input_history.drain(0..excess); |
| 1759 | } |
| 1760 | // Mirror prompts and commands to the persisted cross-session history |
| 1761 | // so arrow-up recall works across restarts (#366, #6006). A history |
| 1762 | // limit of zero saves nothing (U01-m2). |
| 1763 | if self.max_input_history > 0 { |
| 1764 | crate::composer_history::append_history(&input); |
| 1765 | } |
| 1766 | self.history_index = None; |
| 1767 | self.history_navigation_draft = None; |
| 1768 | self.clear_input(); |
| 1769 | // Collapse recent-only Work chrome on the next accepted turn (#4688). |
| 1770 | self.work_surface.note_user_turn_or_new_operation(); |
| 1771 | Some(input) |
| 1772 | } |
| 1773 | |
| 1774 | /// Put a message that was never sent back in the composer as it was |
| 1775 | /// first sent, skill and all, so Enter sends the same request again. |
| 1776 | pub fn restore_unsent_message(&mut self, message: QueuedMessage) { |
| 1777 | self.input = message.display; |
| 1778 | self.resync_command_line_claim(); |
| 1779 | self.cursor_position = char_count(&self.input); |
| 1780 | self.history_index = None; |
| 1781 | self.history_navigation_draft = None; |
| 1782 | self.selected_attachment_index = None; |
| 1783 | self.active_skill = message.skill_instruction; |
| 1784 | self.active_skill_provenance = message.skill_provenance; |
| 1785 | self.needs_redraw = true; |
| 1786 | } |
| 1787 | |
| 1788 | pub fn restore_last_submitted_prompt_if_empty(&mut self) -> bool { |
| 1789 | if !self.input.is_empty() { |
| 1790 | return false; |
| 1791 | } |
| 1792 | let Some(prompt) = self |
| 1793 | .last_submitted_prompt |
| 1794 | .as_deref() |
| 1795 | .filter(|prompt| !prompt.is_empty()) |
| 1796 | else { |
| 1797 | return false; |
| 1798 | }; |
| 1799 | |
| 1800 | self.input = prompt.to_string(); |
| 1801 | self.resync_command_line_claim(); |
| 1802 | self.cursor_position = char_count(&self.input); |
| 1803 | self.history_index = None; |
| 1804 | self.history_navigation_draft = None; |
| 1805 | self.selected_attachment_index = None; |
| 1806 | self.needs_redraw = true; |
| 1807 | true |
| 1808 | } |
| 1809 | |
| 1810 | /// Replace the composer buffer with externally edited text. Recalled |
| 1811 | /// history, selection, and attachment positions belong to the old text: |
| 1812 | /// a stale `history_index` would let the next Up/Down silently discard |
| 1813 | /// the edited buffer. |
| 1814 | pub fn apply_external_edit(&mut self, new: String) { |
| 1815 | self.input = new; |
| 1816 | self.resync_command_line_claim(); |
| 1817 | self.cursor_position = char_count(&self.input); |
| 1818 | self.history_index = None; |
| 1819 | self.history_navigation_draft = None; |
| 1820 | self.selection_anchor = None; |
| 1821 | self.selected_attachment_index = None; |
| 1822 | self.needs_redraw = true; |
| 1823 | } |
| 1824 | |
| 1825 | /// Restore the last cleared input if the composer is empty. |
| 1826 | /// Returns `true` if the input was restored. |
| 1827 | pub fn restore_last_cleared_input_if_empty(&mut self) -> bool { |
| 1828 | if !self.input.is_empty() { |
| 1829 | return false; |
| 1830 | } |
| 1831 | let Some(saved) = self.clear_undo_buffer.take().filter(|s| !s.is_empty()) else { |
| 1832 | return false; |
| 1833 | }; |
| 1834 | |
| 1835 | self.input = saved; |
| 1836 | self.resync_command_line_claim(); |
| 1837 | self.cursor_position = char_count(&self.input); |
| 1838 | self.history_index = None; |
| 1839 | self.history_navigation_draft = None; |
| 1840 | self.selected_attachment_index = None; |
| 1841 | self.slash_menu_selected = 0; |
| 1842 | self.slash_menu_hidden = false; |
| 1843 | self.needs_redraw = true; |
| 1844 | self.clear_undo_buffer = None; |
| 1845 | true |
| 1846 | } |
| 1847 | |
| 1848 | /// Composer-Enter dispatch. Returns `Some(input)` when the press should |
| 1849 | /// fire a submit; `None` when Enter was absorbed (paste-burst Enter |
| 1850 | /// suppression — see #1073). |
| 1851 | /// |
| 1852 | /// Two suppression cases are handled here. Both are silent: nothing |
| 1853 | /// visible happens beyond the text gaining a newline. |
| 1854 | /// |
| 1855 | /// 1. **Burst active.** A paste burst is currently being assembled in |
| 1856 | /// `paste_burst.buffer`. The Enter is part of the paste content; |
| 1857 | /// append `\n` to the buffer so the next flush includes it, do not |
| 1858 | /// submit, and extend the suppression window so a follow-on Enter |
| 1859 | /// (i.e. the *next* line of a multi-line paste) is also absorbed. |
| 1860 | /// 2. **Window open after flush.** A burst just flushed into |
| 1861 | /// `self.input`, but the suppression window is still alive. The |
| 1862 | /// Enter is probably the trailing newline of that paste, not a submit |
| 1863 | /// gesture by the user, so insert `\n` directly into the composer |
| 1864 | /// text. The window is deliberately *not* re-armed here: no burst is |
| 1865 | /// being assembled, so this Enter is only a guess, and re-arming on a |
| 1866 | /// guess meant every absorbed Enter bought another 120ms — a user |
| 1867 | /// pressing Enter to send just kept adding newlines and never |
| 1868 | /// submitted. Suppression now always ends 120ms after the last real |
| 1869 | /// keystroke. |
| 1870 | /// |
| 1871 | /// Outside both cases the call falls through to [`Self::submit_input`] |
| 1872 | /// unchanged so normal Enter-to-send behaviour is preserved. |
| 1873 | pub fn handle_composer_enter(&mut self) -> Option<String> { |
| 1874 | if self.use_paste_burst_detection { |
| 1875 | let now = Instant::now(); |
| 1876 | if self |
| 1877 | .paste_burst |
| 1878 | .newline_should_insert_instead_of_submit(now) |
| 1879 | { |
| 1880 | if !self.paste_burst.append_newline_if_active(now) { |
| 1881 | self.insert_char('\n'); |
| 1882 | } |
| 1883 | self.needs_redraw = true; |
| 1884 | return None; |
| 1885 | } |
| 1886 | } |
| 1887 | self.submit_input() |
| 1888 | } |
| 1889 | |
| 1890 | /// Non-destructive twin of [`Self::handle_composer_enter`] for callers |
| 1891 | /// that must commit other state before the composer may be consumed: |
| 1892 | /// the startup composer begins the launch session before it consumes |
| 1893 | /// its draft, so it probes first and never begins a session for an |
| 1894 | /// Enter the paste-burst window is about to absorb. Reads the exact |
| 1895 | /// same two predicates `handle_composer_enter` acts on — the burst |
| 1896 | /// window and the trimmed-empty buffer — without mutating anything. |
| 1897 | #[must_use] |
| 1898 | pub fn composer_enter_would_submit(&self) -> bool { |
| 1899 | if self.use_paste_burst_detection |
| 1900 | && self |
| 1901 | .paste_burst |
| 1902 | .newline_should_insert_instead_of_submit(Instant::now()) |
| 1903 | { |
| 1904 | return false; |
| 1905 | } |
| 1906 | !self.input.trim().is_empty() |
| 1907 | } |
| 1908 | |
| 1909 | /// Whether the *draft* is in a submittable state, for display only. |
| 1910 | /// |
| 1911 | /// Deliberately time-independent. [`Self::composer_enter_would_submit`] |
| 1912 | /// additionally consults the paste-burst heuristic, whose suppression |
| 1913 | /// window is re-extended on every fast keystroke -- correct for deciding |
| 1914 | /// what a newline does mid-paste, wrong for a persistent affordance. |
| 1915 | /// Driving the `[↵]` chip from it made the chip strobe `[↵]`/`[·]` for as |
| 1916 | /// long as the user kept typing, because the window kept reopening |
| 1917 | /// (#6397). Enter routing, mouse submit and hover registration stay on |
| 1918 | /// the timing predicate. |
| 1919 | #[must_use] |
| 1920 | pub fn composer_draft_is_submittable(&self) -> bool { |
| 1921 | !self.input.trim().is_empty() |
| 1922 | } |
| 1923 | |
| 1924 | /// Public wrapper around [`Self::consolidate_large_input`] that no-ops |
| 1925 | /// when the current input fits inside the safety cap. Both the paste- |
| 1926 | /// insert path (visible-before-submit) and the submit-time safety net |
| 1927 | /// route through here, so the cap is enforced exactly once even when |
| 1928 | /// both paths fire on the same buffer. |
| 1929 | /// |
| 1930 | /// Returns `false` when the input is oversized and could not be backed |
| 1931 | /// up to a paste file; the composer then still holds the full text. |
| 1932 | pub(crate) fn consolidate_large_input_if_oversized(&mut self) -> bool { |
| 1933 | if char_count(&self.input) > MAX_SUBMITTED_INPUT_CHARS { |
| 1934 | return self.consolidate_large_input(); |
| 1935 | } |
| 1936 | true |
| 1937 | } |
| 1938 | |
| 1939 | /// When the composer input exceeds [`MAX_SUBMITTED_INPUT_CHARS`], write |
| 1940 | /// the full content to a timestamped paste file under |
| 1941 | /// `.codewhale/pastes/` and replace `self.input` with an `@`-mention |
| 1942 | /// pointing at it so the model can read the full content via the |
| 1943 | /// normal file-mention resolution path (#553). |
| 1944 | /// |
| 1945 | /// Returns `false` without touching the composer when the paste file |
| 1946 | /// cannot be written, so the caller holds the submit instead of sending |
| 1947 | /// a truncated prompt. |
| 1948 | fn consolidate_large_input(&mut self) -> bool { |
| 1949 | let now = chrono::Local::now(); |
| 1950 | let suffix = uuid::Uuid::new_v4().to_string()[..8].to_string(); |
| 1951 | let filename = format!("paste-{}-{}.md", now.format("%Y-%m-%d-%H%M%S"), suffix); |
| 1952 | let rel_path = format!(".codewhale/pastes/{filename}"); |
| 1953 | |
| 1954 | // Confined to the workspace: a linked `.codewhale` or `pastes` |
| 1955 | // directory must not send the pasted text somewhere else. |
| 1956 | let file_path = self.workspace.join(&rel_path); |
| 1957 | let written = crate::fs_confined::write(&self.workspace, &file_path, self.input.as_bytes()); |
| 1958 | if let Err(error) = written { |
| 1959 | let limit = MAX_SUBMITTED_INPUT_CHARS.to_string(); |
| 1960 | // The toast row sheds clauses to fit and left only "Not sent", so |
| 1961 | // the toast carries a short form and the full reason, including |
| 1962 | // the write error, goes to the transcript where nothing is clipped. |
| 1963 | let short = self |
| 1964 | .tr(MessageId::ComposerOversizedSubmitHeldShort) |
| 1965 | .replace("{limit}", &limit); |
| 1966 | let reason = self |
| 1967 | .tr(MessageId::ComposerOversizedSubmitHeld) |
| 1968 | .replace("{limit}", &limit) |
| 1969 | .replace("{error}", &error.to_string()); |
| 1970 | self.push_status_toast(short, StatusToastLevel::Error, Some(8_000)); |
| 1971 | // Enter and paste both retry this; do not stack identical cells. |
| 1972 | let already_noted = matches!( |
| 1973 | self.history.last(), |
| 1974 | Some(HistoryCell::System { content }) if *content == reason |
| 1975 | ); |
| 1976 | if !already_noted { |
| 1977 | self.add_message(HistoryCell::System { content: reason }); |
| 1978 | } |
| 1979 | self.needs_redraw = true; |
| 1980 | return false; |
| 1981 | } |
| 1982 | let full_input = std::mem::take(&mut self.input); |
| 1983 | |
| 1984 | // Keep a truncated preview in the composer so the user can still |
| 1985 | // select, copy, and edit it. The full text is written to the paste |
| 1986 | // file; at submit time the inline text is replaced by the @mention |
| 1987 | // so the model reads the file instead of receiving the content twice. |
| 1988 | self.pending_paste_reference = Some(format!("@{rel_path}")); |
| 1989 | self.oversized_paste_full_text = Some(full_input.clone()); |
| 1990 | let display_chars = char_count(&full_input).min(MAX_COMPOSER_DISPLAY_CHARS); |
| 1991 | let mut truncated: String = full_input.chars().take(display_chars).collect(); |
| 1992 | if char_count(&full_input) > MAX_COMPOSER_DISPLAY_CHARS { |
| 1993 | truncated.push_str("\n\n---\n(content truncated for display — start typing to expand; full text sent to model)"); |
| 1994 | } |
| 1995 | self.input = truncated; |
| 1996 | self.resync_command_line_claim(); |
| 1997 | self.cursor_position = 0; |
| 1998 | self.push_status_toast( |
| 1999 | "Large paste backed up to file — the model will receive the full content.", |
| 2000 | StatusToastLevel::Info, |
| 2001 | Some(5_000), |
| 2002 | ); |
| 2003 | true |
| 2004 | } |
| 2005 | |
| 2006 | pub fn history_down(&mut self) { |
| 2007 | if self.input_history.is_empty() { |
| 2008 | return; |
| 2009 | } |
| 2010 | match self.history_index { |
| 2011 | None => {} |
| 2012 | Some(i) => { |
| 2013 | if i + 1 < self.input_history.len() { |
| 2014 | self.history_index = Some(i + 1); |
| 2015 | self.input = self.input_history[i + 1].clone(); |
| 2016 | self.resync_command_line_claim(); |
| 2017 | self.cursor_position = char_count(&self.input); |
| 2018 | self.selection_anchor = None; |
| 2019 | self.selected_attachment_index = None; |
| 2020 | self.slash_menu_hidden = false; |
| 2021 | self.paste_burst.clear_after_explicit_paste(); |
| 2022 | } else { |
| 2023 | self.history_index = None; |
| 2024 | if let Some(draft) = self.history_navigation_draft.take() { |
| 2025 | self.input = draft.input; |
| 2026 | self.resync_command_line_claim(); |
| 2027 | self.cursor_position = draft.cursor.min(char_count(&self.input)); |
| 2028 | self.selection_anchor = None; |
| 2029 | self.selected_attachment_index = None; |
| 2030 | self.slash_menu_hidden = false; |
| 2031 | self.paste_burst.clear_after_explicit_paste(); |
| 2032 | self.needs_redraw = true; |
| 2033 | } else { |
| 2034 | self.clear_input(); |
| 2035 | } |
| 2036 | } |
| 2037 | } |
| 2038 | } |
| 2039 | } |
| 2040 | } |
| 2041 |