返回 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 /// Maximum characters displayed in the composer for oversized input.
448 /// Beyond this, the text is truncated for rendering but the full content
449 /// is preserved for model submission (#3263).
450 const MAX_COMPOSER_DISPLAY_CHARS: usize = 4_000;
451 const MAX_DRAFT_HISTORY: usize = 50;
452
453 impl ComposerState {
454 pub fn cursor_byte_index(&self) -> usize {
455 byte_index_at_char(&self.input, self.cursor_position)
456 }
457
458 /// When the user starts editing a truncated oversized paste, restore the
459 /// full text so they can see and edit the complete content (#3263).
460 fn auto_expand_oversized_paste(&mut self) {
461 if let Some(full) = self.oversized_paste_full_text.take() {
462 self.input = full;
463 // Clamp cursor to the new length instead of resetting to 0,
464 // so the user's position in the truncated preview is preserved.
465 self.cursor_position = self.cursor_position.min(char_count(&self.input));
466 }
467 }
468
469 pub fn composer_attachment_count(&self) -> usize {
470 crate::tui::file_mention::media_attachment_references(&self.input).len()
471 }
472
473 pub fn selected_composer_attachment_index(&self) -> Option<usize> {
474 let count = self.composer_attachment_count();
475 self.selected_attachment_index
476 .filter(|index| *index < count)
477 }
478
479 fn strip_raw_mouse_reports_from_input(&mut self) {
480 if let Some((input, cursor_position)) =
481 strip_raw_mouse_report_runs(&self.input, self.cursor_position)
482 {
483 self.input = input;
484 self.cursor_position = cursor_position;
485 }
486 }
487
488 // === Selection helpers ===
489 /// Return the (start, end) of the active selection, or `None`.
490 /// `start` is inclusive, `end` is exclusive; both are char indices.
491 pub fn selection_range(&self) -> Option<(usize, usize)> {
492 let total = char_count(&self.input);
493 let anchor = self.selection_anchor?.min(total);
494 let cursor = self.cursor_position.min(total);
495 if anchor == cursor {
496 return None;
497 }
498 Some(if anchor < cursor {
499 (anchor, cursor)
500 } else {
501 (cursor, anchor)
502 })
503 }
504
505 /// Return the selected text, or empty string if no selection.
506 pub fn selected_text(&self) -> String {
507 self.selection_range()
508 .map(|(s, e)| {
509 let sb = byte_index_at_char(&self.input, s);
510 let eb = byte_index_at_char(&self.input, e);
511 self.input[sb..eb].to_string()
512 })
513 .unwrap_or_default()
514 }
515
516 /// Clear the selection without moving the cursor.
517 pub fn clear_selection(&mut self) {
518 self.selection_anchor = None;
519 }
520
521 /// Returns `true` when vim mode is active and the composer is in Normal
522 /// mode, which means character keys should NOT be inserted as text.
523 #[must_use]
524 pub fn vim_is_normal_mode(&self) -> bool {
525 self.vim_enabled && self.vim_mode == VimMode::Normal
526 }
527
528 /// Returns `true` when vim mode is active and the composer is in Visual mode.
529 #[must_use]
530 pub fn vim_is_visual_mode(&self) -> bool {
531 self.vim_enabled && self.vim_mode == VimMode::Visual
532 }
533
534 pub fn stash_current_input_for_recovery(&mut self) {
535 // Before stashing, expand any truncated paste so the saved draft
536 // contains the full text, not the truncated preview (#3263).
537 self.auto_expand_oversized_paste();
538 let draft = self.input.clone();
539 if draft.trim().is_empty() {
540 self.clear_undo_buffer = None;
541 return;
542 }
543 self.clear_undo_buffer = Some(draft.clone());
544 self.remember_draft_for_recovery(draft);
545 }
546
547 fn remember_draft_for_recovery(&mut self, draft: String) {
548 if draft.trim().is_empty() {
549 return;
550 }
551 self.draft_history.retain(|existing| existing != &draft);
552 self.draft_history.push_back(draft);
553 while self.draft_history.len() > MAX_DRAFT_HISTORY {
554 let _ = self.draft_history.pop_front();
555 }
556 }
557
558 pub fn is_history_search_active(&self) -> bool {
559 self.composer_history_search.is_some()
560 }
561
562 pub fn history_search_query(&self) -> Option<&str> {
563 self.composer_history_search
564 .as_ref()
565 .map(|search| search.query.as_str())
566 }
567
568 pub fn history_search_selected_index(&self) -> usize {
569 self.composer_history_search
570 .as_ref()
571 .map_or(0, |search| search.selected)
572 }
573
574 pub fn composer_display_input(&self) -> &str {
575 self.history_search_query().unwrap_or(&self.input)
576 }
577
578 pub fn composer_display_cursor(&self) -> usize {
579 self.composer_history_search
580 .as_ref()
581 .map_or(self.cursor_position, |search| char_count(&search.query))
582 }
583
584 pub fn history_search_matches(&self) -> Vec<String> {
585 let Some(query) = self.history_search_query() else {
586 return Vec::new();
587 };
588 self.history_search_matches_for_query(query)
589 }
590
591 fn history_search_matches_for_query(&self, query: &str) -> Vec<String> {
592 let normalized_query = query.trim().to_lowercase();
593 let mut seen: HashSet<&str> = HashSet::new();
594 let mut matches = Vec::new();
595
596 for candidate in self
597 .draft_history
598 .iter()
599 .rev()
600 .chain(self.input_history.iter().rev())
601 {
602 if candidate.trim().is_empty() || !seen.insert(candidate.as_str()) {
603 continue;
604 }
605 if normalized_query.is_empty() || candidate.to_lowercase().contains(&normalized_query) {
606 matches.push(candidate.clone());
607 }
608 }
609
610 matches
611 }
612
613 fn clamp_history_search_selection(&mut self) {
614 let Some(search) = self.composer_history_search.as_ref() else {
615 return;
616 };
617 let selected = search.selected;
618 let query = search.query.clone();
619 let match_count = self.history_search_matches_for_query(&query).len();
620 if let Some(search) = self.composer_history_search.as_mut() {
621 search.selected = if match_count == 0 {
622 0
623 } else {
624 selected.min(match_count.saturating_sub(1))
625 };
626 }
627 }
628
629 pub fn history_up(&mut self) {
630 if self.input_history.is_empty() {
631 return;
632 }
633 if self.history_index.is_none() {
634 // Expand truncated paste first so the saved draft contains the
635 // full text instead of the truncated preview (#3263).
636 self.auto_expand_oversized_paste();
637 self.history_navigation_draft = Some(InputHistoryDraft {
638 input: self.input.clone(),
639 cursor: self.cursor_position,
640 });
641 }
642 let new_index = match self.history_index {
643 None => self.input_history.len().saturating_sub(1),
644 Some(i) => i.saturating_sub(1),
645 };
646 self.history_index = Some(new_index);
647 self.input = self.input_history[new_index].clone();
648 self.cursor_position = char_count(&self.input);
649 self.selection_anchor = None;
650 self.selected_attachment_index = None;
651 self.slash_menu_hidden = false;
652 self.paste_burst.clear_after_explicit_paste();
653 }
654
655 fn clear_input_history_navigation(&mut self) {
656 self.history_index = None;
657 self.history_navigation_draft = None;
658 }
659 }
660
661 impl App {
662 pub fn insert_str(&mut self, text: &str) {
663 if text.is_empty() {
664 return;
665 }
666 self.auto_expand_oversized_paste();
667 self.delete_selection();
668 self.selected_attachment_index = None;
669 let cursor = self.cursor_position.min(char_count(&self.input));
670 let byte_index = byte_index_at_char(&self.input, cursor);
671 self.input.insert_str(byte_index, text);
672 self.cursor_position = cursor + char_count(text);
673 self.strip_raw_mouse_reports_from_input();
674 self.slash_menu_hidden = false;
675 self.mention_menu_hidden = false;
676 self.mention_menu_selected = 0;
677 self.needs_redraw = true;
678 }
679
680 pub fn insert_paste_text(&mut self, text: &str) {
681 if let Some(pending) = self.paste_burst.flush_before_modified_input() {
682 self.insert_str(&pending);
683 }
684 let normalized = normalize_paste_text(text);
685 if !normalized.is_empty() {
686 self.insert_str(&normalized);
687 }
688 self.paste_burst.clear_after_explicit_paste();
689 // Large pasted input stays editable and visible until submit. The
690 // submit-time safety net consolidates oversized composer content into
691 // an @paste-...md mention before dispatch, so no path silently
692 // truncates user input.
693 // self.consolidate_large_input_if_oversized(); // deferred to submit time
694 }
695
696 pub fn insert_media_attachment(&mut self, kind: &str, path: &Path, description: Option<&str>) {
697 let reference = media_attachment_reference(kind, path, description);
698 let cursor = self.cursor_position.min(char_count(&self.input));
699 let byte_index = byte_index_at_char(&self.input, cursor);
700 let needs_prefix_newline = self.input[..byte_index]
701 .chars()
702 .last()
703 .is_some_and(|ch| !ch.is_whitespace());
704 let needs_suffix_newline = self.input[byte_index..]
705 .chars()
706 .next()
707 .is_some_and(|ch| !ch.is_whitespace());
708
709 let mut inserted = String::new();
710 if needs_prefix_newline {
711 inserted.push('\n');
712 }
713 inserted.push_str(&reference);
714 if needs_suffix_newline || self.input[byte_index..].is_empty() {
715 inserted.push('\n');
716 }
717 self.insert_str(&inserted);
718 self.paste_burst.clear_after_explicit_paste();
719 }
720
721 pub fn select_previous_composer_attachment(&mut self) -> bool {
722 let count = self.composer_attachment_count();
723 if count == 0 {
724 self.selected_attachment_index = None;
725 return false;
726 }
727
728 let next = self
729 .selected_composer_attachment_index()
730 .map_or(count.saturating_sub(1), |index| index.saturating_sub(1));
731 self.selected_attachment_index = Some(next);
732 self.cursor_position = 0;
733 self.status_message = Some("Attachment selected - Backspace/Delete removes it".to_string());
734 self.needs_redraw = true;
735 true
736 }
737
738 pub fn select_next_composer_attachment(&mut self) -> bool {
739 let count = self.composer_attachment_count();
740 let Some(index) = self.selected_composer_attachment_index() else {
741 return false;
742 };
743 if index + 1 < count {
744 self.selected_attachment_index = Some(index + 1);
745 self.status_message =
746 Some("Attachment selected - Backspace/Delete removes it".to_string());
747 } else {
748 self.selected_attachment_index = None;
749 self.status_message = Some("Composer focused".to_string());
750 }
751 self.needs_redraw = true;
752 true
753 }
754
755 pub fn clear_composer_attachment_selection(&mut self) -> bool {
756 if self.selected_attachment_index.take().is_some() {
757 self.status_message = Some("Composer focused".to_string());
758 self.needs_redraw = true;
759 true
760 } else {
761 false
762 }
763 }
764
765 pub fn remove_selected_composer_attachment(&mut self) -> bool {
766 let references = crate::tui::file_mention::media_attachment_references(&self.input);
767 let Some(index) = self
768 .selected_composer_attachment_index()
769 .filter(|index| *index < references.len())
770 else {
771 self.selected_attachment_index = None;
772 return false;
773 };
774 let reference = references[index].clone();
775 let cursor_byte = byte_index_at_char(&self.input, self.cursor_position);
776 let new_cursor_byte = if cursor_byte <= reference.start_byte {
777 cursor_byte
778 } else if cursor_byte >= reference.end_byte {
779 cursor_byte.saturating_sub(reference.end_byte - reference.start_byte)
780 } else {
781 reference.start_byte
782 };
783
784 self.input
785 .replace_range(reference.start_byte..reference.end_byte, "");
786 self.cursor_position = self.input[..new_cursor_byte.min(self.input.len())]
787 .chars()
788 .count();
789 let remaining = self.composer_attachment_count();
790 self.selected_attachment_index = if remaining == 0 {
791 None
792 } else {
793 Some(index.min(remaining.saturating_sub(1)))
794 };
795 self.slash_menu_hidden = false;
796 self.mention_menu_hidden = false;
797 self.mention_menu_selected = 0;
798 self.status_message = Some(format!("Removed attachment: {}", reference.path));
799 self.needs_redraw = true;
800 true
801 }
802
803 pub fn flush_paste_burst_if_due(&mut self, now: Instant) -> bool {
804 match self.paste_burst.flush_if_due(now) {
805 FlushResult::Paste(text) => {
806 self.insert_str(&text);
807 true
808 }
809 FlushResult::Typed(ch) => {
810 self.insert_char(ch);
811 true
812 }
813 FlushResult::None => false,
814 }
815 }
816
817 pub fn flush_paste_burst_if_enabled(&mut self, now: Instant) -> bool {
818 self.use_paste_burst_detection && self.flush_paste_burst_if_due(now)
819 }
820
821 pub fn paste_burst_next_flush_delay_if_enabled(&self, now: Instant) -> Option<Duration> {
822 if self.use_paste_burst_detection {
823 self.paste_burst.next_flush_delay(now)
824 } else {
825 None
826 }
827 }
828
829 pub fn flush_paste_burst_before_modified_input_if_enabled(&mut self) -> Option<String> {
830 if self.use_paste_burst_detection {
831 self.paste_burst.flush_before_modified_input()
832 } else {
833 None
834 }
835 }
836
837 /// Paste from clipboard into input.
838 ///
839 /// Returns whether content was inserted. In SSH sessions without a
840 /// forwarded graphical display, the terminal client owns paste, so direct
841 /// clipboard shortcuts surface the local terminal-paste instruction while
842 /// `Event::Paste` remains the data path.
843 pub fn paste_from_clipboard(&mut self) -> bool {
844 if self.clipboard.requires_terminal_paste() {
845 self.status_message = Some(self.tr(MessageId::ClipboardSshPasteHint).into_owned());
846 return false;
847 }
848 if let Some(content) = self.clipboard.read(self.workspace.as_path()) {
849 self.apply_clipboard_content(content);
850 return true;
851 }
852 false
853 }
854
855 pub fn apply_clipboard_content(&mut self, content: ClipboardContent) {
856 match content {
857 ClipboardContent::Text(text) => {
858 self.insert_paste_text(&text);
859 }
860 ClipboardContent::Image(pasted) => {
861 let description = format!("{} ({})", pasted.short_label(), pasted.size_label());
862 self.insert_media_attachment("image", &pasted.path, Some(&description));
863 self.status_message = Some(format!("Attached image: {description}"));
864 }
865 }
866 }
867
868 pub fn insert_char(&mut self, c: char) {
869 self.acknowledge_sticky_on_composer_activity();
870 self.clear_input_history_navigation();
871 self.auto_expand_oversized_paste();
872 self.delete_selection();
873 self.selected_attachment_index = None;
874 let cursor = self.cursor_position.min(char_count(&self.input));
875 let byte_index = byte_index_at_char(&self.input, cursor);
876 self.input.insert(byte_index, c);
877 self.cursor_position = cursor + 1;
878 self.strip_raw_mouse_reports_from_input();
879 self.slash_menu_hidden = false;
880 self.mention_menu_hidden = false;
881 self.mention_menu_selected = 0;
882 self.needs_redraw = true;
883 }
884
885 pub fn delete_char(&mut self) {
886 self.clear_input_history_navigation();
887 self.auto_expand_oversized_paste();
888 if self.delete_selection() {
889 return;
890 }
891 self.selected_attachment_index = None;
892 if self.cursor_position == 0 {
893 return;
894 }
895 // Grapheme-aware: Backspace removes the whole cluster before the
896 // cursor (emoji ZWJ sequence, flag pair, CJK char + combining mark),
897 // never a lone scalar out of the middle of one.
898 let cursor = self.cursor_position.min(char_count(&self.input));
899 let target = prev_grapheme_boundary(&self.input, cursor);
900 let removed = remove_char_range(&mut self.input, target, cursor);
901 if removed {
902 self.cursor_position = target;
903 self.slash_menu_hidden = false;
904 self.mention_menu_hidden = false;
905 self.mention_menu_selected = 0;
906 self.needs_redraw = true;
907 }
908 }
909
910 pub fn delete_char_forward(&mut self) {
911 self.clear_input_history_navigation();
912 self.auto_expand_oversized_paste();
913 if self.delete_selection() {
914 return;
915 }
916 self.selected_attachment_index = None;
917 if self.input.is_empty() {
918 return;
919 }
920 // Grapheme-aware: forward-delete removes the whole cluster at the
921 // cursor rather than a single scalar from inside it.
922 let target = self.cursor_position;
923 let end = next_grapheme_boundary(&self.input, target);
924 let removed = remove_char_range(&mut self.input, target, end);
925 if !removed {
926 self.cursor_position = char_count(&self.input);
927 }
928 self.slash_menu_hidden = false;
929 self.mention_menu_hidden = false;
930 self.mention_menu_selected = 0;
931 self.needs_redraw = true;
932 }
933
934 /// Delete the word before the cursor.
935 pub fn delete_word_backward(&mut self) {
936 self.clear_input_history_navigation();
937 if self.delete_selection() {
938 return;
939 }
940 self.selected_attachment_index = None;
941 if self.cursor_position == 0 {
942 return;
943 }
944
945 let cursor_byte = byte_index_at_char(&self.input, self.cursor_position);
946 let mut word_start = cursor_byte;
947
948 while word_start > 0 {
949 let Some((prev, ch)) = self.input[..word_start].char_indices().next_back() else {
950 break;
951 };
952 if !ch.is_whitespace() {
953 break;
954 }
955 word_start = prev;
956 }
957
958 while word_start > 0 {
959 let Some((prev, ch)) = self.input[..word_start].char_indices().next_back() else {
960 break;
961 };
962 if ch.is_whitespace() {
963 break;
964 }
965 word_start = prev;
966 }
967
968 if word_start < cursor_byte {
969 self.input.replace_range(word_start..cursor_byte, "");
970 self.cursor_position = char_count(&self.input[..word_start]);
971 self.slash_menu_hidden = false;
972 self.mention_menu_hidden = false;
973 self.mention_menu_selected = 0;
974 self.needs_redraw = true;
975 }
976 }
977
978 /// Delete from the cursor to the start of the line.
979 pub fn delete_to_start_of_line(&mut self) {
980 self.clear_input_history_navigation();
981 if self.delete_selection() {
982 return;
983 }
984 self.selected_attachment_index = None;
985 if self.cursor_position == 0 {
986 return;
987 }
988
989 let cursor_byte = byte_index_at_char(&self.input, self.cursor_position);
990 // Find the start of the current line (last newline or start of string)
991 let line_start = self.input[..cursor_byte]
992 .rfind('\n')
993 .map(|idx| idx + 1)
994 .unwrap_or(0);
995
996 if line_start < cursor_byte {
997 self.input.replace_range(line_start..cursor_byte, "");
998 self.cursor_position = char_count(&self.input[..line_start]);
999 self.slash_menu_hidden = false;
1000 self.mention_menu_hidden = false;
1001 self.mention_menu_selected = 0;
1002 self.needs_redraw = true;
1003 }
1004 }
1005
1006 /// Delete the word after the cursor.
1007 pub fn delete_word_forward(&mut self) {
1008 self.clear_input_history_navigation();
1009 if self.delete_selection() {
1010 return;
1011 }
1012 self.selected_attachment_index = None;
1013 let cursor_byte = byte_index_at_char(&self.input, self.cursor_position);
1014 if cursor_byte >= self.input.len() {
1015 return;
1016 }
1017
1018 let mut word_end = cursor_byte;
1019 while word_end < self.input.len() {
1020 let Some(ch) = self.input[word_end..].chars().next() else {
1021 break;
1022 };
1023 if !ch.is_whitespace() {
1024 break;
1025 }
1026 word_end += ch.len_utf8();
1027 }
1028
1029 while word_end < self.input.len() {
1030 let Some(ch) = self.input[word_end..].chars().next() else {
1031 break;
1032 };
1033 if ch.is_whitespace() {
1034 break;
1035 }
1036 word_end += ch.len_utf8();
1037 }
1038
1039 if cursor_byte < word_end {
1040 self.input.replace_range(cursor_byte..word_end, "");
1041 self.slash_menu_hidden = false;
1042 self.mention_menu_hidden = false;
1043 self.mention_menu_selected = 0;
1044 self.needs_redraw = true;
1045 }
1046 }
1047
1048 /// Cut from the cursor to the end of the current logical line into the
1049 /// kill buffer. If the cursor is already at end-of-line and a trailing
1050 /// newline exists, that newline is consumed so repeated invocations
1051 /// continue to make progress (matching emacs/codex semantics).
1052 ///
1053 /// Returns `true` when bytes were moved into the kill buffer.
1054 pub fn kill_to_end_of_line(&mut self) -> bool {
1055 self.clear_input_history_navigation();
1056 if let Some((start, end)) = self.selection_range() {
1057 let sb = byte_index_at_char(&self.input, start);
1058 let eb = byte_index_at_char(&self.input, end);
1059 self.kill_buffer = self.input[sb..eb].to_string();
1060 self.delete_selection();
1061 return true;
1062 }
1063 let total_chars = char_count(&self.input);
1064 let cursor = self.cursor_position.min(total_chars);
1065 let start_byte = byte_index_at_char(&self.input, cursor);
1066
1067 // Find the byte offset of the next '\n' (relative to the whole string)
1068 // or the end of the buffer if no newline exists at/after the cursor.
1069 let eol_byte = self.input[start_byte..]
1070 .find('\n')
1071 .map(|rel| start_byte + rel)
1072 .unwrap_or_else(|| self.input.len());
1073
1074 let end_byte = if start_byte == eol_byte {
1075 // Cursor is at EOL — consume the newline itself if one is there.
1076 if eol_byte < self.input.len() {
1077 eol_byte + 1
1078 } else {
1079 return false;
1080 }
1081 } else {
1082 eol_byte
1083 };
1084
1085 let removed: String = self.input[start_byte..end_byte].to_string();
1086 if removed.is_empty() {
1087 return false;
1088 }
1089
1090 self.kill_buffer = removed;
1091 self.input.replace_range(start_byte..end_byte, "");
1092 // Cursor stays at the same character index (start of removed range).
1093 self.cursor_position = cursor;
1094 self.slash_menu_hidden = false;
1095 self.mention_menu_hidden = false;
1096 self.mention_menu_selected = 0;
1097 self.needs_redraw = true;
1098 true
1099 }
1100
1101 /// Insert the contents of the kill buffer at the cursor, advancing it.
1102 /// The kill buffer is left intact so multiple yanks duplicate the text.
1103 /// Returns `true` if any text was inserted.
1104 pub fn yank(&mut self) -> bool {
1105 if self.kill_buffer.is_empty() {
1106 return false;
1107 }
1108 self.delete_selection();
1109 self.clear_input_history_navigation();
1110 let text = self.kill_buffer.clone();
1111 let cursor = self.cursor_position.min(char_count(&self.input));
1112 let byte_index = byte_index_at_char(&self.input, cursor);
1113 self.input.insert_str(byte_index, &text);
1114 self.cursor_position = cursor + char_count(&text);
1115 self.slash_menu_hidden = false;
1116 self.mention_menu_hidden = false;
1117 self.mention_menu_selected = 0;
1118 self.needs_redraw = true;
1119 true
1120 }
1121
1122 pub fn move_cursor_left(&mut self) {
1123 let cursor = self.cursor_position.min(char_count(&self.input));
1124 self.cursor_position = prev_grapheme_boundary(&self.input, cursor);
1125 self.needs_redraw = true;
1126 }
1127
1128 pub fn move_cursor_right(&mut self) {
1129 let total = char_count(&self.input);
1130 if self.cursor_position < total {
1131 self.cursor_position = next_grapheme_boundary(&self.input, self.cursor_position);
1132 self.needs_redraw = true;
1133 }
1134 }
1135
1136 pub fn move_cursor_start(&mut self) {
1137 self.cursor_position = 0;
1138 self.needs_redraw = true;
1139 }
1140
1141 pub fn move_cursor_end(&mut self) {
1142 self.cursor_position = char_count(&self.input);
1143 self.needs_redraw = true;
1144 }
1145
1146 /// In a multiline composer, jump to the start of the current line.
1147 /// On single-line input this is equivalent to `move_cursor_start`.
1148 pub fn move_cursor_line_start(&mut self) {
1149 let byte_pos = byte_index_at_char(&self.input, self.cursor_position);
1150 let before = &self.input[..byte_pos];
1151 if let Some(last_nl_byte) = before.rfind('\n') {
1152 // Position after the '\n' (start of the current line).
1153 self.cursor_position = char_count(&self.input[..=last_nl_byte]);
1154 } else {
1155 self.cursor_position = 0;
1156 }
1157 self.needs_redraw = true;
1158 }
1159
1160 /// In a multiline composer, jump to the end of the current line
1161 /// (just before the next `\n` or at the end of input).
1162 /// On single-line input this is equivalent to `move_cursor_end`.
1163 pub fn move_cursor_line_end(&mut self) {
1164 let search_start = byte_index_at_char(&self.input, self.cursor_position);
1165 if let Some(offset) = self.input[search_start..].find('\n') {
1166 self.cursor_position = char_count(&self.input[..search_start + offset]);
1167 } else {
1168 self.cursor_position = char_count(&self.input);
1169 }
1170 self.needs_redraw = true;
1171 }
1172
1173 /// Move forward one word. Skips over the current word then any trailing
1174 /// whitespace to land on the first character of the next word.
1175 pub fn move_cursor_word_forward(&mut self) {
1176 let text = self.input.clone();
1177 let total = char_count(&text);
1178 let mut pos = self.cursor_position;
1179 if pos >= total {
1180 return;
1181 }
1182 // Skip non-whitespace (current word).
1183 while pos < total {
1184 let byte = byte_index_at_char(&text, pos);
1185 let ch = text[byte..].chars().next().unwrap_or(' ');
1186 if ch.is_whitespace() {
1187 break;
1188 }
1189 pos += 1;
1190 }
1191 // Skip whitespace.
1192 while pos < total {
1193 let byte = byte_index_at_char(&text, pos);
1194 let ch = text[byte..].chars().next().unwrap_or(' ');
1195 if !ch.is_whitespace() {
1196 break;
1197 }
1198 pos += 1;
1199 }
1200 self.cursor_position = pos;
1201 self.needs_redraw = true;
1202 }
1203
1204 /// Move backward one word. Skips leading whitespace then the preceding
1205 /// word to land on its first character.
1206 pub fn move_cursor_word_backward(&mut self) {
1207 let text = self.input.clone();
1208 let mut pos = self.cursor_position;
1209 if pos == 0 {
1210 return;
1211 }
1212 // Step back one so we're not already at the word start.
1213 pos -= 1;
1214 // Skip whitespace.
1215 while pos > 0 {
1216 let byte = byte_index_at_char(&text, pos);
1217 let ch = text[byte..].chars().next().unwrap_or(' ');
1218 if !ch.is_whitespace() {
1219 break;
1220 }
1221 pos -= 1;
1222 }
1223 // Skip non-whitespace.
1224 while pos > 0 {
1225 let byte = byte_index_at_char(&text, pos - 1);
1226 let ch = text[byte..].chars().next().unwrap_or(' ');
1227 if ch.is_whitespace() {
1228 break;
1229 }
1230 pos -= 1;
1231 }
1232 self.cursor_position = pos;
1233 self.needs_redraw = true;
1234 }
1235
1236 /// Select the entire composer contents: anchor at the start, cursor at
1237 /// the end. Expands an oversized-paste preview first so the selection
1238 /// covers the real draft, not a truncated placeholder (#3263).
1239 pub fn select_all(&mut self) {
1240 self.auto_expand_oversized_paste();
1241 if self.input.is_empty() {
1242 self.selection_anchor = None;
1243 return;
1244 }
1245 self.selection_anchor = Some(0);
1246 self.cursor_position = char_count(&self.input);
1247 self.needs_redraw = true;
1248 }
1249
1250 /// Delete the selected text, place cursor at the start of the deleted range.
1251 /// Returns true if a selection was deleted.
1252 ///
1253 /// When the selection spans the whole draft (e.g. select-all then type or
1254 /// Backspace), the outgoing text is stashed exactly like `Ctrl+U` so the
1255 /// destruction is recoverable with `Ctrl+Z` / the draft history.
1256 pub fn delete_selection(&mut self) -> bool {
1257 let Some((start, end)) = self.selection_range() else {
1258 return false;
1259 };
1260 if start == 0 && end == char_count(&self.input) {
1261 let draft = self.input.clone();
1262 if !draft.trim().is_empty() {
1263 self.clear_undo_buffer = Some(draft.clone());
1264 self.remember_draft_for_recovery(draft);
1265 }
1266 }
1267 let sb = byte_index_at_char(&self.input, start);
1268 let eb = byte_index_at_char(&self.input, end);
1269 self.input.replace_range(sb..eb, "");
1270 self.cursor_position = start;
1271 self.selection_anchor = None;
1272 self.clear_input_history_navigation();
1273 self.slash_menu_hidden = false;
1274 self.mention_menu_hidden = false;
1275 self.mention_menu_selected = 0;
1276 self.needs_redraw = true;
1277 true
1278 }
1279
1280 // === Vim composer mode helpers ===
1281 /// Move the cursor to the start of the current logical line (vim `0`).
1282 pub fn vim_move_line_start(&mut self) {
1283 let text = self.input.clone();
1284 let cursor_byte = byte_index_at_char(&text, self.cursor_position);
1285 // Walk backward until we find a newline or the start of the string.
1286 let line_start_byte = text[..cursor_byte].rfind('\n').map_or(0, |idx| idx + 1);
1287 self.cursor_position = char_count(&text[..line_start_byte]);
1288 self.needs_redraw = true;
1289 }
1290
1291 /// Move the cursor to the end of the current logical line (vim `$`).
1292 pub fn vim_move_line_end(&mut self) {
1293 let text = self.input.clone();
1294 let cursor_byte = byte_index_at_char(&text, self.cursor_position);
1295 // Walk forward to the next newline or end-of-string.
1296 let line_end_char = text[cursor_byte..].find('\n').map_or_else(
1297 || char_count(&text),
1298 |rel| char_count(&text[..cursor_byte + rel]),
1299 );
1300 self.cursor_position = line_end_char;
1301 self.needs_redraw = true;
1302 }
1303
1304 /// Move forward one word (vim `w`). Skips over the current word then any
1305 /// trailing whitespace to land on the first character of the next word.
1306 pub fn vim_move_word_forward(&mut self) {
1307 self.move_cursor_word_forward();
1308 }
1309
1310 /// Move backward one word (vim `b`). Skips leading whitespace then the
1311 /// preceding word to land on its first character.
1312 pub fn vim_move_word_backward(&mut self) {
1313 self.move_cursor_word_backward();
1314 }
1315
1316 /// Delete the character under the cursor (vim `x`).
1317 pub fn vim_delete_char_under_cursor(&mut self) {
1318 self.auto_expand_oversized_paste();
1319 let total = char_count(&self.input);
1320 if self.cursor_position >= total {
1321 return;
1322 }
1323 let pos = self.cursor_position;
1324 // Grapheme-aware: `x` deletes the whole cluster under the cursor.
1325 let end = next_grapheme_boundary(&self.input, pos);
1326 remove_char_range(&mut self.input, pos, end);
1327 // Keep cursor in bounds after deletion.
1328 let new_total = char_count(&self.input);
1329 if self.cursor_position > 0 && self.cursor_position >= new_total {
1330 self.cursor_position = new_total.saturating_sub(1);
1331 }
1332 self.needs_redraw = true;
1333 }
1334
1335 /// Delete the entire current logical line (vim `dd`).
1336 pub fn vim_delete_line(&mut self) {
1337 let text = self.input.clone();
1338 let cursor_byte = byte_index_at_char(&text, self.cursor_position);
1339 let line_start_byte = text[..cursor_byte].rfind('\n').map_or(0, |idx| idx + 1);
1340 let line_end_byte = text[cursor_byte..]
1341 .find('\n')
1342 .map_or(text.len(), |rel| cursor_byte + rel);
1343
1344 // Include the trailing newline if present, or the leading newline for the
1345 // very last non-terminated line to avoid leaving a dangling newline.
1346 let (remove_start, remove_end) = if line_end_byte < text.len() {
1347 // There is a newline after the line — remove it too.
1348 (line_start_byte, line_end_byte + 1)
1349 } else if line_start_byte > 0 {
1350 // Last line without trailing newline — remove the preceding newline.
1351 (line_start_byte - 1, line_end_byte)
1352 } else {
1353 // Only line in the buffer.
1354 (line_start_byte, line_end_byte)
1355 };
1356
1357 self.input.replace_range(remove_start..remove_end, "");
1358 self.cursor_position = char_count(&self.input[..remove_start]);
1359 self.needs_redraw = true;
1360 }
1361
1362 /// Enter insert mode at the cursor (vim `i`).
1363 pub fn vim_enter_insert(&mut self) {
1364 self.vim_mode = VimMode::Insert;
1365 self.needs_redraw = true;
1366 }
1367
1368 /// Enter insert mode after the cursor (vim `a`).
1369 pub fn vim_enter_append(&mut self) {
1370 let total = char_count(&self.input);
1371 if self.cursor_position < total {
1372 self.cursor_position += 1;
1373 }
1374 self.vim_mode = VimMode::Insert;
1375 self.needs_redraw = true;
1376 }
1377
1378 /// Open a new line below and enter insert mode (vim `o`).
1379 pub fn vim_open_line_below(&mut self) {
1380 // Move to end of line, then insert a newline.
1381 self.vim_move_line_end();
1382 self.insert_char('\n');
1383 self.vim_mode = VimMode::Insert;
1384 }
1385
1386 /// Return to Normal mode from Insert or Visual (vim `Esc`).
1387 pub fn vim_enter_normal(&mut self) {
1388 self.vim_mode = VimMode::Normal;
1389 self.vim_pending_d = false;
1390 // In Normal mode the cursor sits on a character, not after the last one.
1391 let total = char_count(&self.input);
1392 if self.cursor_position > 0 && self.cursor_position >= total {
1393 self.cursor_position = total.saturating_sub(1);
1394 }
1395 self.needs_redraw = true;
1396 }
1397
1398 /// Move the cursor down one logical line within the buffer (vim `j`).
1399 /// Falls back to history-down when already on the last line.
1400 pub fn vim_move_down(&mut self) {
1401 let text = self.input.clone();
1402 let total = char_count(&text);
1403 if self.cursor_position >= total {
1404 self.history_down();
1405 return;
1406 }
1407 let cursor_byte = byte_index_at_char(&text, self.cursor_position);
1408 let rest = &text[cursor_byte..];
1409 if let Some(rel_nl) = rest.find('\n') {
1410 // Column offset on the current line.
1411 let line_start_byte = text[..cursor_byte].rfind('\n').map_or(0, |i| i + 1);
1412 let col = char_count(&text[line_start_byte..cursor_byte]);
1413 let next_line_start = cursor_byte + rel_nl + 1;
1414 let next_line = &text[next_line_start..];
1415 let next_line_len = next_line.find('\n').unwrap_or(next_line.len());
1416 let next_line_char_len =
1417 char_count(&text[next_line_start..next_line_start + next_line_len]);
1418 let target_col = col.min(next_line_char_len);
1419 self.cursor_position = char_count(&text[..next_line_start]) + target_col;
1420 self.needs_redraw = true;
1421 } else {
1422 self.history_down();
1423 }
1424 }
1425
1426 /// Move the cursor up one logical line within the buffer (vim `k`).
1427 /// Falls back to history-up when already on the first line.
1428 pub fn vim_move_up(&mut self) {
1429 let text = self.input.clone();
1430 let cursor_byte = byte_index_at_char(&text, self.cursor_position);
1431 if let Some(prev_nl) = text[..cursor_byte].rfind('\n') {
1432 // Column on the current line.
1433 let line_start_byte = prev_nl + 1;
1434 let col = char_count(&text[line_start_byte..cursor_byte]);
1435 // Find start of the previous line.
1436 let prev_line_end = prev_nl; // byte of the newline itself
1437 let prev_start = text[..prev_line_end].rfind('\n').map_or(0, |i| i + 1);
1438 let prev_line_len = char_count(&text[prev_start..prev_line_end]);
1439 let target_col = col.min(prev_line_len);
1440 self.cursor_position = char_count(&text[..prev_start]) + target_col;
1441 self.needs_redraw = true;
1442 } else {
1443 self.history_up();
1444 }
1445 }
1446
1447 pub fn clear_input(&mut self) {
1448 self.clear_input_history_navigation();
1449 self.input.clear();
1450 self.cursor_position = 0;
1451 // Prevent stale oversized-paste state from leaking when the user
1452 // clears the composer or navigates to a different input (#3263).
1453 self.pending_paste_reference = None;
1454 self.oversized_paste_full_text = None;
1455 self.selection_anchor = None;
1456 self.selected_attachment_index = None;
1457 self.slash_menu_selected = 0;
1458 self.slash_menu_hidden = false;
1459 self.paste_burst.clear_after_explicit_paste();
1460 self.needs_redraw = true;
1461 }
1462
1463 pub fn clear_input_recoverable(&mut self) {
1464 self.stash_current_input_for_recovery();
1465 self.clear_input();
1466 }
1467
1468 pub fn start_history_search(&mut self) {
1469 if self.composer_history_search.is_some() {
1470 return;
1471 }
1472 // Expand any truncated paste first so the history search seed
1473 // contains the full text, not the truncated preview (#3263).
1474 self.auto_expand_oversized_paste();
1475 self.composer_history_search = Some(ComposerHistorySearch::new(
1476 self.input.clone(),
1477 self.cursor_position,
1478 ));
1479 self.slash_menu_hidden = true;
1480 self.mention_menu_hidden = true;
1481 self.paste_burst.clear_after_explicit_paste();
1482 self.status_message = Some("History search: type to filter, Enter accepts".to_string());
1483 self.needs_redraw = true;
1484 }
1485
1486 pub fn history_search_insert_char(&mut self, ch: char) {
1487 if let Some(search) = self.composer_history_search.as_mut() {
1488 search.query.push(ch);
1489 search.selected = 0;
1490 self.status_message = Some("History search: Enter accepts, Esc restores".to_string());
1491 self.needs_redraw = true;
1492 }
1493 }
1494
1495 pub fn history_search_insert_str(&mut self, text: &str) {
1496 if text.is_empty() {
1497 return;
1498 }
1499 if let Some(search) = self.composer_history_search.as_mut() {
1500 search.query.push_str(&normalize_paste_text(text));
1501 search.selected = 0;
1502 self.status_message = Some("History search: Enter accepts, Esc restores".to_string());
1503 self.needs_redraw = true;
1504 }
1505 }
1506
1507 pub fn history_search_backspace(&mut self) {
1508 if let Some(search) = self.composer_history_search.as_mut() {
1509 search.query.pop();
1510 search.selected = 0;
1511 self.needs_redraw = true;
1512 }
1513 self.clamp_history_search_selection();
1514 }
1515
1516 pub fn history_search_select_previous(&mut self) {
1517 if let Some(search) = self.composer_history_search.as_mut() {
1518 search.selected = search.selected.saturating_sub(1);
1519 self.needs_redraw = true;
1520 }
1521 }
1522
1523 pub fn history_search_select_next(&mut self) {
1524 let Some(search) = self.composer_history_search.as_ref() else {
1525 return;
1526 };
1527 let query = search.query.clone();
1528 let selected = search.selected;
1529 let match_count = self.history_search_matches_for_query(&query).len();
1530 if let Some(search) = self.composer_history_search.as_mut()
1531 && match_count > 0
1532 {
1533 search.selected = (selected + 1).min(match_count.saturating_sub(1));
1534 self.needs_redraw = true;
1535 }
1536 }
1537
1538 pub fn accept_history_search(&mut self) -> bool {
1539 let Some(search) = self.composer_history_search.take() else {
1540 return false;
1541 };
1542 let matches = self.history_search_matches_for_query(&search.query);
1543 if let Some(selected) = matches
1544 .get(search.selected.min(matches.len().saturating_sub(1)))
1545 .cloned()
1546 {
1547 self.input = selected;
1548 self.cursor_position = char_count(&self.input);
1549 self.history_index = None;
1550 self.status_message = Some("History match inserted into composer".to_string());
1551 self.needs_redraw = true;
1552 true
1553 } else {
1554 self.composer_history_search = Some(search);
1555 self.status_message = Some("No history matches".to_string());
1556 self.needs_redraw = true;
1557 false
1558 }
1559 }
1560
1561 pub fn cancel_history_search(&mut self) {
1562 let Some(search) = self.composer_history_search.take() else {
1563 return;
1564 };
1565 self.input = search.pre_search_input;
1566 self.cursor_position = search.pre_search_cursor.min(char_count(&self.input));
1567 self.status_message = Some("History search canceled".to_string());
1568 self.needs_redraw = true;
1569 }
1570
1571 pub fn submit_input(&mut self) -> Option<String> {
1572 if self.input.trim().is_empty() {
1573 self.paste_burst.clear_after_explicit_paste();
1574 return None;
1575 }
1576 // Safety net: if any earlier path filled the buffer above the
1577 // safety cap without going through `insert_paste_text`, fold it
1578 // into a workspace paste file now (#553). Bracketed pastes hit
1579 // the consolidation in `insert_paste_text` first, so the user
1580 // sees the @mention in the composer before submission.
1581 self.consolidate_large_input_if_oversized();
1582 // If consolidation created a paste file, restore the full text and
1583 // append the @mention so the model can read the complete content
1584 // while the composer stays editable (#3263).
1585 let mut input = self
1586 .oversized_paste_full_text
1587 .take()
1588 .unwrap_or_else(|| self.input.clone());
1589 if let Some(reference) = self.pending_paste_reference.take() {
1590 if !input.is_empty() && !input.ends_with('\n') {
1591 input.push('\n');
1592 }
1593 input.push_str(&reference);
1594 }
1595 if !looks_like_slash_command_input(&input) {
1596 self.input_history.push(input.clone());
1597 if self.max_input_history == 0 {
1598 self.input_history.clear();
1599 } else if self.input_history.len() > self.max_input_history {
1600 let excess = self.input_history.len() - self.max_input_history;
1601 self.input_history.drain(0..excess);
1602 }
1603 // Mirror to the persisted cross-session history (#366) so
1604 // arrow-up recall works across restarts. Best-effort write —
1605 // see `composer_history::append_history` for failure modes.
1606 crate::composer_history::append_history(&input);
1607 }
1608 self.history_index = None;
1609 self.history_navigation_draft = None;
1610 self.clear_input();
1611 // Collapse recent-only Work chrome on the next accepted turn (#4688).
1612 self.work_surface.note_user_turn_or_new_operation();
1613 Some(input)
1614 }
1615
1616 pub fn restore_last_submitted_prompt_if_empty(&mut self) -> bool {
1617 if !self.input.is_empty() {
1618 return false;
1619 }
1620 let Some(prompt) = self
1621 .last_submitted_prompt
1622 .as_deref()
1623 .filter(|prompt| !prompt.is_empty())
1624 else {
1625 return false;
1626 };
1627
1628 self.input = prompt.to_string();
1629 self.cursor_position = char_count(&self.input);
1630 self.history_index = None;
1631 self.history_navigation_draft = None;
1632 self.selected_attachment_index = None;
1633 self.needs_redraw = true;
1634 true
1635 }
1636
1637 /// Restore the last cleared input if the composer is empty.
1638 /// Returns `true` if the input was restored.
1639 pub fn restore_last_cleared_input_if_empty(&mut self) -> bool {
1640 if !self.input.is_empty() {
1641 return false;
1642 }
1643 let Some(saved) = self.clear_undo_buffer.take().filter(|s| !s.is_empty()) else {
1644 return false;
1645 };
1646
1647 self.input = saved;
1648 self.cursor_position = char_count(&self.input);
1649 self.history_index = None;
1650 self.history_navigation_draft = None;
1651 self.selected_attachment_index = None;
1652 self.slash_menu_selected = 0;
1653 self.slash_menu_hidden = false;
1654 self.needs_redraw = true;
1655 self.clear_undo_buffer = None;
1656 true
1657 }
1658
1659 /// Composer-Enter dispatch. Returns `Some(input)` when the press should
1660 /// fire a submit; `None` when Enter was absorbed (paste-burst Enter
1661 /// suppression — see #1073).
1662 ///
1663 /// Two suppression cases are handled here. Both are silent: nothing
1664 /// visible happens beyond the text gaining a newline.
1665 ///
1666 /// 1. **Burst active.** A paste burst is currently being assembled in
1667 /// `paste_burst.buffer`. The Enter is part of the paste content;
1668 /// append `\n` to the buffer so the next flush includes it, do not
1669 /// submit, and extend the suppression window so a follow-on Enter
1670 /// (i.e. the *next* line of a multi-line paste) is also absorbed.
1671 /// 2. **Window open after flush.** A burst just flushed into
1672 /// `self.input`, but the suppression window is still alive. The
1673 /// Enter is probably the trailing newline of that paste, not a submit
1674 /// gesture by the user, so insert `\n` directly into the composer
1675 /// text. The window is deliberately *not* re-armed here: no burst is
1676 /// being assembled, so this Enter is only a guess, and re-arming on a
1677 /// guess meant every absorbed Enter bought another 120ms — a user
1678 /// pressing Enter to send just kept adding newlines and never
1679 /// submitted. Suppression now always ends 120ms after the last real
1680 /// keystroke.
1681 ///
1682 /// Outside both cases the call falls through to [`Self::submit_input`]
1683 /// unchanged so normal Enter-to-send behaviour is preserved.
1684 pub fn handle_composer_enter(&mut self) -> Option<String> {
1685 if self.use_paste_burst_detection {
1686 let now = Instant::now();
1687 if self
1688 .paste_burst
1689 .newline_should_insert_instead_of_submit(now)
1690 {
1691 if !self.paste_burst.append_newline_if_active(now) {
1692 self.insert_char('\n');
1693 }
1694 self.needs_redraw = true;
1695 return None;
1696 }
1697 }
1698 self.submit_input()
1699 }
1700
1701 /// Public wrapper around [`Self::consolidate_large_input`] that no-ops
1702 /// when the current input fits inside the safety cap. Both the paste-
1703 /// insert path (visible-before-submit) and the submit-time safety net
1704 /// route through here, so the cap is enforced exactly once even when
1705 /// both paths fire on the same buffer.
1706 fn consolidate_large_input_if_oversized(&mut self) {
1707 if char_count(&self.input) > MAX_SUBMITTED_INPUT_CHARS {
1708 self.consolidate_large_input();
1709 }
1710 }
1711
1712 /// When the composer input exceeds [`MAX_SUBMITTED_INPUT_CHARS`], write
1713 /// the full content to a timestamped paste file under
1714 /// `.codewhale/pastes/` and replace `self.input` with an `@`-mention
1715 /// pointing at it so the model can read the full content via the
1716 /// normal file-mention resolution path (#553).
1717 fn consolidate_large_input(&mut self) {
1718 let full_input = std::mem::take(&mut self.input);
1719 self.cursor_position = 0;
1720
1721 let now = chrono::Local::now();
1722 let suffix = uuid::Uuid::new_v4().to_string()[..8].to_string();
1723 let filename = format!("paste-{}-{}.md", now.format("%Y-%m-%d-%H%M%S"), suffix);
1724 let rel_path = format!(".codewhale/pastes/{filename}");
1725
1726 let pastes_dir = self.workspace.join(".codewhale/pastes");
1727 if let Err(e) = std::fs::create_dir_all(&pastes_dir) {
1728 // Fallback: keep a truncated version so we don't lose the
1729 // user's input entirely when the filesystem is unhappy.
1730 self.input = full_input.chars().take(MAX_SUBMITTED_INPUT_CHARS).collect();
1731 self.cursor_position = char_count(&self.input);
1732 self.push_status_toast(
1733 format!("Failed to create paste directory: {e}"),
1734 StatusToastLevel::Error,
1735 Some(8_000),
1736 );
1737 return;
1738 }
1739
1740 let file_path = self.workspace.join(&rel_path);
1741 if let Err(e) = std::fs::write(&file_path, &full_input) {
1742 self.input = full_input.chars().take(MAX_SUBMITTED_INPUT_CHARS).collect();
1743 self.cursor_position = char_count(&self.input);
1744 self.push_status_toast(
1745 format!("Failed to write paste file: {e}"),
1746 StatusToastLevel::Error,
1747 Some(8_000),
1748 );
1749 return;
1750 }
1751
1752 // Keep a truncated preview in the composer so the user can still
1753 // select, copy, and edit it, while the full text is stored for
1754 // model submission. The @mention is appended at submit time (#3263).
1755 self.pending_paste_reference = Some(format!("@{rel_path}"));
1756 self.oversized_paste_full_text = Some(full_input.clone());
1757 let display_chars = char_count(&full_input).min(MAX_COMPOSER_DISPLAY_CHARS);
1758 let mut truncated: String = full_input.chars().take(display_chars).collect();
1759 if char_count(&full_input) > MAX_COMPOSER_DISPLAY_CHARS {
1760 truncated.push_str("\n\n---\n(content truncated for display — start typing to expand; full text sent to model)");
1761 }
1762 self.input = truncated;
1763 self.cursor_position = 0;
1764 self.push_status_toast(
1765 "Large paste backed up to file — the model will receive the full content.",
1766 StatusToastLevel::Info,
1767 Some(5_000),
1768 );
1769 }
1770
1771 pub fn history_down(&mut self) {
1772 if self.input_history.is_empty() {
1773 return;
1774 }
1775 match self.history_index {
1776 None => {}
1777 Some(i) => {
1778 if i + 1 < self.input_history.len() {
1779 self.history_index = Some(i + 1);
1780 self.input = self.input_history[i + 1].clone();
1781 self.cursor_position = char_count(&self.input);
1782 self.selection_anchor = None;
1783 self.selected_attachment_index = None;
1784 self.slash_menu_hidden = false;
1785 self.paste_burst.clear_after_explicit_paste();
1786 } else {
1787 self.history_index = None;
1788 if let Some(draft) = self.history_navigation_draft.take() {
1789 self.input = draft.input;
1790 self.cursor_position = draft.cursor.min(char_count(&self.input));
1791 self.selection_anchor = None;
1792 self.selected_attachment_index = None;
1793 self.slash_menu_hidden = false;
1794 self.paste_burst.clear_after_explicit_paste();
1795 self.needs_redraw = true;
1796 } else {
1797 self.clear_input();
1798 }
1799 }
1800 }
1801 }
1802 }
1803 }
1804
1804 lines RUST