Lightweight coding agent that runs in your terminal
Rust
Continue Markdown blockquotes when pasting multiline text (#49357)
Benjamin Carlsson1983c48fd186
diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rsindex 72722559fc..0988bf7cd1 100644--- a/codex-rs/tui/src/bottom_pane/chat_composer.rs+++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs@@ -114,6 +114,7 @@//!//! # Submission and Prompt Expansion//!+//! Multiline pastes continue blockquote prefixes.//! `Enter` submits immediately. `Tab` requests queuing while a task is running; if no task is//! running, `Tab` submits just like Enter so input is never dropped.//! Vim Replace shares Insert's composer actions; only textarea editing differs.@@ -562,6 +563,7 @@ pub(crate) struct ChatComposerConfig {pub(crate) shell_commands_enabled: bool,/// Whether pasting a file path can attach local images.pub(crate) image_paste_enabled: bool,+ pub(crate) blockquote_paste_enabled: bool,/// Strip leading and trailing whitespace from submissions.pub(crate) trim_submission: bool,/// Embedded editors reset Vim only when their owner accepts the answer.@@ -575,6 +577,7 @@ impl Default for ChatComposerConfig {slash_commands_enabled: true,shell_commands_enabled: true,image_paste_enabled: true,+ blockquote_paste_enabled: true,trim_submission: true,reset_vim_on_submission: true,}@@ -582,16 +585,14 @@ impl Default for ChatComposerConfig {}impl ChatComposerConfig {- /// A minimal preset for plain-text inputs embedded in other surfaces.- ///- /// This disables popups, slash and shell commands, and image-path attachment behavior- /// so the composer behaves like a simple notes field.+ /// Text answers support Markdown, without popups, commands, or image attachments.pub(crate) const fn plain_text() -> Self {Self {popups_enabled: false,slash_commands_enabled: false,shell_commands_enabled: false,image_paste_enabled: false,+ blockquote_paste_enabled: true,trim_submission: true,reset_vim_on_submission: true,}diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/blockquote_paste_tests.rs b/codex-rs/tui/src/bottom_pane/chat_composer/blockquote_paste_tests.rsnew file mode 100644index 0000000000..fcd393739a--- /dev/null+++ b/codex-rs/tui/src/bottom_pane/chat_composer/blockquote_paste_tests.rs@@ -0,0 +1,144 @@+use super::super::tests::new_test_composer;+use super::super::tests::snapshot_composer_state_with_width;+use super::super::*;+use crossterm::event::MouseEvent;+use crossterm::event::MouseEventKind;+use pretty_assertions::assert_eq;++#[test]+fn blockquote_paste_continues_current_line_prefix() {+ for (draft, pasted, expected) in [+ ("> ", "first\nsecond", "> first\n> second\n\n"),+ ("intro\n> ", "α\r\n\r\nβ\r", "intro\n> α\n> \n> β\n> \n\n"),+ (+ "> existing ",+ "first\nsecond",+ "> existing first\n> second\n\n",+ ),+ ("text > ", "first\nsecond", "text > first\nsecond"),+ (">", "first\nsecond", ">first\nsecond"),+ (+ "> quote\nplain ",+ "first\nsecond",+ "> quote\nplain first\nsecond",+ ),+ ("> ", "single", "> single"),+ ("!> ", "out\npwd", "!> out\npwd"),+ (" !echo hi\n> ", "out\npwd", " !echo hi\n> out\npwd"),+ ] {+ let (mut composer, _rx) = new_test_composer();+ composer.insert_str(draft);+ composer.handle_paste(pasted.to_string());+ assert_eq!(composer.current_text(), expected);+ }+}++#[test]+fn blockquote_paste_uses_cursor_line_and_preserves_suffix() {+ let (mut composer, _rx) = new_test_composer();+ composer.insert_str("intro\n> suffix\nend");+ composer.draft.textarea.set_cursor("intro\n> ".len());+ composer.handle_paste("first\nsecond".to_string());+ assert_eq!(+ composer.draft.textarea.text(),+ "intro\n> first\n> second\n\nsuffix\nend"+ );+ composer.insert_str("next ");+ assert_eq!(+ composer.current_text(),+ "intro\n> first\n> second\n\nnext suffix\nend"+ );+}++#[test]+fn blockquote_paste_large_expands_quoted_text_on_submit() {+ let (mut composer, _rx) = new_test_composer();+ composer.insert_str("> ");+ let first = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD);+ composer.handle_paste(format!("{first}\nsecond"));+ let quoted = format!("{first}\n> second");+ let placeholder = format!("[Pasted Content {} chars]", quoted.chars().count());+ assert_eq!(+ composer.draft.textarea.text(),+ format!("> {placeholder}\n\n")+ );+ assert_eq!(+ composer.draft.pending_pastes,+ vec![(placeholder, quoted.clone())]+ );+ composer.insert_str("Next block");+ let (result, _) = composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));+ let InputResult::Submitted { text, .. } = result else {+ panic!("expected Submitted");+ };+ assert_eq!(text, format!("> {quoted}\n\nNext block"));+}++#[test]+fn blockquote_paste_rendered() {+ snapshot_composer_state_with_width(+ "blockquote_paste",+ /*width*/ 60,+ /*enhanced_keys_supported*/ false,+ |composer| {+ composer.insert_str("Please explain:\n> ");+ composer.handle_paste("first line\n\nlast line".to_string());+ composer.insert_str("Next block");+ },+ );+}++#[test]+fn blockquote_paste_replacing_selected_prefix_stays_literal() {+ let (mut composer, _rx) = new_test_composer();+ composer.insert_str("> selected");+ let area = Rect::new(+ /*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 10,+ );+ composer.render(area, &mut Buffer::empty(area));+ let (x, y) = composer.cursor_pos(area).unwrap();+ for (kind, column) in [+ (+ MouseEventKind::Down(crossterm::event::MouseButton::Left),+ x - 10,+ ),+ (MouseEventKind::Drag(crossterm::event::MouseButton::Left), x),+ ] {+ let event = MouseEvent {+ kind,+ column,+ row: y,+ modifiers: KeyModifiers::NONE,+ };+ assert!(composer.prepare_mouse(event));+ composer.render(area, &mut Buffer::empty(area));+ assert!(composer.handle_mouse(event));+ }+ composer.handle_paste("first\nsecond".to_string());+ assert_eq!(composer.current_text(), "first\nsecond");+}++#[test]+fn blockquote_paste_embedded_answer_starts_next_block() {+ let (mut composer, _rx) = new_test_composer();+ composer.config = ChatComposerConfig::plain_text();+ composer.insert_str("> ");+ composer.handle_paste("first\nsecond".to_string());+ composer.insert_str("Next block");+ assert_eq!(composer.current_text(), "> first\n> second\n\nNext block");+}++#[test]+fn blockquote_paste_embedded_answer_rendered() {+ snapshot_composer_state_with_width(+ "blockquote_paste_embedded_answer",+ /*width*/ 60,+ /*enhanced_keys_supported*/ false,+ |composer| {+ composer.config = ChatComposerConfig::plain_text();+ composer.insert_str("> ");+ composer.handle_paste("first line\n\nlast line".to_string());+ composer.insert_str("Next block");+ },+ );+}diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/paste_input.rs b/codex-rs/tui/src/bottom_pane/chat_composer/paste_input.rsindex 48ea632c1c..eecc926631 100644--- a/codex-rs/tui/src/bottom_pane/chat_composer/paste_input.rs+++ b/codex-rs/tui/src/bottom_pane/chat_composer/paste_input.rs@@ -1,20 +1,29 @@//! Classify and integrate composer pastes and capture raw paste tabs before completion or submission.+//! Multiline pastes on a line beginning with `> ` continue that prefix after every newline,+//! including blank and trailing lines. This happens before large pastes are collapsed, so their+//! expanded text retains the quoting. Two unquoted newlines after the inserted text or placeholder+//! leave the cursor in the next Markdown block, including in embedded answer fields.+//! Provisional startup input, search queries, and shell input remain literal.+//! Paste classification and insertion share one textarea edit target, including selection replacement.use super::*;use crate::bottom_pane::paste_burst::FlushResult;+use crate::bottom_pane::textarea::EditTarget;impl ChatComposer {pub(crate) fn insert_str(&mut self, text: &str) {+ self.insert_str_at_target(self.draft.textarea.edit_target(), text);+ }++ fn insert_str_at_target(&mut self, target: EditTarget, text: &str) {if !text.is_empty() && self.sparkle.draft.get() == sparkle::SparkleDraft::Untouched {self.dismiss_sparkle();}let started_vim_edit = self.begin_direct_vim_edit();- let elements_before = self- .draft- .textarea- .mouse_selection_range()- .map(|_| self.draft.textarea.element_payloads());- self.draft.textarea.insert_str(text);+ let elements_before = target+ .replaces_text()+ .then(|| self.draft.textarea.element_payloads());+ self.draft.textarea.insert_str_at_target(target, text);if let Some(elements_before) = elements_before {self.reconcile_deleted_elements(elements_before);}@@ -130,10 +139,24 @@ impl ChatComposer {}let started_vim_edit = self.begin_direct_vim_edit();let elements_before = self.draft.textarea.element_payloads();+ let target = self.draft.textarea.edit_target();+ let before_cursor = &self.draft.textarea.text()[..target.start()];+ let current_line = before_cursor.rsplit('\n').next().unwrap_or_default();+ let is_blockquote = self.config.blockquote_paste_enabled+ && !self.is_bang_shell_command()+ && current_line.starts_with("> ")+ && pasted.contains('\n');+ let pasted = if is_blockquote {+ std::borrow::Cow::Owned(pasted.replace('\n', "\n> "))+ } else {+ pasted+ };let char_count = pasted.chars().count();if char_count > LARGE_PASTE_CHAR_THRESHOLD {let placeholder = self.next_large_paste_placeholder(char_count);- self.draft.textarea.insert_element(&placeholder);+ self.draft+ .textarea+ .insert_element_at_target(target, &placeholder);self.draft.pending_pastes.push((placeholder, pasted.into_owned()));@@ -144,7 +167,11 @@ impl ChatComposer {let cursor = self.draft.textarea.cursor();self.draft.textarea.insert_str_at(cursor, " ");} else {- self.insert_str(&pasted);+ self.insert_str_at_target(target, &pasted);+ }+ if is_blockquote {+ let textarea = &mut self.draft.textarea;+ textarea.insert_str_at(textarea.cursor(), "\n\n");}self.draft.paste_burst.clear_after_explicit_paste();self.reconcile_deleted_elements(elements_before);@@ -191,3 +218,7 @@ impl ChatComposer {false}}++#[cfg(test)]+#[path = "blockquote_paste_tests.rs"]+mod blockquote_paste_tests;diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__blockquote_paste.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__blockquote_paste.snapnew file mode 100644index 0000000000..69bbc367af--- /dev/null+++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__blockquote_paste.snap@@ -0,0 +1,14 @@+---+source: tui/src/bottom_pane/chat_composer.rs+assertion_line: 5302+expression: terminal.backend()+---+" "+"› Please explain: "+" > first line "+" > "+" > last line "+" "+" Next block "+" "+" 100% context left "diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__blockquote_paste_embedded_answer.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__blockquote_paste_embedded_answer.snapnew file mode 100644index 0000000000..e53f1d94ce--- /dev/null+++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__blockquote_paste_embedded_answer.snap@@ -0,0 +1,14 @@+---+source: tui/src/bottom_pane/chat_composer.rs+assertion_line: 5302+expression: terminal.backend()+---+" "+"› > first line "+" > "+" > last line "+" "+" Next block "+" "+" "+" 100% context left "diff --git a/codex-rs/tui/src/bottom_pane/textarea.rs b/codex-rs/tui/src/bottom_pane/textarea.rsindex 60bd8e7e70..51f988b830 100644--- a/codex-rs/tui/src/bottom_pane/textarea.rs+++ b/codex-rs/tui/src/bottom_pane/textarea.rs@@ -16,6 +16,7 @@//! Visible web URLs carry their complete terminal hyperlink destination across wrapped rows;//! masked rendering never exposes hyperlink destinations.//! Mouse selection uses those same visual rows and keeps graphemes and elements atomic.+//! The editing module resolves replacement targets shared by insertion and paste-context inspection.use crate::key_hint::KeyBindingListExt;use crate::key_hint::is_altgr;@@ -50,12 +51,14 @@ use std::ops::Range;use std::sync::Arc;use unicode_segmentation::UnicodeSegmentation;+mod editing;mod hyperlinks;mod mouse;mod vim;mod vim_commands;mod vim_search;mod wrapping;+use self::vim::VimMode;use self::vim::VimMotion;use self::vim::VimOperator;@@ -67,6 +70,7 @@ use self::vim_commands::VimCommandState;use self::vim_commands::VimEditTarget;use self::vim_commands::VimInsertPosition;pub(crate) use self::vim_commands::VimPersistentState;+pub(crate) use editing::EditTarget;const WORD_SEPARATORS: &str = "`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?";@@ -441,16 +445,6 @@ impl TextArea {&self.text}- pub fn insert_str(&mut self, text: &str) {- let replaced_selection = !text.is_empty() && self.delete_mouse_selection();- self.record_vim_inserted_text(text);- if self.is_vim_replace_mode() && !replaced_selection {- self.replace_vim_text(text);- } else {- self.insert_str_at(self.cursor_pos, text);- }- }-pub fn insert_str_at(&mut self, pos: usize, text: &str) {self.mouse_selection = None;self.clear_vim_replace_recovery();@@ -1723,17 +1717,6 @@ impl TextArea {true}- pub fn insert_element(&mut self, text: &str) -> u64 {- self.delete_mouse_selection();- let start = self.clamp_pos_for_insertion(self.cursor_pos);- self.insert_str_at(start, text);- let end = start + text.len();- let id = self.add_element(start..end);- // Place cursor at end of inserted element- self.set_cursor(end);- id- }-fn add_element(&mut self, range: Range<usize>) -> u64 {let id = self.next_element_id();self.elements.push(TextElement { id, range });diff --git a/codex-rs/tui/src/bottom_pane/textarea/editing.rs b/codex-rs/tui/src/bottom_pane/textarea/editing.rsnew file mode 100644index 0000000000..6c97ea69dd--- /dev/null+++ b/codex-rs/tui/src/bottom_pane/textarea/editing.rs@@ -0,0 +1,81 @@+//! Resolve the replacement range once for context-sensitive edits, then consume it on insertion.+//! Targets respect character and atomic-element boundaries and must be used before another edit+//! or cursor/selection change. Text insertion retains Vim Replace and repeat policies; atomic+//! elements always replace the target literally.++use super::*;++/// The selection to replace, or an empty range at the insertion cursor.+/// Vim Replace without a selection computes its overwrite span as it inserts each grapheme.+#[derive(Debug)]+pub(crate) struct EditTarget {+ range: Range<usize>,+}++impl EditTarget {+ pub(crate) fn start(&self) -> usize {+ self.range.start+ }++ pub(crate) fn replaces_text(&self) -> bool {+ !self.range.is_empty()+ }+}++impl TextArea {+ pub(crate) fn edit_target(&self) -> EditTarget {+ let range = self.mouse_selection_range().map_or_else(+ || {+ let cursor = self.clamp_pos_for_insertion(self.cursor_pos);+ cursor..cursor+ },+ |range| self.expand_range_to_element_boundaries(range),+ );+ EditTarget { range }+ }++ pub fn insert_str(&mut self, text: &str) {+ self.insert_str_at_target(self.edit_target(), text);+ }++ pub(crate) fn insert_str_at_target(&mut self, target: EditTarget, text: &str) {+ // Empty text must not delete a selection or create a Vim replacement step.+ if text.is_empty() {+ if !self.is_vim_replace_mode() {+ self.insert_str_at(self.cursor_pos, text);+ }+ return;+ }+ let replaces_selection = target.replaces_text();+ if replaces_selection {+ // Pointer-selected edits cannot be replayed as keyboard-relative Vim commands.+ self.vim_commands = VimCommandState::default();+ }+ self.record_vim_inserted_text(text);+ if self.is_vim_replace_mode() && !replaces_selection {+ self.replace_vim_text(text);+ } else {+ self.replace_range(target.range, text);+ }+ }++ pub fn insert_element(&mut self, text: &str) -> u64 {+ self.insert_element_at_target(self.edit_target(), text)+ }++ pub(crate) fn insert_element_at_target(&mut self, target: EditTarget, text: &str) -> u64 {+ let start = target.start();+ if target.replaces_text() {+ self.vim_commands = VimCommandState::default();+ }+ self.replace_range(target.range, text);+ let end = start + text.len();+ let id = self.add_element(start..end);+ self.set_cursor(end);+ id+ }+}++#[cfg(test)]+#[path = "editing_tests.rs"]+mod tests;diff --git a/codex-rs/tui/src/bottom_pane/textarea/editing_tests.rs b/codex-rs/tui/src/bottom_pane/textarea/editing_tests.rsnew file mode 100644index 0000000000..8df7f7234d--- /dev/null+++ b/codex-rs/tui/src/bottom_pane/textarea/editing_tests.rs@@ -0,0 +1,74 @@+use super::*;+use crossterm::event::MouseButton;+use crossterm::event::MouseEvent;+use crossterm::event::MouseEventKind;+use pretty_assertions::assert_eq;++#[test]+fn target_replaces_forward_and_backward_selections() {+ for (anchor, cursor) in [(1, 4), (4, 1)] {+ let mut textarea = TextArea::new();+ textarea.insert_str("abcdef");+ let area = Rect::new(+ /*x*/ 0, /*y*/ 0, /*width*/ 20, /*height*/ 2,+ );+ let mut state = TextAreaState::default();+ StatefulWidgetRef::render_ref(&&textarea, area, &mut Buffer::empty(area), &mut state);+ for (kind, column) in [+ (MouseEventKind::Down(MouseButton::Left), anchor),+ (MouseEventKind::Drag(MouseButton::Left), cursor),+ ] {+ assert!(textarea.handle_mouse(+ MouseEvent {+ kind,+ column,+ row: 0,+ modifiers: KeyModifiers::NONE+ },+ state,+ ));+ }+ let target = textarea.edit_target();+ assert_eq!(&textarea.text()[..target.start()], "a");+ textarea.insert_str_at_target(target, "界");+ assert_eq!((textarea.text(), textarea.cursor()), ("a界ef", "a界".len()));+ assert_eq!(textarea.mouse_selection_range(), None);+ }+}++#[test]+fn target_element_insertion_preserves_adjacent_elements() {+ let mut textarea = TextArea::new();+ textarea.insert_str("before ");+ textarea.insert_element("[old]");+ textarea.insert_str(" after");+ textarea.set_cursor("before ".len());+ let target = textarea.edit_target();+ textarea.insert_element_at_target(target, "[new]");+ assert_eq!(+ (+ textarea.text(),+ textarea.cursor(),+ textarea.element_payloads()+ ),+ (+ "before [new][old] after",+ "before [new]".len(),+ vec!["[new]".to_string(), "[old]".to_string()]+ ),+ );+}++#[test]+fn target_text_preserves_vim_replace_and_backspace_recovery() {+ let mut textarea = TextArea::new();+ textarea.insert_str("abc");+ textarea.set_cursor(/*pos*/ 0);+ textarea.set_vim_enabled(/*enabled*/ true);+ textarea.input(KeyCode::Char('R').into());+ let target = textarea.edit_target();+ textarea.insert_str_at_target(target, "界");+ assert_eq!((textarea.text(), textarea.cursor()), ("界bc", "界".len()));+ textarea.input(KeyCode::Backspace.into());+ assert_eq!((textarea.text(), textarea.cursor()), ("abc", 0));+}diff --git a/codex-rs/tui/src/bottom_pane/textarea/mouse.rs b/codex-rs/tui/src/bottom_pane/textarea/mouse.rsindex 00c2c2adfe..ccbe221a67 100644--- a/codex-rs/tui/src/bottom_pane/textarea/mouse.rs+++ b/codex-rs/tui/src/bottom_pane/textarea/mouse.rs@@ -63,16 +63,6 @@ impl TextArea {(!range.is_empty()).then_some(range)}- pub(super) fn delete_mouse_selection(&mut self) -> bool {- let Some(range) = self.mouse_selection_range() else {- return false;- };- // A pointer-selected edit cannot be replayed as a keyboard-relative Vim command.- self.vim_commands = VimCommandState::default();- self.replace_range(range, "");- true- }-pub(crate) fn handle_mouse(&mut self, event: MouseEvent, state: TextAreaState) -> bool {let area = self.rendered_area.get();let dragging = self.mouse_selection.as_ref().is_some_and(|s| s.dragging);diff --git a/codex-rs/tui/src/startup_draft.rs b/codex-rs/tui/src/startup_draft.rsindex 96ffcecd70..258e78070c 100644--- a/codex-rs/tui/src/startup_draft.rs+++ b/codex-rs/tui/src/startup_draft.rs@@ -530,7 +530,11 @@ fn startup_draft_bottom_pane(effects: Default::default(),skills: None,},- ChatComposerConfig::plain_text(),+ ChatComposerConfig {+ // Keep partial pastes literal until the startup draft is handed off.+ blockquote_paste_enabled: false,+ ..ChatComposerConfig::plain_text()+ },);bottom_pane.set_context_window_pending(/*pending*/ true);bottom_pane