mirror of
https://github.com/openai/codex.git
synced 2026-11-18 22:20:48 +00:00
Add undo and redo to the non-Vim prompt composer (#61954)
## What changed - Add configurable `composer.undo` and `composer.redo` actions to the keymap picker. Default undo shortcuts are `Alt+Z` on Unix, `Ctrl+Z` on Windows, and `F7`, with `Super+Z` also available on macOS. Add `Shift` to redo. - Group contiguous typing and consecutive Backspaces into separate undo steps, and keep detected paste bursts separate from preceding typing. Restore complete drafts, including attachments and large pastes. - Make startup draft transfers undoable, preserve editing history across Vim mode changes, and clear history when a submitted draft is consumed. Track edits while disconnected so new input invalidates redo. ## Testing Add regression coverage for grouped edits, paste detection and selection replacement, clipboard images, startup draft transfers, disconnected editing, and keybinding conflicts. GitOrigin-RevId: 46cadf3c69320367dc972e47e0e8b3d3aac3c4ec
This commit is contained in:
@@ -243,6 +243,10 @@ pub struct TuiComposerKeymap {
|
||||
pub history_search_previous: Option<KeybindingsSpec>,
|
||||
/// Move to the next match in reverse history search.
|
||||
pub history_search_next: Option<KeybindingsSpec>,
|
||||
/// Undo the last edit to the composer draft.
|
||||
pub undo: Option<KeybindingsSpec>,
|
||||
/// Redo an undone composer edit.
|
||||
pub redo: Option<KeybindingsSpec>,
|
||||
}
|
||||
|
||||
/// Editor context keybindings for text editing inside text areas.
|
||||
|
||||
@@ -5527,8 +5527,10 @@
|
||||
"history_search_next": null,
|
||||
"history_search_previous": null,
|
||||
"queue": null,
|
||||
"redo": null,
|
||||
"submit": null,
|
||||
"toggle_shortcuts": null
|
||||
"toggle_shortcuts": null,
|
||||
"undo": null
|
||||
},
|
||||
"editor": {
|
||||
"delete_backward": null,
|
||||
@@ -6174,6 +6176,14 @@
|
||||
],
|
||||
"description": "Queue the current composer draft while a task is running."
|
||||
},
|
||||
"redo": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/KeybindingsSpec"
|
||||
}
|
||||
],
|
||||
"description": "Redo an undone composer edit."
|
||||
},
|
||||
"submit": {
|
||||
"allOf": [
|
||||
{
|
||||
@@ -6189,6 +6199,14 @@
|
||||
}
|
||||
],
|
||||
"description": "Toggle the composer shortcut overlay."
|
||||
},
|
||||
"undo": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/KeybindingsSpec"
|
||||
}
|
||||
],
|
||||
"description": "Undo the last edit to the composer draft."
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
@@ -6716,8 +6734,10 @@
|
||||
"history_search_next": null,
|
||||
"history_search_previous": null,
|
||||
"queue": null,
|
||||
"redo": null,
|
||||
"submit": null,
|
||||
"toggle_shortcuts": null
|
||||
"toggle_shortcuts": null,
|
||||
"undo": null
|
||||
}
|
||||
},
|
||||
"editor": {
|
||||
|
||||
@@ -39,6 +39,16 @@
|
||||
//! Confirmed `$` picker selections inform future ordering within each match tier.
|
||||
//! A cached plugin skill keeps its ranking when its installed version changes.
|
||||
//!
|
||||
//! Ordinary prompt undo records the complete draft before each edit. Contiguous typing shares a
|
||||
//! step until a pause or cursor move; consecutive Backspaces share their own step until a pause
|
||||
//! or another edit. Paste bursts stay open until flushing classifies the input.
|
||||
//! Detected paste bursts, including those promoted by Enter or Tab, form a separate step from typing.
|
||||
//! Retroactive detection reuses the pre-replacement draft when the burst began over a selection.
|
||||
//! Clipboard attachments also settle buffered typing first. Undo restores text and attachments together;
|
||||
//! Vim retains command-level transactions, and consuming a submitted draft ends its history.
|
||||
//! A draft transferred from the provisional startup composer is one ordinary undo step back to
|
||||
//! the destination draft, including when the transfer merges with an initial prompt.
|
||||
//!
|
||||
//! # Key Event Routing
|
||||
//!
|
||||
//! Plain Left opens agents from an empty, active composer connected to a local daemon or remote App Server.
|
||||
@@ -599,6 +609,7 @@ pub(crate) struct ChatComposerConfig {
|
||||
pub(crate) trim_submission: bool,
|
||||
/// Embedded editors reset Vim only when their owner accepts the answer.
|
||||
pub(crate) reset_vim_on_submission: bool,
|
||||
pub(crate) undo_enabled: bool,
|
||||
}
|
||||
|
||||
impl Default for ChatComposerConfig {
|
||||
@@ -611,6 +622,7 @@ impl Default for ChatComposerConfig {
|
||||
blockquote_paste_enabled: true,
|
||||
trim_submission: true,
|
||||
reset_vim_on_submission: true,
|
||||
undo_enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -626,6 +638,7 @@ impl ChatComposerConfig {
|
||||
blockquote_paste_enabled: true,
|
||||
trim_submission: true,
|
||||
reset_vim_on_submission: true,
|
||||
undo_enabled: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -684,6 +697,8 @@ pub(crate) struct ChatComposer {
|
||||
toggle_shortcuts_keys: Vec<KeyBinding>,
|
||||
history_search_previous_keys: Vec<KeyBinding>,
|
||||
history_search_next_keys: Vec<KeyBinding>,
|
||||
undo_keys: Vec<KeyBinding>,
|
||||
redo_keys: Vec<KeyBinding>,
|
||||
editor_keymap: Arc<EditorKeymap>,
|
||||
vim_normal_keymap: VimNormalKeymap,
|
||||
}
|
||||
@@ -702,7 +717,7 @@ pub(crate) enum ShellPrefixHandling {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(super) struct ComposerDraft {
|
||||
pub(crate) struct ComposerDraft {
|
||||
is_bash_mode: bool,
|
||||
pub(super) text: String,
|
||||
text_elements: Vec<TextElement>,
|
||||
@@ -872,6 +887,8 @@ impl ChatComposer {
|
||||
],
|
||||
history_search_previous_keys: default_keymap.composer.history_search_previous.clone(),
|
||||
history_search_next_keys: default_keymap.composer.history_search_next.clone(),
|
||||
undo_keys: default_keymap.composer.undo.clone(),
|
||||
redo_keys: default_keymap.composer.redo.clone(),
|
||||
editor_keymap: default_editor_keymap,
|
||||
vim_normal_keymap: default_vim_normal_keymap,
|
||||
};
|
||||
@@ -1098,6 +1115,8 @@ impl ChatComposer {
|
||||
self.toggle_shortcuts_keys = keymap.composer.toggle_shortcuts.clone();
|
||||
self.history_search_previous_keys = keymap.composer.history_search_previous.clone();
|
||||
self.history_search_next_keys = keymap.composer.history_search_next.clone();
|
||||
self.undo_keys = keymap.composer.undo.clone();
|
||||
self.redo_keys = keymap.composer.redo.clone();
|
||||
self.editor_keymap = keymap.editor.clone();
|
||||
self.vim_normal_keymap = keymap.vim_normal.clone();
|
||||
self.draft.textarea.set_keymap_bindings(keymap);
|
||||
@@ -1139,11 +1158,24 @@ impl ChatComposer {
|
||||
if self.history_search.is_some() {
|
||||
return KeymapContextSet::new(KeymapContext::Composer);
|
||||
}
|
||||
if !self.draft.input_enabled || self.popups.active() {
|
||||
if !self.draft.input_enabled {
|
||||
return KeymapContextSet::default();
|
||||
}
|
||||
let undo_enabled = self.config.undo_enabled && !self.draft.textarea.is_vim_enabled();
|
||||
if self.popups.active() {
|
||||
return if undo_enabled {
|
||||
KeymapContextSet::composer_edit_only()
|
||||
} else {
|
||||
KeymapContextSet::default()
|
||||
};
|
||||
}
|
||||
let contexts = self.draft.textarea.keymap_contexts();
|
||||
contexts.with(KeymapContext::Composer)
|
||||
let contexts = contexts.with(KeymapContext::Composer);
|
||||
if undo_enabled {
|
||||
contexts
|
||||
} else {
|
||||
contexts.without_composer_edits()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_collaboration_mode_indicator(
|
||||
@@ -1402,13 +1434,18 @@ impl ChatComposer {
|
||||
/// changes because Vim normal mode treats rapid character sequences as
|
||||
/// commands, not as candidate literal paste text. It also resets transient
|
||||
/// footer mode so the visible hints match the new editing surface.
|
||||
/// Editors without ordinary undo discard Vim history across mode changes.
|
||||
pub(crate) fn set_vim_enabled(&mut self, enabled: bool) {
|
||||
if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() {
|
||||
self.apply_paste(pasted);
|
||||
}
|
||||
self.finish_edit();
|
||||
self.draft.textarea.enable_vim_search();
|
||||
self.draft.textarea.set_vim_enabled(enabled);
|
||||
self.edit_history = EditHistory::default();
|
||||
self.finish_edit();
|
||||
if !self.config.undo_enabled {
|
||||
self.edit_history = EditHistory::default();
|
||||
}
|
||||
self.draft.paste_burst.clear_after_explicit_paste();
|
||||
self.footer.mode = reset_mode_after_activity(self.footer.mode);
|
||||
}
|
||||
@@ -1820,6 +1857,12 @@ impl ChatComposer {
|
||||
if self.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let undo_clear = self.config.undo_enabled && !self.draft.textarea.is_vim_enabled();
|
||||
if undo_clear {
|
||||
self.finish_edit();
|
||||
self.begin_edit_transaction();
|
||||
}
|
||||
let edit = undo_clear.then(|| std::mem::take(&mut self.edit_history));
|
||||
let previous = self.current_text();
|
||||
let text_elements = self.current_text_elements();
|
||||
let local_image_paths = self.attachments.local_image_paths();
|
||||
@@ -1828,6 +1871,10 @@ impl ChatComposer {
|
||||
let mention_bindings = self.snapshot_mention_bindings();
|
||||
self.set_text_content(String::new(), Vec::new(), Vec::new());
|
||||
self.attachments.clear_remote_image_urls();
|
||||
if let Some(history) = edit {
|
||||
self.edit_history = history;
|
||||
self.finish_edit();
|
||||
}
|
||||
self.history.reset_navigation();
|
||||
self.history.record_local_submission(HistoryEntry {
|
||||
text: previous.clone(),
|
||||
@@ -2055,7 +2102,14 @@ impl ChatComposer {
|
||||
|
||||
self.draft.textarea_state.get_mut().follow_cursor();
|
||||
let before = self.before_sparkle_key(key_event);
|
||||
if !self.draft.textarea.is_vim_enabled() {
|
||||
self.handle_paste_burst_flush(tokio::time::Instant::now().into_std());
|
||||
}
|
||||
self.begin_composer_key_edit(key_event);
|
||||
let result = self.handle_key_event_inner(key_event);
|
||||
if !self.draft.textarea.is_vim_enabled() {
|
||||
self.finish_edit();
|
||||
}
|
||||
if is_char && !self.draft.paste_burst.is_active() {
|
||||
self.draft.skill_completion_space = None;
|
||||
}
|
||||
@@ -2190,6 +2244,7 @@ impl ChatComposer {
|
||||
if grab.grabbed.is_empty()
|
||||
|| self.draft.textarea.retract_paste_burst(grab.start_byte)
|
||||
{
|
||||
self.begin_retroactive_paste_edit(grab.start_byte);
|
||||
self.draft.paste_burst.append_char_to_buffer(ch, now);
|
||||
return (InputResult::None, true);
|
||||
}
|
||||
@@ -3263,6 +3318,11 @@ impl ChatComposer {
|
||||
}
|
||||
|
||||
fn reset_vim_mode_after_successful_dispatch(&mut self, result: &InputResult) {
|
||||
if matches!(result, InputResult::Command(command) | InputResult::CommandWithArgs(command, _, _)
|
||||
if command.requires_dispatch_validation())
|
||||
{
|
||||
return;
|
||||
}
|
||||
if matches!(
|
||||
result,
|
||||
InputResult::Submitted { .. }
|
||||
@@ -3270,9 +3330,11 @@ impl ChatComposer {
|
||||
| InputResult::Command(_)
|
||||
| InputResult::ServiceTierCommand(_)
|
||||
| InputResult::CommandWithArgs(_, _, _)
|
||||
) && self.config.reset_vim_on_submission
|
||||
{
|
||||
self.reset_vim_mode();
|
||||
) {
|
||||
self.edit_history = EditHistory::default();
|
||||
if self.config.reset_vim_on_submission {
|
||||
self.reset_vim_mode();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3820,6 +3882,7 @@ impl ChatComposer {
|
||||
if grab.grabbed.is_empty()
|
||||
|| self.draft.textarea.retract_paste_burst(grab.start_byte)
|
||||
{
|
||||
self.begin_retroactive_paste_edit(grab.start_byte);
|
||||
self.draft.paste_burst.append_char_to_buffer(ch, now);
|
||||
return (InputResult::None, true);
|
||||
}
|
||||
@@ -3830,6 +3893,7 @@ impl ChatComposer {
|
||||
}
|
||||
CharDecision::BeginBufferFromPending => {
|
||||
// First char was held; now append the current one.
|
||||
self.begin_detected_paste_edit();
|
||||
self.draft.paste_burst.append_char_to_buffer(ch, now);
|
||||
return (InputResult::None, true);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
//! so canceled commands cannot evict committed history.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use super::super::textarea::VimPersistentState;
|
||||
use super::ChatComposer;
|
||||
@@ -15,18 +17,30 @@ use crate::key_hint::KeyBindingListExt;
|
||||
use crossterm::event::KeyEvent;
|
||||
|
||||
const MAX_UNDO_STEPS: usize = 64;
|
||||
const MAX_UNDO_BYTES: usize = 1024 * 1024;
|
||||
const MAX_UNDO_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
enum EditDirection {
|
||||
Undo,
|
||||
Redo,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum TypingEdit {
|
||||
Start,
|
||||
ReplaceSelection(usize),
|
||||
Continue,
|
||||
BackspaceStart,
|
||||
BackspaceContinue(usize),
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct EditHistory {
|
||||
undo: VecDeque<ComposerDraft>,
|
||||
redo: VecDeque<ComposerDraft>,
|
||||
pending: Option<ComposerDraft>,
|
||||
typing: Option<(Instant, Instant, usize, Option<usize>)>,
|
||||
typing_edit: Option<TypingEdit>,
|
||||
backspace: Option<(Instant, usize)>,
|
||||
}
|
||||
|
||||
impl ComposerDraft {
|
||||
@@ -57,12 +71,19 @@ impl EditHistory {
|
||||
direction: EditDirection,
|
||||
current: impl FnOnce() -> ComposerDraft,
|
||||
) -> Option<ComposerDraft> {
|
||||
self.typing = None;
|
||||
self.backspace = None;
|
||||
let (from, to) = match direction {
|
||||
EditDirection::Undo => (&mut self.undo, &mut self.redo),
|
||||
EditDirection::Redo => (&mut self.redo, &mut self.undo),
|
||||
};
|
||||
let snapshot = from.pop_back()?;
|
||||
to.push_back(current());
|
||||
let current = current();
|
||||
if current.history_bytes() <= MAX_UNDO_BYTES {
|
||||
to.push_back(current);
|
||||
} else {
|
||||
to.clear();
|
||||
}
|
||||
self.trim();
|
||||
Some(snapshot)
|
||||
}
|
||||
@@ -85,21 +106,48 @@ impl EditHistory {
|
||||
}
|
||||
|
||||
impl ChatComposer {
|
||||
pub(super) fn wants_edit_history_key(&self, event: KeyEvent) -> bool {
|
||||
self.draft.textarea.is_vim_normal_mode()
|
||||
&& !self.draft.textarea.is_vim_operator_pending()
|
||||
&& !self.popups.active()
|
||||
&& (self.vim_normal_keymap.redo.is_pressed(event)
|
||||
|| self.vim_normal_keymap.undo.is_pressed(event))
|
||||
pub(in crate::bottom_pane) fn capture_startup_undo(&mut self) -> Option<ComposerDraft> {
|
||||
self.begin_edit_transaction();
|
||||
self.edit_history.pending.take()
|
||||
}
|
||||
|
||||
/// Consume undo and redo before normal-mode commands, even when their history is empty.
|
||||
/// Make a draft transferred from the provisional startup composer undoable.
|
||||
pub(in crate::bottom_pane) fn record_startup_undo(&mut self, destination: ComposerDraft) {
|
||||
if self.config.undo_enabled && !self.draft.textarea.is_vim_enabled() {
|
||||
self.edit_history.undo.push_back(destination);
|
||||
self.edit_history.redo.clear();
|
||||
self.edit_history.trim();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn wants_edit_history_key(&self, event: KeyEvent) -> bool {
|
||||
if self.history_search.is_some() || self.draft.textarea.vim_query().is_some() {
|
||||
return false;
|
||||
}
|
||||
(self.config.undo_enabled
|
||||
&& !self.draft.textarea.is_vim_enabled()
|
||||
&& (self.redo_keys.is_pressed(event) || self.undo_keys.is_pressed(event)))
|
||||
|| (self.draft.textarea.is_vim_normal_mode()
|
||||
&& !self.draft.textarea.is_vim_operator_pending()
|
||||
&& !self.popups.active()
|
||||
&& (self.vim_normal_keymap.redo.is_pressed(event)
|
||||
|| self.vim_normal_keymap.undo.is_pressed(event)))
|
||||
}
|
||||
|
||||
/// Consume undo and redo even when their history is empty.
|
||||
pub(super) fn handle_edit_history_key(&mut self, event: KeyEvent) -> bool {
|
||||
if !self.wants_edit_history_key(event) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let direction = if self.vim_normal_keymap.redo.is_pressed(event) {
|
||||
let normal = self.draft.textarea.is_vim_normal_mode();
|
||||
if !normal {
|
||||
self.flush_pending_paste_burst();
|
||||
self.finish_edit();
|
||||
self.popups.active = super::ActivePopup::None;
|
||||
}
|
||||
let direction = if (normal && self.vim_normal_keymap.redo.is_pressed(event))
|
||||
|| (!normal && self.redo_keys.is_pressed(event))
|
||||
{
|
||||
EditDirection::Redo
|
||||
} else {
|
||||
EditDirection::Undo
|
||||
@@ -115,12 +163,134 @@ impl ChatComposer {
|
||||
self.draft
|
||||
.textarea
|
||||
.swap_vim_persistent_state(&mut vim_state);
|
||||
self.draft.textarea.enter_vim_normal_mode();
|
||||
}
|
||||
self.edit_history = history;
|
||||
if normal {
|
||||
self.draft.textarea.enter_vim_normal_mode();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Group contiguous ordinary typing and backward-character deletions separately.
|
||||
pub(super) fn begin_composer_key_edit(&mut self, event: KeyEvent) {
|
||||
if !self.config.undo_enabled
|
||||
|| self.draft.textarea.is_vim_enabled()
|
||||
|| self.history_search.is_some()
|
||||
|| self.wants_edit_history_key(event)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let selection = self.draft.textarea.mouse_selection_range();
|
||||
let typing = (crate::key_hint::is_plain_text_key_event(event)
|
||||
|| matches!(event.code, crossterm::event::KeyCode::Char(_))
|
||||
&& crate::key_hint::is_altgr(event.modifiers))
|
||||
&& !self.editor_keymap.insert_newline.is_pressed(event)
|
||||
&& !self.editor_keymap.delete_backward_word.is_pressed(event);
|
||||
if !typing
|
||||
&& !matches!(
|
||||
event.code,
|
||||
crossterm::event::KeyCode::Enter | crossterm::event::KeyCode::Tab
|
||||
)
|
||||
&& self.draft.paste_burst.is_active()
|
||||
{
|
||||
self.flush_pending_paste_burst();
|
||||
self.finish_edit();
|
||||
}
|
||||
if self.edit_history.pending.is_some() || self.edit_history.typing_edit.is_some() {
|
||||
return;
|
||||
}
|
||||
let previous_backspace = self.edit_history.backspace.take();
|
||||
if self.editor_keymap.delete_backward.is_pressed(event)
|
||||
&& !self.editor_keymap.delete_backward_word.is_pressed(event)
|
||||
&& selection.is_none()
|
||||
&& !self.popups.active()
|
||||
&& self.attachments.selected_remote_image_index.is_none()
|
||||
{
|
||||
self.edit_history.typing = None;
|
||||
if previous_backspace.is_some_and(|(last, cursor)| {
|
||||
last.elapsed() < Duration::from_millis(500) && cursor == self.current_cursor()
|
||||
}) {
|
||||
self.edit_history.typing_edit =
|
||||
Some(TypingEdit::BackspaceContinue(self.current_cursor()));
|
||||
} else {
|
||||
self.edit_history.typing_edit = Some(TypingEdit::BackspaceStart);
|
||||
self.begin_edit_transaction();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.editor_keymap.move_left.is_pressed(event)
|
||||
|| self.editor_keymap.move_right.is_pressed(event)
|
||||
|| self.editor_keymap.move_up.is_pressed(event)
|
||||
|| self.editor_keymap.move_down.is_pressed(event)
|
||||
|| self.editor_keymap.move_word_left.is_pressed(event)
|
||||
|| self.editor_keymap.move_word_right.is_pressed(event)
|
||||
|| self.editor_keymap.move_line_start.is_pressed(event)
|
||||
|| self.editor_keymap.move_line_end.is_pressed(event)
|
||||
{
|
||||
self.edit_history.typing = None;
|
||||
return;
|
||||
}
|
||||
let now = Instant::now();
|
||||
if typing
|
||||
&& selection.is_none()
|
||||
&& !self.popups.active()
|
||||
&& self
|
||||
.edit_history
|
||||
.typing
|
||||
.is_some_and(|(start, last, cursor, _)| {
|
||||
now.duration_since(start) < Duration::from_secs(1)
|
||||
&& now.duration_since(last) < Duration::from_millis(500)
|
||||
&& cursor == self.current_cursor()
|
||||
})
|
||||
{
|
||||
self.edit_history.typing_edit = Some(TypingEdit::Continue);
|
||||
return;
|
||||
}
|
||||
self.edit_history.typing_edit = typing.then(|| {
|
||||
selection.map_or(TypingEdit::Start, |range| {
|
||||
TypingEdit::ReplaceSelection(range.start)
|
||||
})
|
||||
});
|
||||
self.begin_edit_transaction();
|
||||
}
|
||||
|
||||
/// Once buffered keys are classified as a paste, separate them from preceding typing.
|
||||
pub(super) fn begin_detected_paste_edit(&mut self) {
|
||||
if self.config.undo_enabled && !self.draft.textarea.is_vim_enabled() {
|
||||
self.edit_history.typing_edit = None;
|
||||
self.edit_history.typing = None;
|
||||
self.begin_edit_transaction();
|
||||
}
|
||||
}
|
||||
|
||||
/// Reuse the pre-selection draft if the retroactive prefix began with a replacement.
|
||||
pub(super) fn begin_retroactive_paste_edit(&mut self, start: usize) {
|
||||
let replacement = self.config.undo_enabled
|
||||
&& !self.draft.textarea.is_vim_enabled()
|
||||
&& self
|
||||
.edit_history
|
||||
.typing
|
||||
.is_some_and(|(_, _, _, selection)| selection == Some(start));
|
||||
if replacement && let Some(snapshot) = self.edit_history.undo.pop_back() {
|
||||
self.edit_history.pending = Some(snapshot);
|
||||
self.edit_history.typing_edit = None;
|
||||
self.edit_history.typing = None;
|
||||
} else {
|
||||
self.begin_detected_paste_edit();
|
||||
}
|
||||
}
|
||||
|
||||
/// A separator can promote a held character or extend an already detected paste.
|
||||
pub(super) fn begin_promoted_paste_edit(&mut self) {
|
||||
if self.config.undo_enabled && !self.draft.textarea.is_vim_enabled() {
|
||||
self.edit_history.typing_edit = None;
|
||||
self.edit_history.typing = None;
|
||||
if self.edit_history.pending.is_none() {
|
||||
self.begin_edit_transaction();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Snapshot only keys that can begin or complete a Vim edit transaction.
|
||||
pub(super) fn begin_vim_edit(&mut self, event: KeyEvent) {
|
||||
if !self.draft.textarea.is_vim_enabled()
|
||||
@@ -157,30 +327,35 @@ impl ChatComposer {
|
||||
|
||||
/// Start one standalone draft edit without splitting an active Vim command.
|
||||
pub(super) fn begin_direct_edit(&mut self) -> bool {
|
||||
if !self.draft.textarea.is_vim_enabled()
|
||||
if (!self.config.undo_enabled && !self.draft.textarea.is_vim_enabled())
|
||||
|| self.draft.textarea.is_vim_operator_pending()
|
||||
|| self.edit_history.pending.is_some()
|
||||
|| self.edit_history.typing_edit.is_some()
|
||||
|| self.history_search.is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
self.edit_history.typing = None;
|
||||
self.edit_history.backspace = None;
|
||||
self.begin_edit_transaction();
|
||||
if self.edit_history.pending.is_none() {
|
||||
return false;
|
||||
}
|
||||
let mut vim_state = VimPersistentState::default();
|
||||
self.draft
|
||||
.textarea
|
||||
.swap_vim_persistent_state(&mut vim_state);
|
||||
vim_state.commands.last_change.clear();
|
||||
self.draft
|
||||
.textarea
|
||||
.swap_vim_persistent_state(&mut vim_state);
|
||||
if self.draft.textarea.is_vim_enabled() {
|
||||
let mut vim_state = VimPersistentState::default();
|
||||
self.draft
|
||||
.textarea
|
||||
.swap_vim_persistent_state(&mut vim_state);
|
||||
vim_state.commands.last_change.clear();
|
||||
self.draft
|
||||
.textarea
|
||||
.swap_vim_persistent_state(&mut vim_state);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn begin_edit_transaction(&mut self) {
|
||||
pub(super) fn begin_edit_transaction(&mut self) {
|
||||
let visible_bytes = self.draft.textarea.text().len();
|
||||
let paste_bytes = self
|
||||
.draft
|
||||
@@ -202,14 +377,34 @@ impl ChatComposer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Commit a complete normal-mode command or one insert-mode session.
|
||||
pub(super) fn finish_edit(&mut self) {
|
||||
if !self.draft.textarea.is_vim_normal_mode()
|
||||
|| self.draft.textarea.is_vim_operator_pending()
|
||||
/// Commit an ordinary edit or a complete Vim command or insert session.
|
||||
pub(in crate::bottom_pane) fn finish_edit(&mut self) {
|
||||
if self.draft.textarea.is_vim_enabled()
|
||||
&& (!self.draft.textarea.is_vim_normal_mode()
|
||||
|| self.draft.textarea.is_vim_operator_pending())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if !self.draft.textarea.is_vim_enabled() && self.draft.paste_burst.is_active() {
|
||||
return;
|
||||
}
|
||||
let typing_edit = self.edit_history.typing_edit.take();
|
||||
if let Some(TypingEdit::BackspaceContinue(previous)) = typing_edit {
|
||||
let cursor = self.current_cursor();
|
||||
self.edit_history.backspace = (cursor < previous).then(|| (Instant::now(), cursor));
|
||||
return;
|
||||
}
|
||||
if matches!(typing_edit, Some(TypingEdit::Continue)) {
|
||||
let cursor = self.current_cursor();
|
||||
self.edit_history.typing =
|
||||
self.edit_history
|
||||
.typing
|
||||
.and_then(|(start, _, previous, selection)| {
|
||||
(cursor > previous).then_some((start, Instant::now(), cursor, selection))
|
||||
});
|
||||
return;
|
||||
}
|
||||
let Some(snapshot) = self.edit_history.pending.take() else {
|
||||
return;
|
||||
};
|
||||
@@ -217,12 +412,28 @@ impl ChatComposer {
|
||||
let mut current = self.snapshot_draft();
|
||||
current.cursor = snapshot.cursor;
|
||||
if snapshot == current {
|
||||
self.edit_history.typing = None;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let now = Instant::now();
|
||||
self.edit_history.redo.clear();
|
||||
self.edit_history.undo.push_back(snapshot);
|
||||
self.edit_history.backspace = matches!(typing_edit, Some(TypingEdit::BackspaceStart))
|
||||
.then(|| (now, self.current_cursor()));
|
||||
self.edit_history.typing = match typing_edit {
|
||||
Some(TypingEdit::Start) => Some((now, now, self.current_cursor(), None)),
|
||||
Some(TypingEdit::ReplaceSelection(start)) => {
|
||||
Some((now, now, self.current_cursor(), Some(start)))
|
||||
}
|
||||
Some(
|
||||
TypingEdit::Continue
|
||||
| TypingEdit::BackspaceStart
|
||||
| TypingEdit::BackspaceContinue(_),
|
||||
)
|
||||
| None => None,
|
||||
};
|
||||
self.edit_history.trim();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -873,3 +873,161 @@ fn editor_actions_insert_shell_prefixes() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_composer_undo_redo_restores_grouped_typing_and_paste() {
|
||||
snapshot_composer_state_with_width(
|
||||
"ordinary_composer_undo",
|
||||
/*width*/ 60,
|
||||
/*enhanced_keys_supported*/ true,
|
||||
|composer| {
|
||||
let undo = KeyEvent::new(KeyCode::F(7), KeyModifiers::NONE);
|
||||
let redo = KeyEvent::new(KeyCode::F(7), KeyModifiers::SHIFT);
|
||||
for ch in ['d', 'r'] {
|
||||
composer.handle_key_event(KeyCode::Char(ch).into());
|
||||
composer.handle_paste_burst_flush(
|
||||
std::time::Instant::now() + PasteBurst::recommended_active_flush_delay(),
|
||||
);
|
||||
}
|
||||
composer.set_disable_paste_burst(/*disabled*/ true);
|
||||
keys(composer, "aft");
|
||||
composer.handle_key_event(KeyCode::Backspace.into());
|
||||
composer.handle_key_event(undo);
|
||||
assert_eq!(composer.current_text(), "draft");
|
||||
composer.handle_paste("x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1));
|
||||
composer.handle_key_event(undo);
|
||||
composer.handle_key_event(undo);
|
||||
assert_eq!(composer.current_text(), "");
|
||||
composer.handle_key_event(redo);
|
||||
composer.handle_key_event(redo);
|
||||
composer.clear_for_ctrl_c();
|
||||
composer.handle_key_event(undo);
|
||||
composer.handle_key_event(undo);
|
||||
composer.set_vim_enabled(/*enabled*/ true);
|
||||
keys(composer, "u");
|
||||
assert_eq!(composer.current_text(), "");
|
||||
ctrl_r(composer);
|
||||
composer.set_vim_enabled(/*enabled*/ false);
|
||||
},
|
||||
);
|
||||
let (mut composer, _) = new_test_composer();
|
||||
composer.set_disable_paste_burst(/*disabled*/ true);
|
||||
let original = "a".repeat(70);
|
||||
composer.set_text_content(original.clone(), Vec::new(), Vec::new());
|
||||
composer.set_current_cursor(original.len());
|
||||
for _ in 0..65 {
|
||||
composer.handle_key_event(KeyCode::Backspace.into());
|
||||
}
|
||||
keys(&mut composer, "x");
|
||||
let undo = KeyEvent::from(KeyCode::F(7));
|
||||
let redo = KeyEvent::new(KeyCode::F(7), KeyModifiers::SHIFT);
|
||||
composer.handle_key_event(undo);
|
||||
assert_eq!(composer.current_text(), "aaaaa");
|
||||
composer.handle_key_event(undo);
|
||||
assert_eq!(composer.current_text(), original);
|
||||
composer.handle_key_event(redo);
|
||||
assert_eq!(composer.current_text(), "aaaaa");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detected_paste_is_separate_from_preceding_typing() {
|
||||
for (input, pasted) in [
|
||||
(vec![KeyCode::Char('X'), KeyCode::Char('Y')], "XY"),
|
||||
(
|
||||
vec![KeyCode::Char('X'), KeyCode::Enter, KeyCode::Char('Y')],
|
||||
"X\nY",
|
||||
),
|
||||
(
|
||||
vec![KeyCode::Char('X'), KeyCode::Tab, KeyCode::Char('Y')],
|
||||
"X\tY",
|
||||
),
|
||||
] {
|
||||
let (mut composer, _receiver) = new_test_composer();
|
||||
composer.handle_key_event(KeyCode::Char('a').into());
|
||||
composer.handle_paste_burst_flush(
|
||||
std::time::Instant::now() + PasteBurst::recommended_active_flush_delay(),
|
||||
);
|
||||
for key in input {
|
||||
composer.handle_key_event(key.into());
|
||||
}
|
||||
composer.handle_key_event(KeyEvent::from(KeyCode::F(7)));
|
||||
assert_eq!(composer.current_text(), "a");
|
||||
composer.handle_key_event(KeyEvent::new(KeyCode::F(7), KeyModifiers::SHIFT));
|
||||
assert_eq!(composer.current_text(), format!("a{pasted}"));
|
||||
}
|
||||
|
||||
// Non-ASCII input replaces a selection before it can be recognized as a paste.
|
||||
use crossterm::event::MouseButton;
|
||||
use crossterm::event::MouseEvent;
|
||||
use crossterm::event::MouseEventKind;
|
||||
use ratatui::widgets::StatefulWidgetRef;
|
||||
let (mut composer, _) = new_test_composer();
|
||||
composer.set_text_content("abcdef".into(), Vec::new(), Vec::new());
|
||||
let area = ratatui::layout::Rect::new(0, 0, 40, 4);
|
||||
let mut state = super::super::super::textarea::TextAreaState::default();
|
||||
let mut buffer = ratatui::buffer::Buffer::empty(area);
|
||||
(&composer.draft.textarea).render_ref(area, &mut buffer, &mut state);
|
||||
for (kind, column) in [
|
||||
(MouseEventKind::Down(MouseButton::Left), 1),
|
||||
(MouseEventKind::Drag(MouseButton::Left), 3),
|
||||
] {
|
||||
composer.draft.textarea.handle_mouse(
|
||||
MouseEvent {
|
||||
kind,
|
||||
column,
|
||||
row: 0,
|
||||
modifiers: KeyModifiers::NONE,
|
||||
},
|
||||
state,
|
||||
);
|
||||
}
|
||||
let before = composer.snapshot_draft();
|
||||
keys(&mut composer, "日\u{3000}語");
|
||||
composer.handle_key_event(KeyCode::F(7).into());
|
||||
assert_eq!(composer.snapshot_draft(), before);
|
||||
composer.handle_key_event(KeyEvent::new(KeyCode::F(7), KeyModifiers::SHIFT));
|
||||
assert_eq!(composer.current_text(), "a日\u{3000}語def");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deferred_command_preserves_undo_until_consumed() {
|
||||
for command in ["/review", "/fork"] {
|
||||
let (mut composer, _) = new_test_composer();
|
||||
composer.handle_paste(command.to_owned());
|
||||
assert!(matches!(
|
||||
composer.handle_key_event(KeyCode::Enter.into()).0,
|
||||
InputResult::Command(_)
|
||||
));
|
||||
composer.handle_key_event(KeyCode::F(7).into());
|
||||
assert_eq!(composer.current_text(), "");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabling_ordinary_undo_discards_vim_redo_on_mode_change() {
|
||||
let mut composer = vim_composer("abc");
|
||||
composer.config.undo_enabled = false;
|
||||
keys(&mut composer, "x");
|
||||
keys(&mut composer, "u");
|
||||
composer.set_vim_enabled(/*enabled*/ false);
|
||||
keys(&mut composer, "z");
|
||||
let answer = composer.current_text();
|
||||
composer.set_vim_enabled(/*enabled*/ true);
|
||||
ctrl_r(&mut composer);
|
||||
assert_eq!(composer.current_text(), answer);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn altgr_delete_word_is_an_undoable_deletion() {
|
||||
let (mut composer, _) = new_test_composer();
|
||||
composer.set_disable_paste_burst(/*disabled*/ true);
|
||||
keys(&mut composer, "hello world");
|
||||
composer.handle_key_event(KeyEvent::new(
|
||||
KeyCode::Char('h'),
|
||||
KeyModifiers::CONTROL | KeyModifiers::ALT,
|
||||
));
|
||||
assert_eq!(composer.current_text(), "hello ");
|
||||
composer.handle_key_event(KeyCode::F(7).into());
|
||||
assert_eq!(composer.current_text(), "hello world");
|
||||
}
|
||||
|
||||
@@ -92,6 +92,9 @@ impl ChatComposer {
|
||||
/// Classify an explicit paste before integrating text shared with the buffered key path.
|
||||
pub fn handle_paste(&mut self, pasted: String) -> bool {
|
||||
self.flush_pending_paste_burst();
|
||||
if !self.draft.textarea.is_vim_enabled() {
|
||||
self.finish_edit();
|
||||
}
|
||||
self.note_sparkle_paste(&pasted);
|
||||
self.apply_paste(pasted)
|
||||
}
|
||||
@@ -168,6 +171,9 @@ impl ChatComposer {
|
||||
match self.draft.paste_burst.flush_if_due(now) {
|
||||
FlushResult::Paste(pasted) => {
|
||||
self.apply_paste(pasted);
|
||||
if !self.draft.textarea.is_vim_enabled() {
|
||||
self.finish_edit();
|
||||
}
|
||||
true
|
||||
}
|
||||
FlushResult::Typed(ch) => {
|
||||
@@ -177,7 +183,7 @@ impl ChatComposer {
|
||||
self.draft.textarea.replace_range(space..space + 1, "");
|
||||
}
|
||||
self.insert_str(ch.to_string().as_str());
|
||||
if started_edit {
|
||||
if started_edit || !self.draft.textarea.is_vim_enabled() {
|
||||
self.finish_edit();
|
||||
}
|
||||
true
|
||||
@@ -294,6 +300,7 @@ impl ChatComposer {
|
||||
.paste_burst
|
||||
.append_control_char_if_active(separator, now)
|
||||
{
|
||||
self.begin_promoted_paste_edit();
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ impl ChatComposer {
|
||||
.paste_burst
|
||||
.append_control_char_if_active('\n', now)
|
||||
{
|
||||
self.begin_promoted_paste_edit();
|
||||
return true;
|
||||
}
|
||||
if self
|
||||
@@ -105,6 +106,8 @@ impl ChatComposer {
|
||||
self.popups.active = ActivePopup::None;
|
||||
}
|
||||
self.set_disable_paste_burst(/*disabled*/ true);
|
||||
let history_handled = matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
|
||||
&& self.handle_edit_history_key(key);
|
||||
// Expand in reverse order so remaining ranges stay valid. Textarea replacement
|
||||
// preserves the cursor and other elements, including images and mentions.
|
||||
let pending_pastes = std::mem::take(&mut self.draft.pending_pastes);
|
||||
@@ -120,6 +123,10 @@ impl ChatComposer {
|
||||
}
|
||||
}
|
||||
}
|
||||
if history_handled {
|
||||
self.draft.textarea_state.get_mut().follow_cursor();
|
||||
return InputResult::None;
|
||||
}
|
||||
if mode == RestrictedInputMode::UnavailableThread
|
||||
&& self.draft.textarea.wants_vim_search_key(key)
|
||||
&& matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
|
||||
@@ -153,6 +160,7 @@ impl ChatComposer {
|
||||
slash_input::SlashPopupInputMode::UnavailableThread,
|
||||
)
|
||||
.0;
|
||||
self.reset_vim_mode_after_successful_dispatch(&result);
|
||||
self.sync_command_popup(/*allow*/ true);
|
||||
return result;
|
||||
}
|
||||
@@ -194,10 +202,12 @@ impl ChatComposer {
|
||||
if matches!(command, SlashCommand::Warnings | SlashCommand::Config | SlashCommand::Quit | SlashCommand::Exit)
|
||||
|| mode == RestrictedInputMode::UnavailableThread && command.available_when_thread_unavailable())
|
||||
{
|
||||
return self
|
||||
let result = self
|
||||
.try_dispatch_bare_slash_command()
|
||||
.or_else(|| self.try_dispatch_slash_command_with_args())
|
||||
.unwrap_or(InputResult::None);
|
||||
self.reset_vim_mode_after_successful_dispatch(&result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -226,7 +236,11 @@ impl ChatComposer {
|
||||
self.draft.textarea_state.get_mut().follow_cursor();
|
||||
self.before_sparkle_editor_key(key)
|
||||
};
|
||||
self.begin_composer_key_edit(key);
|
||||
let (result, _) = self.handle_input_basic(key);
|
||||
if !self.draft.textarea.is_vim_enabled() {
|
||||
self.finish_edit();
|
||||
}
|
||||
self.after_sparkle_key(before, &result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,7 +195,17 @@ fn unavailable_thread_dispatches_recovery_and_local_commands() {
|
||||
] {
|
||||
let (mut composer, _) = new_test_composer();
|
||||
composer.blocks_direct_input = true;
|
||||
composer.set_text_content(format!("/{}", command.command()), Vec::new(), Vec::new());
|
||||
let text = format!("/{}", command.command());
|
||||
if command == SlashCommand::Status {
|
||||
for ch in text.chars() {
|
||||
composer.handle_restricted_key(
|
||||
KeyCode::Char(ch).into(),
|
||||
RestrictedInputMode::UnavailableThread,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
composer.set_text_content(text, Vec::new(), Vec::new());
|
||||
}
|
||||
assert_eq!(
|
||||
composer.handle_restricted_key(
|
||||
KeyEvent::from(KeyCode::Enter),
|
||||
@@ -204,6 +214,13 @@ fn unavailable_thread_dispatches_recovery_and_local_commands() {
|
||||
InputResult::Command(command),
|
||||
);
|
||||
assert_eq!(composer.current_text(), "");
|
||||
if command == SlashCommand::Status {
|
||||
composer.handle_restricted_key(
|
||||
KeyCode::F(7).into(),
|
||||
RestrictedInputMode::UnavailableThread,
|
||||
);
|
||||
assert_eq!(composer.current_text(), "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -396,3 +413,16 @@ fn unavailable_thread_expands_pasted_commands_without_dispatching() {
|
||||
);
|
||||
assert_eq!(composer.current_text(), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnected_edit_invalidates_ordinary_redo() {
|
||||
let (mut composer, _) = new_test_composer();
|
||||
composer.set_disable_paste_burst(/*disabled*/ true);
|
||||
composer.handle_key_event(KeyCode::Char('a').into());
|
||||
let undo = KeyEvent::new(KeyCode::F(7), KeyModifiers::NONE);
|
||||
composer.handle_restricted_key(undo, RestrictedInputMode::Disconnected);
|
||||
assert_eq!(composer.current_text(), "");
|
||||
composer.handle_restricted_key(KeyCode::Char('b').into(), RestrictedInputMode::Disconnected);
|
||||
composer.handle_key_event(KeyEvent::new(KeyCode::F(7), KeyModifiers::SHIFT));
|
||||
assert_eq!(composer.current_text(), "b");
|
||||
}
|
||||
|
||||
@@ -852,7 +852,13 @@ impl BottomPane {
|
||||
self.push_view(Box::new(modal));
|
||||
}
|
||||
|
||||
fn is_composer_activity_key(key: KeyEvent) -> bool {
|
||||
fn is_composer_activity_key(&self, key: KeyEvent) -> bool {
|
||||
if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
|
||||
&& (self.keymap.composer.undo.is_pressed(key)
|
||||
|| self.keymap.composer.redo.is_pressed(key))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat)
|
||||
&& !key_hint::has_ctrl_or_alt(key.modifiers)
|
||||
&& matches!(
|
||||
@@ -873,7 +879,7 @@ impl BottomPane {
|
||||
) -> InputResult {
|
||||
if mode == RestrictedInputMode::DraftHandoff {
|
||||
let result = self.composer.handle_restricted_key(key, mode);
|
||||
if Self::is_composer_activity_key(key) {
|
||||
if self.is_composer_activity_key(key) {
|
||||
self.record_composer_activity_at(Instant::now());
|
||||
}
|
||||
self.request_redraw();
|
||||
@@ -917,7 +923,7 @@ impl BottomPane {
|
||||
view.observe_key_event_while_covered(key_event, routed_key);
|
||||
}
|
||||
}
|
||||
let records_composer_activity = Self::is_composer_activity_key(key_event);
|
||||
let records_composer_activity = self.is_composer_activity_key(key_event);
|
||||
if self.warnings_active() {
|
||||
if matches!(key_event.kind, KeyEventKind::Press | KeyEventKind::Repeat) {
|
||||
self.record_composer_activity_at(Instant::now());
|
||||
@@ -2345,6 +2351,9 @@ impl BottomPane {
|
||||
/// Commit accepted typing before snapshotting the target of an asynchronous paste.
|
||||
pub(crate) fn prepare_composer_clipboard_paste(&mut self) {
|
||||
self.composer.flush_pending_paste_burst();
|
||||
if !self.composer.is_vim_enabled() {
|
||||
self.composer.finish_edit();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_in_paste_burst(&self) -> bool {
|
||||
@@ -2766,6 +2775,18 @@ mod tests {
|
||||
test_pane_with_disable_paste_burst(app_event_tx, /*disable_paste_burst*/ false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipboard_image_undo_preserves_buffered_typing() {
|
||||
let (tx, _) = unbounded_channel();
|
||||
let mut pane = test_pane(AppEventSender::new(tx));
|
||||
pane.composer.handle_key_event(KeyCode::Char('a').into());
|
||||
pane.prepare_composer_clipboard_paste();
|
||||
pane.attach_image(std::path::PathBuf::from("example.png"));
|
||||
pane.composer.handle_key_event(KeyCode::F(7).into());
|
||||
assert_eq!(pane.composer.current_text(), "a");
|
||||
assert!(pane.composer.local_image_paths().is_empty());
|
||||
}
|
||||
|
||||
fn test_pane_with_disable_paste_burst(
|
||||
app_event_tx: AppEventSender,
|
||||
disable_paste_burst: bool,
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
---
|
||||
source: tui/src/bottom_pane/chat_composer.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
" "
|
||||
"› draft "
|
||||
" "
|
||||
" "
|
||||
" "
|
||||
" "
|
||||
" "
|
||||
" "
|
||||
" 100% context left "
|
||||
@@ -104,6 +104,14 @@ impl BottomPane {
|
||||
self.composer.sync_popups();
|
||||
}
|
||||
|
||||
pub(crate) fn startup_undo_draft(&mut self) -> Option<super::chat_composer::ComposerDraft> {
|
||||
self.composer.capture_startup_undo()
|
||||
}
|
||||
|
||||
pub(crate) fn record_startup_undo(&mut self, destination: super::chat_composer::ComposerDraft) {
|
||||
self.composer.record_startup_undo(destination);
|
||||
}
|
||||
|
||||
/// Preserve startup-local history and the newest protected-prompt activity timestamp.
|
||||
pub(crate) fn restore_startup_composer_state(
|
||||
&mut self,
|
||||
|
||||
@@ -71,6 +71,9 @@ impl ChatWidget {
|
||||
|| !startup_message.local_images.is_empty()
|
||||
|| !startup_message.remote_image_urls.is_empty()
|
||||
|| !draft.pending_pastes.is_empty();
|
||||
let startup_undo = (startup_has_content && !self.local_settings.tui.vim_mode_default)
|
||||
.then(|| self.bottom_pane.startup_undo_draft())
|
||||
.flatten();
|
||||
|
||||
let cursor = if existing_has_content && startup_has_content {
|
||||
let mut used_paste_placeholders = HashSet::new();
|
||||
@@ -118,6 +121,9 @@ impl ChatWidget {
|
||||
);
|
||||
draft.cursor
|
||||
};
|
||||
if let Some(destination) = startup_undo {
|
||||
self.bottom_pane.record_startup_undo(destination);
|
||||
}
|
||||
self.bottom_pane.set_composer_cursor(cursor);
|
||||
self.bottom_pane.restore_startup_composer_state(
|
||||
draft.last_composer_activity_at,
|
||||
|
||||
@@ -226,12 +226,15 @@ impl ChatWidget {
|
||||
{
|
||||
return KeyEventAction::None;
|
||||
}
|
||||
if !self.startup_submission_has_protected_input()
|
||||
&& !self.blocks_direct_input
|
||||
&& self.bottom_pane.composer_input_enabled()
|
||||
&& let Some(action) =
|
||||
self.image_paste_key_action(key, ClipboardPasteContext::DraftHandoff)
|
||||
{
|
||||
let protected = self.startup_submission_has_protected_input()
|
||||
|| self.blocks_direct_input
|
||||
|| !self.bottom_pane.composer_input_enabled();
|
||||
let composer = &self.bottom_pane.keymap().composer;
|
||||
if protected && (composer.undo.is_pressed(key) || composer.redo.is_pressed(key)) {
|
||||
return KeyEventAction::None;
|
||||
}
|
||||
let context = ClipboardPasteContext::DraftHandoff;
|
||||
if !protected && let Some(action) = self.image_paste_key_action(key, context) {
|
||||
return action;
|
||||
}
|
||||
self.bottom_pane.handle_restricted_key(key, mode);
|
||||
|
||||
@@ -1472,6 +1472,12 @@ async fn startup_draft_handoff_preserves_cursor_and_large_paste() {
|
||||
chat.restore_startup_draft(startup_draft.clone());
|
||||
|
||||
assert_eq!(chat.bottom_pane.composer_draft_snapshot(), startup_draft);
|
||||
chat.handle_key_event(KeyEvent::from(KeyCode::F(7)));
|
||||
assert!(chat.bottom_pane.composer_is_empty());
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::F(7), KeyModifiers::SHIFT));
|
||||
let mut restored = chat.bottom_pane.composer_draft_snapshot();
|
||||
restored.last_composer_activity_at = startup_draft.last_composer_activity_at;
|
||||
assert_eq!(restored, startup_draft);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1497,6 +1503,8 @@ async fn startup_draft_handoff_merges_existing_prompt_images_and_large_pastes()
|
||||
);
|
||||
let initial_paste = "y".repeat(/*n*/ 1_001);
|
||||
chat.bottom_pane.handle_paste(initial_paste.clone());
|
||||
chat.bottom_pane
|
||||
.set_composer_cursor(image_placeholder.len() + 1);
|
||||
let existing_draft = chat.bottom_pane.composer_draft_snapshot();
|
||||
let existing_placeholder = existing_draft.pending_pastes[0].0.clone();
|
||||
|
||||
@@ -1526,6 +1534,15 @@ async fn startup_draft_handoff_merges_existing_prompt_images_and_large_pastes()
|
||||
}],
|
||||
)
|
||||
);
|
||||
let merged = chat.bottom_pane.composer_draft_snapshot();
|
||||
chat.handle_key_event(KeyEvent::from(KeyCode::F(7)));
|
||||
let mut undone = chat.bottom_pane.composer_draft_snapshot();
|
||||
undone.last_composer_activity_at = existing_draft.last_composer_activity_at;
|
||||
assert_eq!(undone, existing_draft);
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::F(7), KeyModifiers::SHIFT));
|
||||
let mut redone = chat.bottom_pane.composer_draft_snapshot();
|
||||
redone.last_composer_activity_at = merged.last_composer_activity_at;
|
||||
assert_eq!(redone, merged);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -207,6 +207,8 @@ pub(crate) struct ComposerKeymap {
|
||||
pub(crate) history_search_previous: Vec<KeyBinding>,
|
||||
/// Move to the next match in reverse history search.
|
||||
pub(crate) history_search_next: Vec<KeyBinding>,
|
||||
pub(crate) undo: Vec<KeyBinding>,
|
||||
pub(crate) redo: Vec<KeyBinding>,
|
||||
}
|
||||
|
||||
/// Editor-specific keybindings used by the composer textarea.
|
||||
@@ -992,6 +994,8 @@ impl RuntimeKeymap {
|
||||
history_search_previous
|
||||
),
|
||||
history_search_next: resolve_local!(keymap, defaults, composer, history_search_next),
|
||||
undo: resolve_local!(keymap, defaults, composer, undo),
|
||||
redo: resolve_local!(keymap, defaults, composer, redo),
|
||||
};
|
||||
|
||||
let editor = Arc::new(EditorKeymap {
|
||||
@@ -1767,9 +1771,13 @@ impl RuntimeKeymap {
|
||||
approval,
|
||||
};
|
||||
|
||||
let vim_undo = KeymapActionId {
|
||||
context: KeymapContext::VimNormal,
|
||||
action: "undo",
|
||||
};
|
||||
let configured: Vec<_> = runtime_action_bindings(&resolved)
|
||||
.filter(|action| {
|
||||
action.id.context.overlaps(KeymapContext::VimNormal)
|
||||
action.id.overlaps(vim_undo)
|
||||
&& bindings::configured_binding_for_action(keymap, action.id)
|
||||
.is_some_and(Option::is_some)
|
||||
})
|
||||
@@ -1795,8 +1803,36 @@ impl RuntimeKeymap {
|
||||
let event = KeyEvent::new(code, modifiers);
|
||||
!configured.is_pressed(event)
|
||||
&& !resolved.chords.bindings.iter().any(|chord| {
|
||||
chord.action.context.overlaps(KeymapContext::VimNormal)
|
||||
&& chord.chord.prefix.is_press(event)
|
||||
chord.action.overlaps(vim_undo) && chord.chord.prefix.is_press(event)
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
let undo_action = KeymapActionId {
|
||||
context: KeymapContext::Composer,
|
||||
action: "undo",
|
||||
};
|
||||
let configured: Vec<_> = runtime_action_bindings(&resolved)
|
||||
.filter(|action| {
|
||||
action.id.overlaps(undo_action)
|
||||
&& bindings::configured_binding_for_action(keymap, action.id)
|
||||
.is_some_and(Option::is_some)
|
||||
})
|
||||
.flat_map(|action| action.bindings.iter().copied())
|
||||
.collect();
|
||||
for (setting, bindings) in [
|
||||
(keymap.composer.undo.as_ref(), &mut resolved.composer.undo),
|
||||
(keymap.composer.redo.as_ref(), &mut resolved.composer.redo),
|
||||
] {
|
||||
if setting.is_none() {
|
||||
bindings.retain(|binding| {
|
||||
let (code, modifiers) = binding.parts();
|
||||
let event = KeyEvent::new(code, modifiers);
|
||||
!configured.is_pressed(event)
|
||||
&& !(keymap.global.leader.is_some()
|
||||
&& resolved.chords.leader.is_pressed(event))
|
||||
&& !resolved.chords.bindings.iter().any(|chord| {
|
||||
chord.action.overlaps(undo_action) && chord.chord.prefix.is_press(event)
|
||||
})
|
||||
});
|
||||
}
|
||||
@@ -1826,6 +1862,23 @@ impl RuntimeKeymap {
|
||||
/// both `?` and `shift-?`) because terminals disagree on whether SHIFT is
|
||||
/// preserved for certain printable/control chords.
|
||||
fn built_in_defaults() -> Self {
|
||||
let undo_modifier = if cfg!(windows) {
|
||||
KeyModifiers::CONTROL
|
||||
} else {
|
||||
KeyModifiers::ALT
|
||||
};
|
||||
let mut undo = vec![KeyBinding::new(KeyCode::Char('z'), undo_modifier)];
|
||||
if cfg!(target_os = "macos") {
|
||||
undo.push(KeyBinding::new(KeyCode::Char('z'), KeyModifiers::SUPER));
|
||||
}
|
||||
undo.push(key_hint::plain(KeyCode::F(7)));
|
||||
let redo = undo
|
||||
.iter()
|
||||
.map(|binding| {
|
||||
let (code, modifiers) = binding.parts();
|
||||
KeyBinding::new(code, modifiers | KeyModifiers::SHIFT)
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
app: AppKeymap {
|
||||
change_host: Vec::new(),
|
||||
@@ -1889,6 +1942,8 @@ impl RuntimeKeymap {
|
||||
],
|
||||
history_search_previous: default_bindings![ctrl(KeyCode::Char('r'))],
|
||||
history_search_next: default_bindings![ctrl(KeyCode::Char('s'))],
|
||||
undo,
|
||||
redo,
|
||||
},
|
||||
editor: Arc::new(EditorKeymap {
|
||||
insert_newline: default_bindings![
|
||||
@@ -2175,6 +2230,8 @@ impl RuntimeKeymap {
|
||||
("global.change_host", &self.app.change_host),
|
||||
("chat.open_presets", &self.chat.open_presets),
|
||||
("chat.toggle_voice", &self.chat.toggle_voice),
|
||||
("composer.undo", &self.composer.undo),
|
||||
("composer.redo", &self.composer.redo),
|
||||
(
|
||||
"chat.previous_permission_mode",
|
||||
&self.chat.previous_permission_mode,
|
||||
@@ -2222,6 +2279,8 @@ impl RuntimeKeymap {
|
||||
("global.sidebar_down", &self.app.sidebar_down),
|
||||
("chat.open_presets", &self.chat.open_presets),
|
||||
("chat.toggle_voice", &self.chat.toggle_voice),
|
||||
("composer.undo", &self.composer.undo),
|
||||
("composer.redo", &self.composer.redo),
|
||||
] {
|
||||
if bindings.contains(&key_hint::ctrl(KeyCode::Char('z'))) {
|
||||
return Err(format!(
|
||||
@@ -2335,6 +2394,8 @@ impl RuntimeKeymap {
|
||||
"composer.history_search_next",
|
||||
self.composer.history_search_next.as_slice(),
|
||||
),
|
||||
("composer.undo", self.composer.undo.as_slice()),
|
||||
("composer.redo", self.composer.redo.as_slice()),
|
||||
];
|
||||
validate_unique("app", main_bindings)?;
|
||||
|
||||
@@ -2504,6 +2565,8 @@ impl RuntimeKeymap {
|
||||
),
|
||||
("chat.skip_question", self.chat.skip_question.as_slice()),
|
||||
("composer.submit", self.composer.submit.as_slice()),
|
||||
("composer.undo", self.composer.undo.as_slice()),
|
||||
("composer.redo", self.composer.redo.as_slice()),
|
||||
("toggle_vim_mode", self.app.toggle_vim_mode.as_slice()),
|
||||
("toggle_fast_mode", self.app.toggle_fast_mode.as_slice()),
|
||||
("toggle_raw_output", self.app.toggle_raw_output.as_slice()),
|
||||
|
||||
@@ -137,6 +137,14 @@ impl KeymapActionId {
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let edit = |id: Self| {
|
||||
id.context == KeymapContext::Composer && matches!(id.action, "undo" | "redo")
|
||||
};
|
||||
if edit(self) && other.context.allows_plain_chord_prefix()
|
||||
|| edit(other) && self.context.allows_plain_chord_prefix()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match (self.context, other.context) {
|
||||
// Presets cannot open while a list owns input.
|
||||
(Chat, List) => self.action != "open_presets",
|
||||
@@ -362,6 +370,8 @@ define_runtime_action_bindings! {
|
||||
toggle_shortcuts,
|
||||
history_search_previous,
|
||||
history_search_next,
|
||||
undo,
|
||||
redo,
|
||||
],
|
||||
"editor" => Editor, editor, editor [
|
||||
insert_newline,
|
||||
|
||||
@@ -64,10 +64,19 @@ const SIDEBAR_CHOOSER: u32 = 1 << 27;
|
||||
const SIDEBAR_RESIZE: u32 = 1 << 28;
|
||||
const FOCUSED_SIDEBAR: u32 = 1 << 29;
|
||||
const TRANSCRIPT_SELECT: u32 = 1 << 30;
|
||||
const COMPOSER_EDIT_ONLY: u32 = 1 << 31;
|
||||
|
||||
const TRANSCRIPT_BROWSING: u32 = 1 << 14;
|
||||
|
||||
impl KeymapContextSet {
|
||||
pub(crate) const fn composer_edit_only() -> Self {
|
||||
Self(COMPOSER_EDIT_ONLY)
|
||||
}
|
||||
|
||||
pub(crate) const fn without_composer_edits(self) -> Self {
|
||||
Self(self.0 | COMPOSER_EDIT_ONLY)
|
||||
}
|
||||
|
||||
pub(crate) const fn new(context: KeymapContext) -> Self {
|
||||
Self(context_bit(context))
|
||||
}
|
||||
@@ -211,6 +220,13 @@ impl KeymapContextSet {
|
||||
|
||||
/// Whether this input path can dispatch the action, including focus-specific exclusions.
|
||||
pub(crate) fn contains_action(self, action: KeymapActionId) -> bool {
|
||||
if self.0 & COMPOSER_EDIT_ONLY != 0 && action.context == KeymapContext::Composer {
|
||||
let edit = matches!(action.action, "undo" | "redo");
|
||||
return edit != self.contains(KeymapContext::Composer);
|
||||
}
|
||||
if action.context == KeymapContext::Composer && matches!(action.action, "undo" | "redo") {
|
||||
return self.contains(KeymapContext::Composer) && self.contains(KeymapContext::Editor);
|
||||
}
|
||||
if action.context == KeymapContext::Pager && action.action == "mark_markdown" {
|
||||
return self.0 & TRANSCRIPT_SELECT != 0;
|
||||
}
|
||||
|
||||
@@ -635,3 +635,16 @@ fn warning_context_keeps_local_chords_ahead_of_copy_and_hides_unreachable_hints(
|
||||
assert!(runtime.list.jump_bottom.is_pressed(event));
|
||||
assert!(!runtime.app.copy.is_pressed(event));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_undo_defaults_yield_without_shadowing_vim_redo() {
|
||||
let mut config = TuiKeymap::default();
|
||||
config.global.leader = Some(binding("f7"));
|
||||
config.composer.history_search_previous = Some(binding("alt-h"));
|
||||
config.composer.redo = Some(binding("ctrl-r f6"));
|
||||
let runtime = RuntimeKeymap::from_config(&config).unwrap();
|
||||
let undo = KeyEvent::new(KeyCode::F(7), KeyModifiers::NONE);
|
||||
let redo = KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL);
|
||||
assert!(!runtime.composer.undo.is_pressed(undo));
|
||||
assert!(runtime.vim_normal.redo.is_pressed(redo));
|
||||
}
|
||||
|
||||
@@ -168,6 +168,8 @@ define_keymap_actions! {
|
||||
toggle_shortcuts => "Show or hide the composer shortcut overlay.",
|
||||
history_search_previous => "Open history search or move to the previous match.",
|
||||
history_search_next => "Move to the next history search match.",
|
||||
undo => "Undo the last composer edit.",
|
||||
redo => "Redo the last composer edit.",
|
||||
}
|
||||
editor "Editor" {
|
||||
insert_newline => "Insert a newline in the editor.",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ expression: "render_picker(params, 120)"
|
||||
|
||||
Keymap
|
||||
All configurable shortcuts.
|
||||
154 actions, 1 customized, 5 unbound.
|
||||
156 actions, 1 customized, 5 unbound.
|
||||
|
||||
All Common Customized (1) Unbound (5) App Composer Editor Vim Navigation Agents Approval ›
|
||||
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ expression: "render_picker(params, 120)"
|
||||
|
||||
Keymap
|
||||
All configurable shortcuts.
|
||||
155 actions, 0 customized, 6 unbound.
|
||||
157 actions, 0 customized, 6 unbound.
|
||||
|
||||
All Common Customized (0) Unbound (6) App Composer Editor Vim Navigation Agents Approval ›
|
||||
|
||||
|
||||
+2
-2
@@ -2,12 +2,12 @@
|
||||
source: tui/src/keymap_setup.rs
|
||||
expression: snapshot
|
||||
---
|
||||
tab: All (154 selectable)
|
||||
tab: All (156 selectable)
|
||||
tab: Common (20 selectable)
|
||||
tab: Customized (0) (0 selectable)
|
||||
tab: Unbound (5) (5 selectable)
|
||||
tab: App (22 selectable)
|
||||
tab: Composer (5 selectable)
|
||||
tab: Composer (7 selectable)
|
||||
tab: Editor (17 selectable)
|
||||
tab: Vim (69 selectable)
|
||||
tab: Navigation (22 selectable)
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ expression: "render_picker(params, 120)"
|
||||
|
||||
Keymap
|
||||
All configurable shortcuts.
|
||||
154 actions, 1 customized, 8 unbound.
|
||||
156 actions, 1 customized, 8 unbound.
|
||||
|
||||
All Common Customized (1) Unbound (8) App Composer Editor Vim Navigation Agents Approval ›
|
||||
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ expression: "render_picker(params, 78)"
|
||||
|
||||
Keymap
|
||||
All configurable shortcuts.
|
||||
154 actions, 0 customized, 5 unbound.
|
||||
156 actions, 0 customized, 5 unbound.
|
||||
|
||||
All Common Customized (0) Unbound (5) App Composer Editor ›
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ expression: "render_picker(params, 120)"
|
||||
|
||||
Keymap
|
||||
All configurable shortcuts.
|
||||
154 actions, 0 customized, 5 unbound.
|
||||
156 actions, 0 customized, 5 unbound.
|
||||
|
||||
All Common Customized (0) Unbound (5) App Composer Editor Vim Navigation Agents Approval ›
|
||||
|
||||
|
||||
Reference in New Issue
Block a user