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