//! 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 lines, but not after a single trailing newline. 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. //! Pasted image files are copied into private temporary attachments while the client can read them. use super::*; use crate::bottom_pane::paste_burst::FlushResult; use crate::bottom_pane::textarea::EditTarget; use crate::clipboard_paste::normalize_pasted_path; use crate::clipboard_paste::pasted_image_format; impl ChatComposer { fn copy_pasted_image_path(pasted: &str) -> std::io::Result> { use std::io::Seek; #[cfg(unix)] use std::os::unix::fs::OpenOptionsExt; let Some(path_buf) = normalize_pasted_path(pasted) else { return Ok(None); }; // Opening a serial device or FIFO can block the input loop. if !path_buf.is_file() { return Ok(None); } let mut options = std::fs::OpenOptions::new(); options.read(true); #[cfg(unix)] options.custom_flags(libc::O_NONBLOCK); let Ok(mut file) = options.open(&path_buf) else { return Ok(None); }; let Ok(metadata) = file.metadata() else { return Ok(None); }; if !metadata.is_file() { return Ok(None); } let Ok(image_format) = image::ImageFormat::from_path(&path_buf) else { return Ok(None); }; let dimensions = image::ImageReader::with_format(std::io::BufReader::new(&mut file), image_format) .into_dimensions(); match dimensions { Ok((width, height)) => { tracing::info!("OK: {pasted}"); tracing::debug!("image dimensions={}x{}", width, height); let format = pasted_image_format(&path_buf); tracing::debug!("attached image format={}", format.label()); let suffix = path_buf .extension() .map(|extension| format!(".{}", extension.to_string_lossy())) .unwrap_or_default(); if metadata.len() > crate::clipboard_paste::MAX_PASTED_IMAGE_BYTES { return Err(std::io::Error::other("image exceeds the 1 GiB input limit")); } file.rewind()?; crate::clipboard_paste::persist_pasted_image(file, &suffix).map(Some) } Err(err) => { tracing::trace!("ERR: {err}"); Ok(None) } } } pub(crate) fn insert_str(&mut self, text: &str) { self.insert_str_at_target( self.draft.textarea.edit_target(), text, ShellPrefixHandling::Interpret, ); } fn insert_str_at_target( &mut self, target: EditTarget, text: &str, shell_prefix: ShellPrefixHandling, ) { self.draft.skill_completion_space = None; if !text.is_empty() && self.sparkle.draft.get() == sparkle::SparkleDraft::Untouched { self.dismiss_sparkle(); } let started_edit = self.begin_direct_edit(); let elements_before = target .replaces_text() .then(|| self.draft.textarea.element_payloads()); let inserts_shell_prefix = matches!(shell_prefix, ShellPrefixHandling::Interpret) && target.start() == 0 && text.starts_with('!'); self.draft.textarea.insert_str_at_target(target, text); if let Some(elements_before) = elements_before { self.reconcile_deleted_elements(elements_before); } if inserts_shell_prefix { self.sync_bash_mode_from_text(); } self.sync_popups(); if started_edit { self.finish_edit(); } } /// Include accepted but unflushed keys without changing live paste detection. pub(crate) fn recovery_snapshot(&self) -> ComposerDraftSnapshot { let mut snapshot = self.draft_snapshot(); let pending = self.draft.paste_burst.clone().flush_pending(); if matches!(pending, FlushResult::None) { return snapshot; } let mut textarea = TextArea::new(); textarea.set_text_with_elements(&snapshot.text, &snapshot.text_elements); match pending { FlushResult::Typed(ch) if self.draft.textarea.is_vim_replace_mode() => { textarea.set_cursor(snapshot.cursor); if let Some(selection) = self.draft.textarea.mouse_selection_range() { let offset = usize::from(self.draft.is_bash_mode); textarea.replace_range( selection.start + offset..selection.end + offset, &ch.to_string(), ); } else { textarea.replace_vim_text(&ch.to_string()); } } FlushResult::Typed(ch) => { if let Some(space) = self.draft.skill_completion_space_for_char(ch) { let space = space + usize::from(self.draft.is_bash_mode); textarea.replace_range(space..space + 1, &ch.to_string()); snapshot.cursor = space + ch.len_utf8(); } else { textarea.insert_str_at(snapshot.cursor, &ch.to_string()); } } FlushResult::Paste(pasted) => textarea.insert_str_at(snapshot.cursor, &pasted), FlushResult::None => {} } snapshot.text = textarea.text().to_owned(); snapshot.text_elements = textarea.text_elements(); snapshot } /// 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) } pub(crate) fn flush_pending_paste_burst(&mut self) { if let Some(pasted) = self.draft.paste_burst.flush_before_modified_input() { self.apply_paste(pasted); } } pub(in crate::bottom_pane) fn paste_handoff_deadline(&self) -> Option { if self.draft.disable_paste_burst { return None; } self.draft.paste_burst.handoff_deadline() } pub(in crate::bottom_pane) fn has_paste_window(&self, now: Instant) -> bool { !self.draft.disable_paste_burst && self .draft .paste_burst .newline_should_insert_instead_of_submit(now) } /// Display flushed text without losing the window for its trailing paste keys. pub(in crate::bottom_pane) fn flush_handoff_paste(&mut self, now: Instant) -> bool { let deadline = self.paste_handoff_deadline(); let flushed = self.handle_paste_burst_flush(now); if flushed && let Some(deadline) = deadline.filter(|deadline| *deadline >= now) { self.draft.paste_burst.preserve_window_until(deadline); } flushed } /// Enable or disable paste-burst handling. /// /// `disable_paste_burst` is an escape hatch for terminals/platforms where the burst heuristic /// is unwanted or has already been handled elsewhere. /// /// When transitioning from enabled → disabled, we "defuse" any in-flight burst state so it /// cannot affect subsequent normal typing: /// /// - First, flush held/buffered text via [`PasteBurst::flush_before_modified_input`] and /// integrate it with [`Self::apply_paste`]. Its key events have already been classified; /// [`Self::handle_paste`] classifies explicit terminal pastes before using the same /// integration path (large-paste placeholders, image-path detection, and popup sync). /// - Then clear the burst timing and Enter-suppression window via /// [`PasteBurst::clear_after_explicit_paste`]. /// /// We intentionally do not use `clear_window_after_non_char()` here: it clears timing state /// without emitting any buffered text, which can leave a non-empty buffer unable to flush /// later (because `flush_if_due()` relies on `last_plain_char_time` to time out). pub(crate) fn set_disable_paste_burst(&mut self, disabled: bool) { let was_disabled = self.draft.disable_paste_burst; self.draft.disable_paste_burst = disabled; if disabled && !was_disabled { self.flush_pending_paste_burst(); self.draft.paste_burst.clear_after_explicit_paste(); } } /// Applies any due `PasteBurst` flush at time `now`. /// /// Converts [`PasteBurst::flush_if_due`] results into concrete textarea mutations. /// Buffered keys have already been classified; paste results use [`Self::apply_paste`]. /// /// Callers: /// /// - UI ticks via [`ChatComposer::flush_paste_burst_if_due`], so held first-chars can render. /// - Input handling via [`ChatComposer::handle_input_basic`], so a due burst does not lag. /// - Submission, before deciding whether Enter belongs to an active paste burst. pub(super) fn handle_paste_burst_flush(&mut self, now: Instant) -> bool { 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) => { let completion_space = self.draft.skill_completion_space_for_char(ch); let started_edit = completion_space.is_some() && self.begin_direct_edit(); if let Some(space) = completion_space { self.draft.textarea.replace_range(space..space + 1, ""); } self.insert_str(ch.to_string().as_str()); if started_edit || !self.draft.textarea.is_vim_enabled() { self.finish_edit(); } true } FlushResult::None => false, } } /// Integrate pasted text into the composer. /// /// Both input paths integrate their text here: /// /// - Real/explicit paste events surfaced by the terminal, and /// - Non-bracketed "paste bursts" that /// [`PasteBurst`](crate::bottom_pane::paste_burst::PasteBurst) buffers and later flushes here. /// /// Behavior: /// /// - If history search is active, inserts nonempty text into its query and ignores empty pastes. /// - If Vim search is active, inserts text into its query. /// - Otherwise, if the paste is larger than `LARGE_PASTE_CHAR_THRESHOLD` chars, inserts a /// placeholder element (expanded on submit) and stores the full text in `pending_pastes`. /// - Otherwise, if the paste looks like an image path, attaches the image and inserts a /// trailing space so the user can keep typing naturally. /// - Otherwise, inserts the pasted text directly into the textarea. /// /// Composer edits clear paste-burst Enter suppression and sync popups. pub(super) fn apply_paste(&mut self, pasted: String) -> bool { self.apply_paste_with_shell_prefix(pasted, ShellPrefixHandling::Interpret) } pub(super) fn apply_paste_with_shell_prefix( &mut self, pasted: String, shell_prefix: ShellPrefixHandling, ) -> bool { let pasted = pasted.replace("\r\n", "\n").replace('\r', "\n"); let pasted = sanitize_user_text(pasted.into()); if self.history_search.is_some() { self.draft.skill_completion_space = None; if !pasted.is_empty() { self.update_history_search_query(|query| query.push_str(&pasted)); } return true; } if let Some(query) = self.draft.textarea.vim_query_mut() { self.draft.skill_completion_space = None; query.editor.insert_str(&pasted); return true; } 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 { let pasted = pasted .strip_suffix('\n') .filter(|pasted| !pasted.is_empty()) .unwrap_or(pasted.as_ref()); std::borrow::Cow::Owned(pasted.replace('\n', "\n> ")) } else { pasted }; let char_count = pasted.chars().count(); let image = if (2..=LARGE_PASTE_CHAR_THRESHOLD).contains(&char_count) && self.image_paste_enabled() { match Self::copy_pasted_image_path(&pasted) { Ok(image) => image, Err(error) => { self.draft.paste_burst.clear_after_explicit_paste(); self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new( history_cell::new_error_event(format!("Failed to paste image: {error}")), ))); return true; } } } else { None }; self.draft.skill_completion_space = None; self.draft.textarea_state.get_mut().follow_cursor(); let started_edit = self.begin_direct_edit(); let elements_before = self.draft.textarea.element_payloads(); if char_count > LARGE_PASTE_CHAR_THRESHOLD { let placeholder = self.next_large_paste_placeholder(char_count); self.draft .textarea .insert_element_at_target(target, &placeholder); self.draft .pending_pastes .push((placeholder, pasted.into_owned())); } else if let Some(image) = image { self.attach_image(image); let cursor = self.draft.textarea.cursor(); self.draft.textarea.insert_str_at(cursor, " "); } else { self.insert_str_at_target(target, &pasted, shell_prefix); } 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); self.sync_popups(); if started_edit { self.finish_edit(); } true } pub(super) fn handle_paste_tab(&mut self, key: KeyEvent, now: Instant) -> bool { key.code == KeyCode::Tab && key.modifiers.is_empty() && self.append_recent_paste_separator('\t', now) } pub(super) fn append_recent_paste_separator(&mut self, separator: char, now: Instant) -> bool { if self.draft.disable_paste_burst || !self.draft.textarea.allows_paste_burst() { return false; } self.handle_paste_burst_flush(now); if self .draft .paste_burst .append_control_char_if_active(separator, now) { self.begin_promoted_paste_edit(); return true; } // Short non-ASCII prefixes are inserted directly, without a held first character. if self .draft .paste_burst .direct_insert_newline_should_insert(now) { self.draft .paste_burst .begin_with_retro_grabbed(String::new(), now); return self .draft .paste_burst .append_control_char_if_active(separator, now); } false } } #[cfg(test)] #[path = "blockquote_paste_tests.rs"] mod blockquote_paste_tests;