| 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 | pub fn stash_current_input_for_recovery(&mut self) { |
| 580 | // Before stashing, expand any truncated paste so the saved draft |
| 581 | // contains the full text, not the truncated preview (#3263). |
| 582 | self.auto_expand_oversized_paste(); |
| 583 | let draft = self.input.clone(); |
| 584 | if draft.trim().is_empty() { |
| 585 | self.clear_undo_buffer = None; |
| 586 | return; |
| 587 | } |
| 588 | self.clear_undo_buffer = Some(draft.clone()); |
| 589 | self.remember_draft_for_recovery(draft); |
| 590 | } |
| 591 | |
| 592 | pub(crate) fn stash_typed_draft_before_restore(&mut self) { |
| 593 | if !self.input.trim().is_empty() { |
| 594 | self.stash_current_input_for_recovery(); |
| 595 | } |
| 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 | self.insert_str_with_raw_mouse_recovery(text, true); |
| 716 | } |
| 717 | |
| 718 | fn insert_str_with_raw_mouse_recovery(&mut self, text: &str, recover_raw_mouse: bool) { |
| 719 | if text.is_empty() { |
| 720 | return; |
| 721 | } |
| 722 | // Any edit detaches a recalled history entry (mirrors insert_char): |
| 723 | // without this a paste typed while navigating stays on a stale index |
| 724 | // and the next Up/Down silently discards the pasted text. |
| 725 | self.clear_input_history_navigation(); |
| 726 | self.auto_expand_oversized_paste(); |
| 727 | self.delete_selection(); |
| 728 | self.selected_attachment_index = None; |
| 729 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 730 | let byte_index = byte_index_at_char(&self.input, cursor); |
| 731 | self.input.insert_str(byte_index, text); |
| 732 | self.resync_command_line_claim(); |
| 733 | self.cursor_position = cursor + char_count(text); |
| 734 | if recover_raw_mouse { |
| 735 | self.strip_raw_mouse_reports_from_input(); |
| 736 | } |
| 737 | self.slash_menu_hidden = false; |
| 738 | self.mention_menu_hidden = false; |
| 739 | self.mention_menu_selected = 0; |
| 740 | self.needs_redraw = true; |
| 741 | } |
| 742 | |
| 743 | pub fn insert_paste_text(&mut self, text: &str) { |
| 744 | if let Some(pending) = self.paste_burst.flush_before_modified_input() { |
| 745 | self.insert_str(&pending); |
| 746 | } |
| 747 | if self.attach_pasted_image_paths(text) { |
| 748 | self.paste_burst.clear_after_explicit_paste(); |
| 749 | return; |
| 750 | } |
| 751 | let normalized = normalize_paste_text(text); |
| 752 | if !normalized.is_empty() { |
| 753 | self.insert_str_with_raw_mouse_recovery(&normalized, false); |
| 754 | } |
| 755 | self.paste_burst.clear_after_explicit_paste(); |
| 756 | // Large pasted input stays editable and visible until submit. The |
| 757 | // submit-time safety net consolidates oversized composer content into |
| 758 | // an @paste-...md mention before dispatch, so no path silently |
| 759 | // truncates user input. |
| 760 | // self.consolidate_large_input_if_oversized(); // deferred to submit time |
| 761 | } |
| 762 | |
| 763 | /// A file dragged onto the terminal arrives as a paste of its path. When |
| 764 | /// the whole paste names local image files, attach them on the same |
| 765 | /// `[Attached image: …]` line a clipboard image gets, so each shows as a |
| 766 | /// composer attachment and is sent to the model as an image part (the |
| 767 | /// engine expands the line when it builds the user message, and the |
| 768 | /// route's vision capability decides per request; a text-only route gets |
| 769 | /// the omission notice there). Returns whether the paste was consumed. |
| 770 | /// |
| 771 | /// A command line (`/…`) or shell line (`!…`) keeps the literal path. |
| 772 | pub(crate) fn attach_pasted_image_paths(&mut self, text: &str) -> bool { |
| 773 | if self.input.trim_start().starts_with(['/', '!']) { |
| 774 | return false; |
| 775 | } |
| 776 | let Some(paths) = codewhale_engine::image_attach::pasted_image_paths(text) else { |
| 777 | return false; |
| 778 | }; |
| 779 | for path in &paths { |
| 780 | self.insert_media_attachment("image", path, None); |
| 781 | } |
| 782 | self.show_input_hint(match paths.as_slice() { |
| 783 | [path] => format!("Attached image: {}", path.display()), |
| 784 | paths => format!("Attached {} images", paths.len()), |
| 785 | }); |
| 786 | true |
| 787 | } |
| 788 | |
| 789 | pub fn insert_media_attachment(&mut self, kind: &str, path: &Path, description: Option<&str>) { |
| 790 | // An attachment is user input: the launch card dissolves on the first |
| 791 | // typed character, and a pasted picture has to leave it too, or an |
| 792 | // empty composer keeps the card up and the attachment row behind it. |
| 793 | if self.launch.visible && !self.launch.return_to_session { |
| 794 | self.launch.dissolve_card(self.ambient_clock_ms); |
| 795 | } |
| 796 | let reference = media_attachment_reference(kind, path, description); |
| 797 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 798 | let byte_index = byte_index_at_char(&self.input, cursor); |
| 799 | let needs_prefix_newline = self.input[..byte_index] |
| 800 | .chars() |
| 801 | .last() |
| 802 | .is_some_and(|ch| !ch.is_whitespace()); |
| 803 | let needs_suffix_newline = self.input[byte_index..] |
| 804 | .chars() |
| 805 | .next() |
| 806 | .is_some_and(|ch| !ch.is_whitespace()); |
| 807 | |
| 808 | let mut inserted = String::new(); |
| 809 | if needs_prefix_newline { |
| 810 | inserted.push('\n'); |
| 811 | } |
| 812 | inserted.push_str(&reference); |
| 813 | if needs_suffix_newline || self.input[byte_index..].is_empty() { |
| 814 | inserted.push('\n'); |
| 815 | } |
| 816 | self.insert_str(&inserted); |
| 817 | self.paste_burst.clear_after_explicit_paste(); |
| 818 | } |
| 819 | |
| 820 | pub fn select_previous_composer_attachment(&mut self) -> bool { |
| 821 | let count = self.composer_attachment_count(); |
| 822 | if count == 0 { |
| 823 | self.selected_attachment_index = None; |
| 824 | return false; |
| 825 | } |
| 826 | |
| 827 | let next = self |
| 828 | .selected_composer_attachment_index() |
| 829 | .map_or(count.saturating_sub(1), |index| index.saturating_sub(1)); |
| 830 | self.selected_attachment_index = Some(next); |
| 831 | self.cursor_position = 0; |
| 832 | self.show_input_hint("Attachment selected - Backspace/Delete removes it"); |
| 833 | self.needs_redraw = true; |
| 834 | true |
| 835 | } |
| 836 | |
| 837 | pub fn select_next_composer_attachment(&mut self) -> bool { |
| 838 | let count = self.composer_attachment_count(); |
| 839 | let Some(index) = self.selected_composer_attachment_index() else { |
| 840 | return false; |
| 841 | }; |
| 842 | if index + 1 < count { |
| 843 | self.selected_attachment_index = Some(index + 1); |
| 844 | self.show_input_hint("Attachment selected - Backspace/Delete removes it"); |
| 845 | } else { |
| 846 | self.selected_attachment_index = None; |
| 847 | self.show_input_hint("Composer focused"); |
| 848 | } |
| 849 | self.needs_redraw = true; |
| 850 | true |
| 851 | } |
| 852 | |
| 853 | pub fn clear_composer_attachment_selection(&mut self) -> bool { |
| 854 | if self.selected_attachment_index.take().is_some() { |
| 855 | self.show_input_hint("Composer focused"); |
| 856 | self.needs_redraw = true; |
| 857 | true |
| 858 | } else { |
| 859 | false |
| 860 | } |
| 861 | } |
| 862 | |
| 863 | pub fn remove_selected_composer_attachment(&mut self) -> bool { |
| 864 | let references = codewhale_core::media_attachment_references(&self.input); |
| 865 | let Some(index) = self |
| 866 | .selected_composer_attachment_index() |
| 867 | .filter(|index| *index < references.len()) |
| 868 | else { |
| 869 | self.selected_attachment_index = None; |
| 870 | return false; |
| 871 | }; |
| 872 | self.clear_input_history_navigation(); |
| 873 | let reference = references[index].clone(); |
| 874 | let cursor_byte = byte_index_at_char(&self.input, self.cursor_position); |
| 875 | let new_cursor_byte = if cursor_byte <= reference.start_byte { |
| 876 | cursor_byte |
| 877 | } else if cursor_byte >= reference.end_byte { |
| 878 | cursor_byte.saturating_sub(reference.end_byte - reference.start_byte) |
| 879 | } else { |
| 880 | reference.start_byte |
| 881 | }; |
| 882 | |
| 883 | self.input |
| 884 | .replace_range(reference.start_byte..reference.end_byte, ""); |
| 885 | self.cursor_position = self.input[..new_cursor_byte.min(self.input.len())] |
| 886 | .chars() |
| 887 | .count(); |
| 888 | let remaining = self.composer_attachment_count(); |
| 889 | self.selected_attachment_index = if remaining == 0 { |
| 890 | None |
| 891 | } else { |
| 892 | Some(index.min(remaining.saturating_sub(1))) |
| 893 | }; |
| 894 | self.slash_menu_hidden = false; |
| 895 | self.mention_menu_hidden = false; |
| 896 | self.mention_menu_selected = 0; |
| 897 | self.show_input_hint(format!("Removed attachment: {}", reference.path)); |
| 898 | self.needs_redraw = true; |
| 899 | true |
| 900 | } |
| 901 | |
| 902 | #[cfg(test)] |
| 903 | pub fn flush_paste_burst_if_due(&mut self, now: Instant) -> bool { |
| 904 | match self.paste_burst.flush_if_due(now) { |
| 905 | FlushResult::Paste(text) | FlushResult::TextContinuation(text) => { |
| 906 | self.insert_str(&text); |
| 907 | true |
| 908 | } |
| 909 | FlushResult::Typed(ch) => { |
| 910 | self.insert_char(ch); |
| 911 | true |
| 912 | } |
| 913 | FlushResult::SuppressionExpired => { |
| 914 | self.needs_redraw = true; |
| 915 | true |
| 916 | } |
| 917 | FlushResult::None => false, |
| 918 | } |
| 919 | } |
| 920 | |
| 921 | pub(crate) fn take_paste_burst_flush_if_enabled(&mut self, now: Instant) -> FlushResult { |
| 922 | if self.use_paste_burst_detection { |
| 923 | self.paste_burst.flush_if_due(now) |
| 924 | } else { |
| 925 | FlushResult::None |
| 926 | } |
| 927 | } |
| 928 | |
| 929 | pub fn paste_burst_next_flush_delay_if_enabled(&self, now: Instant) -> Option<Duration> { |
| 930 | if self.use_paste_burst_detection { |
| 931 | self.paste_burst.next_flush_delay(now) |
| 932 | } else { |
| 933 | None |
| 934 | } |
| 935 | } |
| 936 | |
| 937 | pub fn flush_paste_burst_before_modified_input_if_enabled(&mut self) -> Option<String> { |
| 938 | if self.use_paste_burst_detection { |
| 939 | self.paste_burst.flush_before_modified_input() |
| 940 | } else { |
| 941 | None |
| 942 | } |
| 943 | } |
| 944 | |
| 945 | pub fn insert_char(&mut self, c: char) { |
| 946 | self.acknowledge_sticky_on_composer_activity(); |
| 947 | self.clear_input_history_navigation(); |
| 948 | self.auto_expand_oversized_paste(); |
| 949 | self.delete_selection(); |
| 950 | self.selected_attachment_index = None; |
| 951 | // #5925: a line that starts with a typed `/` is a command from its |
| 952 | // first byte, and stays one until Enter. Recorded here — the only |
| 953 | // place a character reaches the composer by typing — so the submit |
| 954 | // guard can tell a lost `/` from a deleted one. |
| 955 | let starts_line = self.input.trim().is_empty(); |
| 956 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 957 | let byte_index = byte_index_at_char(&self.input, cursor); |
| 958 | self.input.insert(byte_index, c); |
| 959 | if starts_line { |
| 960 | self.line_began_with_slash = c == '/'; |
| 961 | } |
| 962 | self.resync_command_line_claim(); |
| 963 | self.cursor_position = cursor + 1; |
| 964 | self.strip_raw_mouse_reports_from_input(); |
| 965 | self.slash_menu_hidden = false; |
| 966 | self.mention_menu_hidden = false; |
| 967 | self.mention_menu_selected = 0; |
| 968 | self.needs_redraw = true; |
| 969 | } |
| 970 | |
| 971 | pub fn delete_char(&mut self) { |
| 972 | self.clear_input_history_navigation(); |
| 973 | self.auto_expand_oversized_paste(); |
| 974 | if self.delete_selection() { |
| 975 | return; |
| 976 | } |
| 977 | self.selected_attachment_index = None; |
| 978 | if self.cursor_position == 0 { |
| 979 | return; |
| 980 | } |
| 981 | // Grapheme-aware: Backspace removes the whole cluster before the |
| 982 | // cursor (emoji ZWJ sequence, flag pair, CJK char + combining mark), |
| 983 | // never a lone scalar out of the middle of one. |
| 984 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 985 | let target = prev_grapheme_boundary(&self.input, cursor); |
| 986 | let removed = remove_char_range(&mut self.input, target, cursor); |
| 987 | self.resync_command_line_claim(); |
| 988 | if removed { |
| 989 | self.cursor_position = target; |
| 990 | self.slash_menu_hidden = false; |
| 991 | self.mention_menu_hidden = false; |
| 992 | self.mention_menu_selected = 0; |
| 993 | self.needs_redraw = true; |
| 994 | } |
| 995 | } |
| 996 | |
| 997 | pub fn delete_char_forward(&mut self) { |
| 998 | self.clear_input_history_navigation(); |
| 999 | self.auto_expand_oversized_paste(); |
| 1000 | if self.delete_selection() { |
| 1001 | return; |
| 1002 | } |
| 1003 | self.selected_attachment_index = None; |
| 1004 | if self.input.is_empty() { |
| 1005 | return; |
| 1006 | } |
| 1007 | // Grapheme-aware: forward-delete removes the whole cluster at the |
| 1008 | // cursor rather than a single scalar from inside it. |
| 1009 | let target = self.cursor_position; |
| 1010 | let end = next_grapheme_boundary(&self.input, target); |
| 1011 | let removed = remove_char_range(&mut self.input, target, end); |
| 1012 | self.resync_command_line_claim(); |
| 1013 | if !removed { |
| 1014 | self.cursor_position = char_count(&self.input); |
| 1015 | } |
| 1016 | self.slash_menu_hidden = false; |
| 1017 | self.mention_menu_hidden = false; |
| 1018 | self.mention_menu_selected = 0; |
| 1019 | self.needs_redraw = true; |
| 1020 | } |
| 1021 | |
| 1022 | /// Delete the word before the cursor. |
| 1023 | pub fn delete_word_backward(&mut self) { |
| 1024 | self.clear_input_history_navigation(); |
| 1025 | if self.delete_selection() { |
| 1026 | return; |
| 1027 | } |
| 1028 | self.selected_attachment_index = None; |
| 1029 | if self.cursor_position == 0 { |
| 1030 | return; |
| 1031 | } |
| 1032 | |
| 1033 | let cursor_byte = byte_index_at_char(&self.input, self.cursor_position); |
| 1034 | let mut word_start = cursor_byte; |
| 1035 | |
| 1036 | while word_start > 0 { |
| 1037 | let Some((prev, ch)) = self.input[..word_start].char_indices().next_back() else { |
| 1038 | break; |
| 1039 | }; |
| 1040 | if !ch.is_whitespace() { |
| 1041 | break; |
| 1042 | } |
| 1043 | word_start = prev; |
| 1044 | } |
| 1045 | |
| 1046 | while word_start > 0 { |
| 1047 | let Some((prev, ch)) = self.input[..word_start].char_indices().next_back() else { |
| 1048 | break; |
| 1049 | }; |
| 1050 | if ch.is_whitespace() { |
| 1051 | break; |
| 1052 | } |
| 1053 | word_start = prev; |
| 1054 | } |
| 1055 | |
| 1056 | if word_start < cursor_byte { |
| 1057 | self.input.replace_range(word_start..cursor_byte, ""); |
| 1058 | self.resync_command_line_claim(); |
| 1059 | self.cursor_position = char_count(&self.input[..word_start]); |
| 1060 | self.slash_menu_hidden = false; |
| 1061 | self.mention_menu_hidden = false; |
| 1062 | self.mention_menu_selected = 0; |
| 1063 | self.needs_redraw = true; |
| 1064 | } |
| 1065 | } |
| 1066 | |
| 1067 | /// Delete from the cursor to the start of the line. |
| 1068 | pub fn delete_to_start_of_line(&mut self) { |
| 1069 | self.clear_input_history_navigation(); |
| 1070 | if self.delete_selection() { |
| 1071 | return; |
| 1072 | } |
| 1073 | self.selected_attachment_index = None; |
| 1074 | if self.cursor_position == 0 { |
| 1075 | return; |
| 1076 | } |
| 1077 | |
| 1078 | let cursor_byte = byte_index_at_char(&self.input, self.cursor_position); |
| 1079 | // Find the start of the current line (last newline or start of string) |
| 1080 | let line_start = self.input[..cursor_byte] |
| 1081 | .rfind('\n') |
| 1082 | .map(|idx| idx + 1) |
| 1083 | .unwrap_or(0); |
| 1084 | |
| 1085 | if line_start < cursor_byte { |
| 1086 | self.input.replace_range(line_start..cursor_byte, ""); |
| 1087 | self.resync_command_line_claim(); |
| 1088 | self.cursor_position = char_count(&self.input[..line_start]); |
| 1089 | self.slash_menu_hidden = false; |
| 1090 | self.mention_menu_hidden = false; |
| 1091 | self.mention_menu_selected = 0; |
| 1092 | self.needs_redraw = true; |
| 1093 | } |
| 1094 | } |
| 1095 | |
| 1096 | /// Delete the word after the cursor. |
| 1097 | pub fn delete_word_forward(&mut self) { |
| 1098 | self.clear_input_history_navigation(); |
| 1099 | if self.delete_selection() { |
| 1100 | return; |
| 1101 | } |
| 1102 | self.selected_attachment_index = None; |
| 1103 | let cursor_byte = byte_index_at_char(&self.input, self.cursor_position); |
| 1104 | if cursor_byte >= self.input.len() { |
| 1105 | return; |
| 1106 | } |
| 1107 | |
| 1108 | let mut word_end = cursor_byte; |
| 1109 | while word_end < self.input.len() { |
| 1110 | let Some(ch) = self.input[word_end..].chars().next() else { |
| 1111 | break; |
| 1112 | }; |
| 1113 | if !ch.is_whitespace() { |
| 1114 | break; |
| 1115 | } |
| 1116 | word_end += ch.len_utf8(); |
| 1117 | } |
| 1118 | |
| 1119 | while word_end < self.input.len() { |
| 1120 | let Some(ch) = self.input[word_end..].chars().next() else { |
| 1121 | break; |
| 1122 | }; |
| 1123 | if ch.is_whitespace() { |
| 1124 | break; |
| 1125 | } |
| 1126 | word_end += ch.len_utf8(); |
| 1127 | } |
| 1128 | |
| 1129 | if cursor_byte < word_end { |
| 1130 | self.input.replace_range(cursor_byte..word_end, ""); |
| 1131 | self.resync_command_line_claim(); |
| 1132 | self.slash_menu_hidden = false; |
| 1133 | self.mention_menu_hidden = false; |
| 1134 | self.mention_menu_selected = 0; |
| 1135 | self.needs_redraw = true; |
| 1136 | } |
| 1137 | } |
| 1138 | |
| 1139 | /// Cut from the cursor to the end of the current logical line into the |
| 1140 | /// kill buffer. If the cursor is already at end-of-line and a trailing |
| 1141 | /// newline exists, that newline is consumed so repeated invocations |
| 1142 | /// continue to make progress (matching emacs/codex semantics). |
| 1143 | /// |
| 1144 | /// Returns `true` when bytes were moved into the kill buffer. |
| 1145 | pub fn kill_to_end_of_line(&mut self) -> bool { |
| 1146 | self.clear_input_history_navigation(); |
| 1147 | if let Some((start, end)) = self.selection_range() { |
| 1148 | let sb = byte_index_at_char(&self.input, start); |
| 1149 | let eb = byte_index_at_char(&self.input, end); |
| 1150 | self.kill_buffer = self.input[sb..eb].to_string(); |
| 1151 | self.delete_selection(); |
| 1152 | return true; |
| 1153 | } |
| 1154 | let total_chars = char_count(&self.input); |
| 1155 | let cursor = self.cursor_position.min(total_chars); |
| 1156 | let start_byte = byte_index_at_char(&self.input, cursor); |
| 1157 | |
| 1158 | // Find the byte offset of the next '\n' (relative to the whole string) |
| 1159 | // or the end of the buffer if no newline exists at/after the cursor. |
| 1160 | let eol_byte = self.input[start_byte..] |
| 1161 | .find('\n') |
| 1162 | .map(|rel| start_byte + rel) |
| 1163 | .unwrap_or_else(|| self.input.len()); |
| 1164 | |
| 1165 | let end_byte = if start_byte == eol_byte { |
| 1166 | // Cursor is at EOL — consume the newline itself if one is there. |
| 1167 | if eol_byte < self.input.len() { |
| 1168 | eol_byte + 1 |
| 1169 | } else { |
| 1170 | return false; |
| 1171 | } |
| 1172 | } else { |
| 1173 | eol_byte |
| 1174 | }; |
| 1175 | |
| 1176 | let removed: String = self.input[start_byte..end_byte].to_string(); |
| 1177 | if removed.is_empty() { |
| 1178 | return false; |
| 1179 | } |
| 1180 | |
| 1181 | self.kill_buffer = removed; |
| 1182 | self.input.replace_range(start_byte..end_byte, ""); |
| 1183 | self.resync_command_line_claim(); |
| 1184 | // Cursor stays at the same character index (start of removed range). |
| 1185 | self.cursor_position = cursor; |
| 1186 | self.slash_menu_hidden = false; |
| 1187 | self.mention_menu_hidden = false; |
| 1188 | self.mention_menu_selected = 0; |
| 1189 | self.needs_redraw = true; |
| 1190 | true |
| 1191 | } |
| 1192 | |
| 1193 | /// Insert the contents of the kill buffer at the cursor, advancing it. |
| 1194 | /// The kill buffer is left intact so multiple yanks duplicate the text. |
| 1195 | /// Returns `true` if any text was inserted. |
| 1196 | pub fn yank(&mut self) -> bool { |
| 1197 | if self.kill_buffer.is_empty() { |
| 1198 | return false; |
| 1199 | } |
| 1200 | self.delete_selection(); |
| 1201 | self.clear_input_history_navigation(); |
| 1202 | let text = self.kill_buffer.clone(); |
| 1203 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 1204 | let byte_index = byte_index_at_char(&self.input, cursor); |
| 1205 | self.input.insert_str(byte_index, &text); |
| 1206 | self.resync_command_line_claim(); |
| 1207 | self.cursor_position = cursor + char_count(&text); |
| 1208 | self.slash_menu_hidden = false; |
| 1209 | self.mention_menu_hidden = false; |
| 1210 | self.mention_menu_selected = 0; |
| 1211 | self.needs_redraw = true; |
| 1212 | true |
| 1213 | } |
| 1214 | |
| 1215 | pub fn move_cursor_left(&mut self) { |
| 1216 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 1217 | self.cursor_position = prev_grapheme_boundary(&self.input, cursor); |
| 1218 | self.needs_redraw = true; |
| 1219 | } |
| 1220 | |
| 1221 | pub fn move_cursor_right(&mut self) { |
| 1222 | let total = char_count(&self.input); |
| 1223 | if self.cursor_position < total { |
| 1224 | self.cursor_position = next_grapheme_boundary(&self.input, self.cursor_position); |
| 1225 | self.needs_redraw = true; |
| 1226 | } |
| 1227 | } |
| 1228 | |
| 1229 | pub fn move_cursor_start(&mut self) { |
| 1230 | self.cursor_position = 0; |
| 1231 | self.needs_redraw = true; |
| 1232 | } |
| 1233 | |
| 1234 | pub fn move_cursor_end(&mut self) { |
| 1235 | self.cursor_position = char_count(&self.input); |
| 1236 | self.needs_redraw = true; |
| 1237 | } |
| 1238 | |
| 1239 | /// In a multiline composer, jump to the start of the current line. |
| 1240 | /// On single-line input this is equivalent to `move_cursor_start`. |
| 1241 | pub fn move_cursor_line_start(&mut self) { |
| 1242 | let byte_pos = byte_index_at_char(&self.input, self.cursor_position); |
| 1243 | let before = &self.input[..byte_pos]; |
| 1244 | if let Some(last_nl_byte) = before.rfind('\n') { |
| 1245 | // Position after the '\n' (start of the current line). |
| 1246 | self.cursor_position = char_count(&self.input[..=last_nl_byte]); |
| 1247 | } else { |
| 1248 | self.cursor_position = 0; |
| 1249 | } |
| 1250 | self.needs_redraw = true; |
| 1251 | } |
| 1252 | |
| 1253 | /// In a multiline composer, jump to the end of the current line |
| 1254 | /// (just before the next `\n` or at the end of input). |
| 1255 | /// On single-line input this is equivalent to `move_cursor_end`. |
| 1256 | pub fn move_cursor_line_end(&mut self) { |
| 1257 | let search_start = byte_index_at_char(&self.input, self.cursor_position); |
| 1258 | if let Some(offset) = self.input[search_start..].find('\n') { |
| 1259 | self.cursor_position = char_count(&self.input[..search_start + offset]); |
| 1260 | } else { |
| 1261 | self.cursor_position = char_count(&self.input); |
| 1262 | } |
| 1263 | self.needs_redraw = true; |
| 1264 | } |
| 1265 | |
| 1266 | /// Move forward one word. Skips over the current word then any trailing |
| 1267 | /// whitespace to land on the first character of the next word. |
| 1268 | pub fn move_cursor_word_forward(&mut self) { |
| 1269 | let text = self.input.clone(); |
| 1270 | let total = char_count(&text); |
| 1271 | let mut pos = self.cursor_position; |
| 1272 | if pos >= total { |
| 1273 | return; |
| 1274 | } |
| 1275 | // Skip non-whitespace (current word). |
| 1276 | while pos < total { |
| 1277 | let byte = byte_index_at_char(&text, pos); |
| 1278 | let ch = text[byte..].chars().next().unwrap_or(' '); |
| 1279 | if ch.is_whitespace() { |
| 1280 | break; |
| 1281 | } |
| 1282 | pos += 1; |
| 1283 | } |
| 1284 | // Skip whitespace. |
| 1285 | while pos < total { |
| 1286 | let byte = byte_index_at_char(&text, pos); |
| 1287 | let ch = text[byte..].chars().next().unwrap_or(' '); |
| 1288 | if !ch.is_whitespace() { |
| 1289 | break; |
| 1290 | } |
| 1291 | pos += 1; |
| 1292 | } |
| 1293 | self.cursor_position = pos; |
| 1294 | self.needs_redraw = true; |
| 1295 | } |
| 1296 | |
| 1297 | /// Move backward one word. Skips leading whitespace then the preceding |
| 1298 | /// word to land on its first character. |
| 1299 | pub fn move_cursor_word_backward(&mut self) { |
| 1300 | let text = self.input.clone(); |
| 1301 | let mut pos = self.cursor_position; |
| 1302 | if pos == 0 { |
| 1303 | return; |
| 1304 | } |
| 1305 | // Step back one so we're not already at the word start. |
| 1306 | pos -= 1; |
| 1307 | // Skip whitespace. |
| 1308 | while pos > 0 { |
| 1309 | let byte = byte_index_at_char(&text, pos); |
| 1310 | let ch = text[byte..].chars().next().unwrap_or(' '); |
| 1311 | if !ch.is_whitespace() { |
| 1312 | break; |
| 1313 | } |
| 1314 | pos -= 1; |
| 1315 | } |
| 1316 | // Skip non-whitespace. |
| 1317 | while pos > 0 { |
| 1318 | let byte = byte_index_at_char(&text, pos - 1); |
| 1319 | let ch = text[byte..].chars().next().unwrap_or(' '); |
| 1320 | if ch.is_whitespace() { |
| 1321 | break; |
| 1322 | } |
| 1323 | pos -= 1; |
| 1324 | } |
| 1325 | self.cursor_position = pos; |
| 1326 | self.needs_redraw = true; |
| 1327 | } |
| 1328 | |
| 1329 | /// Select the entire composer contents: anchor at the start, cursor at |
| 1330 | /// the end. Expands an oversized-paste preview first so the selection |
| 1331 | /// covers the real draft, not a truncated placeholder (#3263). |
| 1332 | pub fn select_all(&mut self) { |
| 1333 | self.auto_expand_oversized_paste(); |
| 1334 | if self.input.is_empty() { |
| 1335 | self.selection_anchor = None; |
| 1336 | return; |
| 1337 | } |
| 1338 | self.selection_anchor = Some(0); |
| 1339 | self.cursor_position = char_count(&self.input); |
| 1340 | self.needs_redraw = true; |
| 1341 | } |
| 1342 | |
| 1343 | /// Delete the selected text, place cursor at the start of the deleted range. |
| 1344 | /// Returns true if a selection was deleted. |
| 1345 | /// |
| 1346 | /// When the selection spans the whole draft (e.g. select-all then type or |
| 1347 | /// Backspace), the outgoing text is stashed exactly like `Ctrl+U` so the |
| 1348 | /// destruction is recoverable with `Ctrl+Z` / the draft history. |
| 1349 | pub fn delete_selection(&mut self) -> bool { |
| 1350 | let Some((start, end)) = self.selection_range() else { |
| 1351 | return false; |
| 1352 | }; |
| 1353 | if start == 0 && end == char_count(&self.input) { |
| 1354 | let draft = self.input.clone(); |
| 1355 | if !draft.trim().is_empty() { |
| 1356 | self.clear_undo_buffer = Some(draft.clone()); |
| 1357 | self.remember_draft_for_recovery(draft); |
| 1358 | } |
| 1359 | } |
| 1360 | let sb = byte_index_at_char(&self.input, start); |
| 1361 | let eb = byte_index_at_char(&self.input, end); |
| 1362 | self.input.replace_range(sb..eb, ""); |
| 1363 | self.resync_command_line_claim(); |
| 1364 | self.cursor_position = start; |
| 1365 | self.selection_anchor = None; |
| 1366 | self.clear_input_history_navigation(); |
| 1367 | self.slash_menu_hidden = false; |
| 1368 | self.mention_menu_hidden = false; |
| 1369 | self.mention_menu_selected = 0; |
| 1370 | self.needs_redraw = true; |
| 1371 | true |
| 1372 | } |
| 1373 | |
| 1374 | // === Vim composer mode helpers === |
| 1375 | /// Move the cursor to the start of the current logical line (vim `0`). |
| 1376 | pub fn vim_move_line_start(&mut self) { |
| 1377 | let text = self.input.clone(); |
| 1378 | let cursor_byte = byte_index_at_char(&text, self.cursor_position); |
| 1379 | // Walk backward until we find a newline or the start of the string. |
| 1380 | let line_start_byte = text[..cursor_byte].rfind('\n').map_or(0, |idx| idx + 1); |
| 1381 | self.cursor_position = char_count(&text[..line_start_byte]); |
| 1382 | self.needs_redraw = true; |
| 1383 | } |
| 1384 | |
| 1385 | /// Move the cursor onto the last character of the current logical line |
| 1386 | /// (vim `$`). |
| 1387 | pub fn vim_move_line_end(&mut self) { |
| 1388 | self.move_cursor_line_end(); |
| 1389 | self.vim_step_off_line_end(); |
| 1390 | } |
| 1391 | |
| 1392 | fn vim_step_off_line_end(&mut self) { |
| 1393 | let cursor = self.cursor_position.min(char_count(&self.input)); |
| 1394 | let cursor_byte = byte_index_at_char(&self.input, cursor); |
| 1395 | let line_start_byte = self.input[..cursor_byte] |
| 1396 | .rfind('\n') |
| 1397 | .map_or(0, |idx| idx + 1); |
| 1398 | let on_line_end = self.input[cursor_byte..] |
| 1399 | .chars() |
| 1400 | .next() |
| 1401 | .is_none_or(|ch| ch == '\n'); |
| 1402 | if on_line_end && cursor_byte > line_start_byte { |
| 1403 | self.cursor_position = prev_grapheme_boundary(&self.input, cursor); |
| 1404 | } |
| 1405 | } |
| 1406 | |
| 1407 | /// Move forward one word (vim `w`). Skips over the current word then any |
| 1408 | /// trailing whitespace to land on the first character of the next word. |
| 1409 | pub fn vim_move_word_forward(&mut self) { |
| 1410 | self.move_cursor_word_forward(); |
| 1411 | } |
| 1412 | |
| 1413 | /// Move backward one word (vim `b`). Skips leading whitespace then the |
| 1414 | /// preceding word to land on its first character. |
| 1415 | pub fn vim_move_word_backward(&mut self) { |
| 1416 | self.move_cursor_word_backward(); |
| 1417 | } |
| 1418 | |
| 1419 | /// Delete the character under the cursor (vim `x`). |
| 1420 | pub fn vim_delete_char_under_cursor(&mut self) { |
| 1421 | self.clear_input_history_navigation(); |
| 1422 | self.auto_expand_oversized_paste(); |
| 1423 | let total = char_count(&self.input); |
| 1424 | if self.cursor_position >= total { |
| 1425 | return; |
| 1426 | } |
| 1427 | let pos = self.cursor_position; |
| 1428 | if self.input[byte_index_at_char(&self.input, pos)..].starts_with('\n') { |
| 1429 | return; |
| 1430 | } |
| 1431 | // Grapheme-aware: `x` deletes the whole cluster under the cursor. |
| 1432 | let end = next_grapheme_boundary(&self.input, pos); |
| 1433 | remove_char_range(&mut self.input, pos, end); |
| 1434 | self.resync_command_line_claim(); |
| 1435 | // Keep cursor in bounds after deletion, on the line's last cluster's start. |
| 1436 | self.vim_step_off_line_end(); |
| 1437 | self.needs_redraw = true; |
| 1438 | } |
| 1439 | |
| 1440 | /// Delete the entire current logical line (vim `dd`). |
| 1441 | pub fn vim_delete_line(&mut self) { |
| 1442 | self.clear_input_history_navigation(); |
| 1443 | let text = self.input.clone(); |
| 1444 | let cursor_byte = byte_index_at_char(&text, self.cursor_position); |
| 1445 | let line_start_byte = text[..cursor_byte].rfind('\n').map_or(0, |idx| idx + 1); |
| 1446 | let line_end_byte = text[cursor_byte..] |
| 1447 | .find('\n') |
| 1448 | .map_or(text.len(), |rel| cursor_byte + rel); |
| 1449 | |
| 1450 | // Include the trailing newline if present, or the leading newline for the |
| 1451 | // very last non-terminated line to avoid leaving a dangling newline. |
| 1452 | let (remove_start, remove_end) = if line_end_byte < text.len() { |
| 1453 | // There is a newline after the line — remove it too. |
| 1454 | (line_start_byte, line_end_byte + 1) |
| 1455 | } else if line_start_byte > 0 { |
| 1456 | // Last line without trailing newline — remove the preceding newline. |
| 1457 | (line_start_byte - 1, line_end_byte) |
| 1458 | } else { |
| 1459 | // Only line in the buffer. |
| 1460 | (line_start_byte, line_end_byte) |
| 1461 | }; |
| 1462 | |
| 1463 | self.input.replace_range(remove_start..remove_end, ""); |
| 1464 | self.resync_command_line_claim(); |
| 1465 | self.cursor_position = char_count(&self.input[..remove_start]); |
| 1466 | self.needs_redraw = true; |
| 1467 | } |
| 1468 | |
| 1469 | /// Enter insert mode at the cursor (vim `i`). |
| 1470 | pub fn vim_enter_insert(&mut self) { |
| 1471 | self.vim_mode = VimMode::Insert; |
| 1472 | self.needs_redraw = true; |
| 1473 | } |
| 1474 | |
| 1475 | /// Enter insert mode after the cursor (vim `a`). |
| 1476 | pub fn vim_enter_append(&mut self) { |
| 1477 | let total = char_count(&self.input); |
| 1478 | if self.cursor_position < total |
| 1479 | && !self.input[byte_index_at_char(&self.input, self.cursor_position)..] |
| 1480 | .starts_with('\n') |
| 1481 | { |
| 1482 | // After the whole cluster under the cursor, not one scalar in. |
| 1483 | self.cursor_position = next_grapheme_boundary(&self.input, self.cursor_position); |
| 1484 | } |
| 1485 | self.vim_mode = VimMode::Insert; |
| 1486 | self.needs_redraw = true; |
| 1487 | } |
| 1488 | |
| 1489 | /// Open a new line below and enter insert mode (vim `o`). |
| 1490 | pub fn vim_open_line_below(&mut self) { |
| 1491 | // Move to end of line, then insert a newline. |
| 1492 | self.move_cursor_line_end(); |
| 1493 | self.insert_char('\n'); |
| 1494 | self.vim_mode = VimMode::Insert; |
| 1495 | } |
| 1496 | |
| 1497 | /// Return to Normal mode from Insert (vim `Esc`). |
| 1498 | pub fn vim_enter_normal(&mut self) { |
| 1499 | self.vim_mode = VimMode::Normal; |
| 1500 | self.vim_pending_d = false; |
| 1501 | // In Normal mode the cursor sits on a character, not after the last |
| 1502 | // one: on the last grapheme cluster's start (U01-m4). |
| 1503 | let total = char_count(&self.input); |
| 1504 | if self.cursor_position > 0 && self.cursor_position >= total { |
| 1505 | self.cursor_position = prev_grapheme_boundary(&self.input, total); |
| 1506 | } |
| 1507 | self.needs_redraw = true; |
| 1508 | } |
| 1509 | |
| 1510 | /// Move the cursor down one logical line within the buffer (vim `j`). |
| 1511 | /// Falls back to history-down when already on the last line. |
| 1512 | pub fn vim_move_down(&mut self) { |
| 1513 | let text = self.input.clone(); |
| 1514 | let total = char_count(&text); |
| 1515 | if self.cursor_position >= total { |
| 1516 | self.history_down(); |
| 1517 | return; |
| 1518 | } |
| 1519 | let cursor_byte = byte_index_at_char(&text, self.cursor_position); |
| 1520 | let rest = &text[cursor_byte..]; |
| 1521 | if let Some(rel_nl) = rest.find('\n') { |
| 1522 | // Column offset on the current line. |
| 1523 | let line_start_byte = text[..cursor_byte].rfind('\n').map_or(0, |i| i + 1); |
| 1524 | let col = char_count(&text[line_start_byte..cursor_byte]); |
| 1525 | let next_line_start = cursor_byte + rel_nl + 1; |
| 1526 | let next_line = &text[next_line_start..]; |
| 1527 | let next_line_len = next_line.find('\n').unwrap_or(next_line.len()); |
| 1528 | let next_line_char_len = |
| 1529 | char_count(&text[next_line_start..next_line_start + next_line_len]); |
| 1530 | let target_col = col.min(next_line_char_len); |
| 1531 | self.cursor_position = |
| 1532 | floor_grapheme_boundary(&text, char_count(&text[..next_line_start]) + target_col); |
| 1533 | self.needs_redraw = true; |
| 1534 | } else { |
| 1535 | self.history_down(); |
| 1536 | } |
| 1537 | } |
| 1538 | |
| 1539 | /// Move the cursor up one logical line within the buffer (vim `k`). |
| 1540 | /// Falls back to history-up when already on the first line. |
| 1541 | pub fn vim_move_up(&mut self) { |
| 1542 | let text = self.input.clone(); |
| 1543 | let cursor_byte = byte_index_at_char(&text, self.cursor_position); |
| 1544 | if let Some(prev_nl) = text[..cursor_byte].rfind('\n') { |
| 1545 | // Column on the current line. |
| 1546 | let line_start_byte = prev_nl + 1; |
| 1547 | let col = char_count(&text[line_start_byte..cursor_byte]); |
| 1548 | // Find start of the previous line. |
| 1549 | let prev_line_end = prev_nl; // byte of the newline itself |
| 1550 | let prev_start = text[..prev_line_end].rfind('\n').map_or(0, |i| i + 1); |
| 1551 | let prev_line_len = char_count(&text[prev_start..prev_line_end]); |
| 1552 | let target_col = col.min(prev_line_len); |
| 1553 | self.cursor_position = |
| 1554 | floor_grapheme_boundary(&text, char_count(&text[..prev_start]) + target_col); |
| 1555 | self.needs_redraw = true; |
| 1556 | } else { |
| 1557 | self.history_up(); |
| 1558 | } |
| 1559 | } |
| 1560 | |
| 1561 | pub fn clear_input(&mut self) { |
| 1562 | self.clear_input_history_navigation(); |
| 1563 | self.input.clear(); |
| 1564 | self.resync_command_line_claim(); |
| 1565 | self.cursor_position = 0; |
| 1566 | // Prevent stale oversized-paste state from leaking when the user |
| 1567 | // clears the composer or navigates to a different input (#3263). |
| 1568 | self.pending_paste_reference = None; |
| 1569 | self.oversized_paste_full_text = None; |
| 1570 | self.selection_anchor = None; |
| 1571 | self.selected_attachment_index = None; |
| 1572 | self.slash_menu_selected = 0; |
| 1573 | self.slash_menu_hidden = false; |
| 1574 | self.paste_burst.clear_after_explicit_paste(); |
| 1575 | self.needs_redraw = true; |
| 1576 | } |
| 1577 | |
| 1578 | pub fn clear_input_recoverable(&mut self) { |
| 1579 | self.stash_current_input_for_recovery(); |
| 1580 | self.clear_input(); |
| 1581 | } |
| 1582 | |
| 1583 | pub fn clear_composer_draft(&mut self) { |
| 1584 | self.backtrack.reset(); |
| 1585 | self.disarm_quit(); |
| 1586 | self.edit_in_progress = false; |
| 1587 | self.clear_input_recoverable(); |
| 1588 | let _ = self.maybe_show_behavioral_tip( |
| 1589 | crate::tui::behavioral_tips::BehavioralTip::ClearedInputRestore, |
| 1590 | ); |
| 1591 | } |
| 1592 | |
| 1593 | pub fn start_history_search(&mut self) { |
| 1594 | if self.composer_history_search.is_some() { |
| 1595 | return; |
| 1596 | } |
| 1597 | // Expand any truncated paste first so the history search seed |
| 1598 | // contains the full text, not the truncated preview (#3263). |
| 1599 | self.auto_expand_oversized_paste(); |
| 1600 | self.composer_history_search = Some(ComposerHistorySearch::new( |
| 1601 | self.input.clone(), |
| 1602 | self.cursor_position, |
| 1603 | )); |
| 1604 | self.slash_menu_hidden = true; |
| 1605 | self.mention_menu_hidden = true; |
| 1606 | self.paste_burst.clear_after_explicit_paste(); |
| 1607 | self.show_input_hint("History search: type to filter, Enter accepts"); |
| 1608 | self.needs_redraw = true; |
| 1609 | } |
| 1610 | |
| 1611 | pub fn history_search_insert_char(&mut self, ch: char) { |
| 1612 | if let Some(search) = self.composer_history_search.as_mut() { |
| 1613 | search.query.push(ch); |
| 1614 | search.selected = 0; |
| 1615 | self.show_input_hint("History search: Enter accepts, Esc restores"); |
| 1616 | self.needs_redraw = true; |
| 1617 | } |
| 1618 | } |
| 1619 | |
| 1620 | pub fn history_search_insert_str(&mut self, text: &str) { |
| 1621 | if text.is_empty() { |
| 1622 | return; |
| 1623 | } |
| 1624 | if let Some(search) = self.composer_history_search.as_mut() { |
| 1625 | search.query.push_str(&normalize_paste_text(text)); |
| 1626 | search.selected = 0; |
| 1627 | self.show_input_hint("History search: Enter accepts, Esc restores"); |
| 1628 | self.needs_redraw = true; |
| 1629 | } |
| 1630 | } |
| 1631 | |
| 1632 | pub fn history_search_backspace(&mut self) { |
| 1633 | if let Some(search) = self.composer_history_search.as_mut() { |
| 1634 | search.query.pop(); |
| 1635 | search.selected = 0; |
| 1636 | self.needs_redraw = true; |
| 1637 | } |
| 1638 | self.clamp_history_search_selection(); |
| 1639 | } |
| 1640 | |
| 1641 | pub fn history_search_select_previous(&mut self) { |
| 1642 | if let Some(search) = self.composer_history_search.as_mut() { |
| 1643 | search.selected = search.selected.saturating_sub(1); |
| 1644 | self.needs_redraw = true; |
| 1645 | } |
| 1646 | } |
| 1647 | |
| 1648 | pub fn history_search_select_next(&mut self) { |
| 1649 | let Some(search) = self.composer_history_search.as_ref() else { |
| 1650 | return; |
| 1651 | }; |
| 1652 | let query = search.query.clone(); |
| 1653 | let selected = search.selected; |
| 1654 | let match_count = self.history_search_matches_for_query(&query).len(); |
| 1655 | if let Some(search) = self.composer_history_search.as_mut() |
| 1656 | && match_count > 0 |
| 1657 | { |
| 1658 | search.selected = (selected + 1).min(match_count.saturating_sub(1)); |
| 1659 | self.needs_redraw = true; |
| 1660 | } |
| 1661 | } |
| 1662 | |
| 1663 | pub fn accept_history_search(&mut self) -> bool { |
| 1664 | let Some(search) = self.composer_history_search.take() else { |
| 1665 | return false; |
| 1666 | }; |
| 1667 | let matches = self.history_search_matches_for_query(&search.query); |
| 1668 | if let Some(selected) = matches |
| 1669 | .get(search.selected.min(matches.len().saturating_sub(1))) |
| 1670 | .cloned() |
| 1671 | { |
| 1672 | self.input = selected; |
| 1673 | self.resync_command_line_claim(); |
| 1674 | self.cursor_position = char_count(&self.input); |
| 1675 | self.history_index = None; |
| 1676 | self.show_input_hint("History match inserted into composer"); |
| 1677 | self.needs_redraw = true; |
| 1678 | true |
| 1679 | } else { |
| 1680 | self.composer_history_search = Some(search); |
| 1681 | self.show_input_hint("No history matches"); |
| 1682 | self.needs_redraw = true; |
| 1683 | false |
| 1684 | } |
| 1685 | } |
| 1686 | |
| 1687 | pub fn cancel_history_search(&mut self) { |
| 1688 | let Some(search) = self.composer_history_search.take() else { |
| 1689 | return; |
| 1690 | }; |
| 1691 | self.input = search.pre_search_input; |
| 1692 | self.resync_command_line_claim(); |
| 1693 | self.cursor_position = search.pre_search_cursor.min(char_count(&self.input)); |
| 1694 | self.show_input_feedback("History search canceled", StatusToastLevel::Warning, 5_000); |
| 1695 | self.needs_redraw = true; |
| 1696 | } |
| 1697 | |
| 1698 | /// Refuse a submit the shell cannot vouch for, leaving the text exactly |
| 1699 | /// where the user can see it (#5925). |
| 1700 | /// |
| 1701 | /// Never destructive: the composer keeps its content and the next Enter |
| 1702 | /// sends it. The hold exists so a line whose first bytes may be missing |
| 1703 | /// is read by a human before it is read by a model. |
| 1704 | fn hold_unproven_submit(&mut self, reason: &str) { |
| 1705 | self.push_status_toast(reason, StatusToastLevel::Warning, Some(8_000)); |
| 1706 | self.needs_redraw = true; |
| 1707 | } |
| 1708 | |
| 1709 | pub fn submit_input(&mut self) -> Option<String> { |
| 1710 | if self.input.trim().is_empty() { |
| 1711 | self.paste_burst.clear_after_explicit_paste(); |
| 1712 | return None; |
| 1713 | } |
| 1714 | // #5925: startup consumed bytes it could not replay, so this shell |
| 1715 | // cannot prove it saw the whole line. Keep the text in the composer |
| 1716 | // and let the user look at it rather than sending a line that may be |
| 1717 | // missing its first characters — a truncated `/command` submitted as |
| 1718 | // prose runs with the session's full authority. Cleared here, so the |
| 1719 | // deliberate second Enter sends exactly what is on screen. |
| 1720 | if self.startup_input_unproven { |
| 1721 | self.startup_input_unproven = false; |
| 1722 | self.hold_unproven_submit( |
| 1723 | "Check the line, then press Enter again to send it. \ |
| 1724 | Startup may have missed some characters.", |
| 1725 | ); |
| 1726 | return None; |
| 1727 | } |
| 1728 | // A line that began with `/` stays a command until Enter. If the |
| 1729 | // outgoing text is no longer a command — a submit-time rewrite, or |
| 1730 | // bytes lost after the composer accepted them — never fall through |
| 1731 | // to the prose-prompt branch; hold it instead. |
| 1732 | let claimed_command = self.command_line_claimed(); |
| 1733 | // A dropped image path that was not converted at paste time (typed |
| 1734 | // keys, or the question written on the same line) still attaches. |
| 1735 | if !claimed_command |
| 1736 | && !self.input.trim_start().starts_with('!') |
| 1737 | && let Some((path, rest)) = |
| 1738 | codewhale_engine::image_attach::leading_dropped_image(&self.input) |
| 1739 | { |
| 1740 | let reference = media_attachment_reference("image", &path, None); |
| 1741 | self.input = if rest.is_empty() { |
| 1742 | reference |
| 1743 | } else { |
| 1744 | format!("{reference}\n{rest}") |
| 1745 | }; |
| 1746 | self.cursor_position = char_count(&self.input); |
| 1747 | } |
| 1748 | // Safety net: if any earlier path filled the buffer above the |
| 1749 | // safety cap without going through `insert_paste_text`, fold it |
| 1750 | // into a workspace paste file now (#553). Bracketed pastes hit |
| 1751 | // the consolidation in `insert_paste_text` first, so the user |
| 1752 | // sees the @mention in the composer before submission. |
| 1753 | if !self.consolidate_large_input_if_oversized() { |
| 1754 | // The paste file could not be written. Never send a silently |
| 1755 | // truncated prompt: the full text stays in the composer and the |
| 1756 | // error explains why Enter did nothing. |
| 1757 | return None; |
| 1758 | } |
| 1759 | // If consolidation created a paste file, submit only the @-mention so |
| 1760 | // the model reads the full content from the paste file. Sending both |
| 1761 | // the inline text and the file mention duplicates the content in the |
| 1762 | // request and confuses the model. |
| 1763 | let mut input = self.input.clone(); |
| 1764 | if let Some(reference) = self.pending_paste_reference.take() { |
| 1765 | // Drop the oversized inline copy; the paste file is now the |
| 1766 | // single source of truth for this content. The submitted text |
| 1767 | // keeps the @-mention (mention resolution attaches the file for |
| 1768 | // the model) but wraps it in a human-readable attachment card |
| 1769 | // with size and a bounded preview, so the transcript row can |
| 1770 | // never render as a mysterious bare filesystem path (#553 |
| 1771 | // follow-up: "a path is not a message"). |
| 1772 | let full = self.oversized_paste_full_text.take(); |
| 1773 | input = match full { |
| 1774 | Some(full) => paste_attachment_display(&reference, &full), |
| 1775 | None => reference, |
| 1776 | }; |
| 1777 | } else if let Some(full) = self.oversized_paste_full_text.take() { |
| 1778 | input = full; |
| 1779 | } |
| 1780 | if claimed_command && !looks_like_slash_command_input(&input) { |
| 1781 | // The line was a command when the composer accepted it and is |
| 1782 | // not one now. Something rewrote it between Enter and dispatch; |
| 1783 | // the one thing that must never happen is sending it to the |
| 1784 | // model as prose (#5925). Put the text back and say so. |
| 1785 | tracing::warn!( |
| 1786 | target: "startup_input", |
| 1787 | submitted = %input, |
| 1788 | "a command line stopped looking like a command before dispatch; holding it in the composer" |
| 1789 | ); |
| 1790 | self.input = input; |
| 1791 | self.cursor_position = char_count(&self.input); |
| 1792 | self.line_began_with_slash = false; |
| 1793 | self.hold_unproven_submit( |
| 1794 | "That line started as a command but no longer reads as one. \ |
| 1795 | Check it and press Enter again to send it as shown.", |
| 1796 | ); |
| 1797 | return None; |
| 1798 | } |
| 1799 | crate::composer_history::push_history_entry(&mut self.input_history, &input); |
| 1800 | if self.max_input_history == 0 { |
| 1801 | self.input_history.clear(); |
| 1802 | } else if self.input_history.len() > self.max_input_history { |
| 1803 | let excess = self.input_history.len() - self.max_input_history; |
| 1804 | self.input_history.drain(0..excess); |
| 1805 | } |
| 1806 | // Mirror prompts and commands to the persisted cross-session history |
| 1807 | // so arrow-up recall works across restarts (#366, #6006). A history |
| 1808 | // limit of zero saves nothing (U01-m2). |
| 1809 | if self.max_input_history > 0 { |
| 1810 | crate::composer_history::append_history(&input); |
| 1811 | } |
| 1812 | self.history_index = None; |
| 1813 | self.history_navigation_draft = None; |
| 1814 | self.clear_input(); |
| 1815 | // Collapse recent-only Work chrome on the next accepted turn (#4688). |
| 1816 | self.work_surface.note_user_turn_or_new_operation(); |
| 1817 | Some(input) |
| 1818 | } |
| 1819 | |
| 1820 | /// Restore unsent user input to the composer; keep command-generated prompts |
| 1821 | /// as receipts that require invoking their original command again. |
| 1822 | pub fn restore_unsent_message(&mut self, message: QueuedMessage) { |
| 1823 | if let Some((command, _)) = message.extension_command.as_ref() { |
| 1824 | self.add_message(crate::tui::history::HistoryCell::System { |
| 1825 | content: format!( |
| 1826 | "{} command prompt was not submitted. Run the command again to retry.\n{}", |
| 1827 | command.origin, message.display |
| 1828 | ), |
| 1829 | }); |
| 1830 | self.needs_redraw = true; |
| 1831 | return; |
| 1832 | } |
| 1833 | self.stash_typed_draft_before_restore(); |
| 1834 | self.input = message.display; |
| 1835 | self.resync_command_line_claim(); |
| 1836 | self.cursor_position = char_count(&self.input); |
| 1837 | self.history_index = None; |
| 1838 | self.history_navigation_draft = None; |
| 1839 | self.selected_attachment_index = None; |
| 1840 | self.active_skill = message.skill_instruction; |
| 1841 | self.active_skill_provenance = message.skill_provenance; |
| 1842 | self.needs_redraw = true; |
| 1843 | } |
| 1844 | |
| 1845 | pub fn restore_last_submitted_prompt_if_empty(&mut self) -> bool { |
| 1846 | if !self.input.is_empty() { |
| 1847 | return false; |
| 1848 | } |
| 1849 | let Some(prompt) = self |
| 1850 | .last_submitted_prompt |
| 1851 | .as_deref() |
| 1852 | .filter(|prompt| !prompt.is_empty()) |
| 1853 | else { |
| 1854 | return false; |
| 1855 | }; |
| 1856 | |
| 1857 | self.input = prompt.to_string(); |
| 1858 | self.resync_command_line_claim(); |
| 1859 | self.cursor_position = char_count(&self.input); |
| 1860 | self.history_index = None; |
| 1861 | self.history_navigation_draft = None; |
| 1862 | self.selected_attachment_index = None; |
| 1863 | self.needs_redraw = true; |
| 1864 | true |
| 1865 | } |
| 1866 | |
| 1867 | /// Replace the composer buffer with externally edited text. Recalled |
| 1868 | /// history, selection, and attachment positions belong to the old text: |
| 1869 | /// a stale `history_index` would let the next Up/Down silently discard |
| 1870 | /// the edited buffer. |
| 1871 | pub fn apply_external_edit(&mut self, new: String) { |
| 1872 | self.input = new; |
| 1873 | self.resync_command_line_claim(); |
| 1874 | self.pending_paste_reference = None; |
| 1875 | self.oversized_paste_full_text = None; |
| 1876 | self.cursor_position = char_count(&self.input); |
| 1877 | self.history_index = None; |
| 1878 | self.history_navigation_draft = None; |
| 1879 | self.selection_anchor = None; |
| 1880 | self.selected_attachment_index = None; |
| 1881 | self.needs_redraw = true; |
| 1882 | } |
| 1883 | |
| 1884 | /// Restore the last cleared input if the composer is empty. |
| 1885 | /// Returns `true` if the input was restored. |
| 1886 | pub fn restore_last_cleared_input_if_empty(&mut self) -> bool { |
| 1887 | if !self.input.is_empty() { |
| 1888 | return false; |
| 1889 | } |
| 1890 | let Some(saved) = self.clear_undo_buffer.take().filter(|s| !s.is_empty()) else { |
| 1891 | return false; |
| 1892 | }; |
| 1893 | |
| 1894 | self.input = saved; |
| 1895 | self.resync_command_line_claim(); |
| 1896 | self.cursor_position = char_count(&self.input); |
| 1897 | self.history_index = None; |
| 1898 | self.history_navigation_draft = None; |
| 1899 | self.selected_attachment_index = None; |
| 1900 | self.slash_menu_selected = 0; |
| 1901 | self.slash_menu_hidden = false; |
| 1902 | self.needs_redraw = true; |
| 1903 | self.clear_undo_buffer = None; |
| 1904 | true |
| 1905 | } |
| 1906 | |
| 1907 | /// Composer dispatch with paste protection for bare Enter. Returns `Some(input)` when the press should |
| 1908 | /// fire a submit; `None` when Enter was absorbed (paste-burst Enter |
| 1909 | /// suppression — see #1073). |
| 1910 | /// |
| 1911 | /// Two suppression cases are handled here. Both are silent: nothing |
| 1912 | /// visible happens beyond the text gaining a newline. |
| 1913 | /// |
| 1914 | /// 1. **Burst active.** A paste burst is currently being assembled in |
| 1915 | /// `paste_burst.buffer`. The Enter is part of the paste content; |
| 1916 | /// append `\n` to the buffer so the next flush includes it, do not |
| 1917 | /// submit, and extend the suppression window so a follow-on Enter |
| 1918 | /// (i.e. the *next* line of a multi-line paste) is also absorbed. |
| 1919 | /// 2. **Window open after flush.** A burst just flushed into |
| 1920 | /// `self.input`, but the suppression window is still alive. The |
| 1921 | /// Enter is probably the trailing newline of that paste, not a submit |
| 1922 | /// gesture by the user, so insert `\n` directly into the composer |
| 1923 | /// text. The window is deliberately *not* re-armed here: no burst is |
| 1924 | /// being assembled, so this Enter is only a guess, and re-arming on a |
| 1925 | /// guess meant every absorbed Enter bought another 120ms — a user |
| 1926 | /// pressing Enter to send just kept adding newlines and never |
| 1927 | /// submitted. Suppression now always ends 120ms after the last real |
| 1928 | /// keystroke. |
| 1929 | /// |
| 1930 | /// Outside both cases the call falls through to [`Self::submit_input`] |
| 1931 | /// unchanged so normal Enter-to-send behaviour is preserved. |
| 1932 | /// |
| 1933 | /// `now` must be the Enter event's observed timestamp, not a fresh |
| 1934 | /// `Instant::now()`: `PasteBurst` records char times in event-observed |
| 1935 | /// time, so a processing-time probe measures staleness as arrival gap |
| 1936 | /// *plus* whatever input backlog the loop is carrying. On a loaded |
| 1937 | /// runner that lag alone can exceed the stream window mid-paste, which |
| 1938 | /// turns a pasted newline into a submit — the failure the real |
| 1939 | /// Windows Terminal clipboard harness showed (24 lines joined, or a |
| 1940 | /// mid-paste modal eating the next lines). |
| 1941 | pub fn handle_composer_enter(&mut self, protect_paste: bool, now: Instant) -> Option<String> { |
| 1942 | if protect_paste |
| 1943 | && self.use_paste_burst_detection |
| 1944 | && self |
| 1945 | .paste_burst |
| 1946 | .newline_should_insert_instead_of_submit(now) |
| 1947 | { |
| 1948 | if !self.paste_burst.append_newline_if_active(now) { |
| 1949 | self.insert_char('\n'); |
| 1950 | } |
| 1951 | self.needs_redraw = true; |
| 1952 | return None; |
| 1953 | } |
| 1954 | self.submit_input() |
| 1955 | } |
| 1956 | |
| 1957 | /// Non-destructive twin of [`Self::handle_composer_enter`] for callers |
| 1958 | /// that must commit other state before the composer may be consumed: |
| 1959 | /// the startup composer begins the launch session before it consumes |
| 1960 | /// its draft, so it probes first and never begins a session for an |
| 1961 | /// Enter the paste-burst window is about to absorb. Reads the exact |
| 1962 | /// same two predicates `handle_composer_enter` acts on — the burst |
| 1963 | /// window and the trimmed-empty buffer — without mutating anything. |
| 1964 | #[must_use] |
| 1965 | pub fn composer_enter_would_submit(&self, protect_paste: bool, now: Instant) -> bool { |
| 1966 | if protect_paste |
| 1967 | && self.use_paste_burst_detection |
| 1968 | && self |
| 1969 | .paste_burst |
| 1970 | .newline_should_insert_instead_of_submit(now) |
| 1971 | { |
| 1972 | return false; |
| 1973 | } |
| 1974 | !self.input.trim().is_empty() |
| 1975 | } |
| 1976 | |
| 1977 | /// Whether the *draft* is in a submittable state, for display only. |
| 1978 | /// |
| 1979 | /// Deliberately time-independent. [`Self::composer_enter_would_submit`] |
| 1980 | /// additionally consults the paste-burst heuristic, whose suppression |
| 1981 | /// window is re-extended on every fast keystroke -- correct for deciding |
| 1982 | /// what a newline does mid-paste, wrong for a persistent affordance. |
| 1983 | /// Driving the `[↵]` chip from it made the chip strobe `[↵]`/`[·]` for as |
| 1984 | /// long as the user kept typing, because the window kept reopening |
| 1985 | /// (#6397). Enter routing, mouse submit and hover registration stay on |
| 1986 | /// the timing predicate. |
| 1987 | #[must_use] |
| 1988 | pub fn composer_draft_is_submittable(&self) -> bool { |
| 1989 | !self.input.trim().is_empty() |
| 1990 | } |
| 1991 | |
| 1992 | pub(crate) fn composer_shows_send(&self) -> bool { |
| 1993 | self.composer_draft_is_submittable() |
| 1994 | || self.decide_composer_submit(ComposerSubmitChord::Enter) |
| 1995 | == ComposerSubmitAction::SendQueuedNow |
| 1996 | } |
| 1997 | |
| 1998 | /// Public wrapper around [`Self::consolidate_large_input`] that no-ops |
| 1999 | /// when the current input fits inside the safety cap. Both the paste- |
| 2000 | /// insert path (visible-before-submit) and the submit-time safety net |
| 2001 | /// route through here, so the cap is enforced exactly once even when |
| 2002 | /// both paths fire on the same buffer. |
| 2003 | /// |
| 2004 | /// Returns `false` when the input is oversized and could not be backed |
| 2005 | /// up to a paste file; the composer then still holds the full text. |
| 2006 | pub(crate) fn consolidate_large_input_if_oversized(&mut self) -> bool { |
| 2007 | if char_count(&self.input) > MAX_SUBMITTED_INPUT_CHARS { |
| 2008 | return self.consolidate_large_input(); |
| 2009 | } |
| 2010 | true |
| 2011 | } |
| 2012 | |
| 2013 | /// When the composer input exceeds [`MAX_SUBMITTED_INPUT_CHARS`], write |
| 2014 | /// the full content to a timestamped paste file under |
| 2015 | /// `.codewhale/pastes/` and replace `self.input` with an `@`-mention |
| 2016 | /// pointing at it so the model can read the full content via the |
| 2017 | /// normal file-mention resolution path (#553). |
| 2018 | /// |
| 2019 | /// Returns `false` without touching the composer when the paste file |
| 2020 | /// cannot be written, so the caller holds the submit instead of sending |
| 2021 | /// a truncated prompt. |
| 2022 | fn consolidate_large_input(&mut self) -> bool { |
| 2023 | let now = chrono::Local::now(); |
| 2024 | let suffix = uuid::Uuid::new_v4().to_string()[..8].to_string(); |
| 2025 | let filename = format!("paste-{}-{}.md", now.format("%Y-%m-%d-%H%M%S"), suffix); |
| 2026 | let rel_path = format!(".codewhale/pastes/{filename}"); |
| 2027 | |
| 2028 | // Confined to the workspace: a linked `.codewhale` or `pastes` |
| 2029 | // directory must not send the pasted text somewhere else. |
| 2030 | let file_path = self.workspace.join(&rel_path); |
| 2031 | let written = |
| 2032 | codewhale_util::fs_confined::write(&self.workspace, &file_path, self.input.as_bytes()); |
| 2033 | if let Err(error) = written { |
| 2034 | let limit = MAX_SUBMITTED_INPUT_CHARS.to_string(); |
| 2035 | // The toast row sheds clauses to fit and left only "Not sent", so |
| 2036 | // the toast carries a short form and the full reason, including |
| 2037 | // the write error, goes to the transcript where nothing is clipped. |
| 2038 | let short = self |
| 2039 | .tr(MessageId::ComposerOversizedSubmitHeldShort) |
| 2040 | .replace("{limit}", &limit); |
| 2041 | let reason = self |
| 2042 | .tr(MessageId::ComposerOversizedSubmitHeld) |
| 2043 | .replace("{limit}", &limit) |
| 2044 | .replace("{error}", &error.to_string()); |
| 2045 | self.push_status_toast(short, StatusToastLevel::Error, Some(8_000)); |
| 2046 | // Enter and paste both retry this; do not stack identical cells. |
| 2047 | let already_noted = matches!( |
| 2048 | self.history.last(), |
| 2049 | Some(HistoryCell::System { content }) if *content == reason |
| 2050 | ); |
| 2051 | if !already_noted { |
| 2052 | self.add_message(HistoryCell::System { content: reason }); |
| 2053 | } |
| 2054 | self.needs_redraw = true; |
| 2055 | return false; |
| 2056 | } |
| 2057 | let full_input = std::mem::take(&mut self.input); |
| 2058 | |
| 2059 | // Keep a truncated preview in the composer so the user can still |
| 2060 | // select, copy, and edit it. The full text is written to the paste |
| 2061 | // file; at submit time the inline text is replaced by the @mention |
| 2062 | // so the model reads the file instead of receiving the content twice. |
| 2063 | self.pending_paste_reference = Some(format!("@{rel_path}")); |
| 2064 | self.oversized_paste_full_text = Some(full_input.clone()); |
| 2065 | let display_chars = char_count(&full_input).min(MAX_COMPOSER_DISPLAY_CHARS); |
| 2066 | let mut truncated: String = full_input.chars().take(display_chars).collect(); |
| 2067 | if char_count(&full_input) > MAX_COMPOSER_DISPLAY_CHARS { |
| 2068 | truncated.push_str("\n\n---\n(content truncated for display — start typing to expand; full text sent to model)"); |
| 2069 | } |
| 2070 | self.input = truncated; |
| 2071 | self.resync_command_line_claim(); |
| 2072 | self.cursor_position = 0; |
| 2073 | self.push_status_toast( |
| 2074 | "Large paste backed up to file — the model will receive the full content.", |
| 2075 | StatusToastLevel::Info, |
| 2076 | Some(5_000), |
| 2077 | ); |
| 2078 | true |
| 2079 | } |
| 2080 | |
| 2081 | pub fn history_down(&mut self) { |
| 2082 | if self.input_history.is_empty() { |
| 2083 | return; |
| 2084 | } |
| 2085 | match self.history_index { |
| 2086 | None => {} |
| 2087 | Some(i) => { |
| 2088 | if i + 1 < self.input_history.len() { |
| 2089 | self.history_index = Some(i + 1); |
| 2090 | self.input = self.input_history[i + 1].clone(); |
| 2091 | self.resync_command_line_claim(); |
| 2092 | self.cursor_position = char_count(&self.input); |
| 2093 | self.selection_anchor = None; |
| 2094 | self.selected_attachment_index = None; |
| 2095 | self.slash_menu_hidden = false; |
| 2096 | self.paste_burst.clear_after_explicit_paste(); |
| 2097 | } else { |
| 2098 | self.history_index = None; |
| 2099 | if let Some(draft) = self.history_navigation_draft.take() { |
| 2100 | self.input = draft.input; |
| 2101 | self.resync_command_line_claim(); |
| 2102 | self.cursor_position = draft.cursor.min(char_count(&self.input)); |
| 2103 | self.selection_anchor = None; |
| 2104 | self.selected_attachment_index = None; |
| 2105 | self.slash_menu_hidden = false; |
| 2106 | self.paste_burst.clear_after_explicit_paste(); |
| 2107 | self.needs_redraw = true; |
| 2108 | } else { |
| 2109 | self.clear_input(); |
| 2110 | } |
| 2111 | } |
| 2112 | } |
| 2113 | } |
| 2114 | } |
| 2115 | } |
| 2116 |