Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Copy transcript selections as literal text while preserving rich HTML (#50467)

Felipe Couryf5a2272c6cb6
diff --git a/codex-rs/tui/src/chatwidget/copy_picker.rs b/codex-rs/tui/src/chatwidget/copy_picker.rs
index c41d40b26e..a8119ddd55 100644
--- a/codex-rs/tui/src/chatwidget/copy_picker.rs
+++ b/codex-rs/tui/src/chatwidget/copy_picker.rs
@@ -98,7 +98,7 @@ impl ChatWidget {
tx.send(AppEvent::CopySelection {
text: Arc::clone(&text),
label: label.clone(),
- format,
+ format: format.clone(),
});
})],
dismiss_on_select: true,
diff --git a/codex-rs/tui/src/clipboard_copy.rs b/codex-rs/tui/src/clipboard_copy.rs
index c08b881b99..cedbd5d545 100644
--- a/codex-rs/tui/src/clipboard_copy.rs
+++ b/codex-rs/tui/src/clipboard_copy.rs
@@ -25,16 +25,19 @@ pub(crate) mod worker;
use base64::Engine;
use std::io::Write;
+use std::sync::Arc;
use tmux::copy as tmux_clipboard_copy;
/// Maximum raw bytes sent through tmux or directly encoded into OSC 52.
/// Large payloads are rejected before encoding to avoid overwhelming the terminal.
const OSC52_MAX_RAW_BYTES: usize = 100_000;
-/// Whether copied text should also have a rendered HTML representation.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+/// Whether copied text should also have a rendered HTML representation and its source.
+#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum CopyFormat {
PlainText,
Markdown,
+ /// Visible selection text is copied literally; only HTML uses the semantic Markdown.
+ MarkdownSelection(Arc<str>),
}
/// A native clipboard write or an unacknowledged request to the user's terminal.
@@ -196,6 +199,9 @@ fn copy_to_clipboard_with(
let html = match format {
CopyFormat::PlainText => None,
CopyFormat::Markdown => Some(crate::clipboard_html::render_markdown(text)),
+ CopyFormat::MarkdownSelection(source) => {
+ Some(crate::clipboard_html::render_markdown(&source))
+ }
};
let native_result = arboard_copy_fn(text, html.as_deref()).or_else(|native_error| {
if environment.wsl_session {
@@ -656,21 +662,27 @@ mod tests {
#[test]
fn local_copy_offers_html_only_for_markdown() {
- for (format, html) in [
+ for (text, format, html) in [
(
+ "**hello**",
CopyFormat::Markdown,
Some("<p><strong>hello</strong></p>\n"),
),
- (CopyFormat::PlainText, None),
+ ("**hello**", CopyFormat::PlainText, None),
+ (
+ "hello /repo/my_notes!.txt",
+ CopyFormat::MarkdownSelection(r"**hello** /repo/my\_notes\!.txt".into()),
+ Some("<p><strong>hello</strong> /repo/my_notes!.txt</p>\n"),
+ ),
] {
let result = copy_to_clipboard_with(
- "**hello**",
+ text,
format,
local_environment(),
|_| panic!("native copy should succeed"),
|_| panic!("native copy should succeed"),
- |text, actual_html| {
- assert_eq!((text, actual_html), ("**hello**", html));
+ |actual_text, actual_html| {
+ assert_eq!((actual_text, actual_html), (text, html));
Ok(None)
},
|_| panic!("native copy should succeed"),
diff --git a/codex-rs/tui/src/markdown_copy.rs b/codex-rs/tui/src/markdown_copy.rs
index 7a9b9d2235..ffdf4f35d5 100644
--- a/codex-rs/tui/src/markdown_copy.rs
+++ b/codex-rs/tui/src/markdown_copy.rs
@@ -37,6 +37,28 @@ pub(crate) fn quote_content(source: &str) -> String {
// Bound retained inline stacks and container prefixes independently of parser nesting.
pub(crate) const MAX_COPY_DEPTH: usize = 64;
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum SelectionOutput {
+ Markdown,
+ PlainText,
+}
+
+impl SelectionOutput {
+ fn render(self, plain: &str, markdown: impl FnOnce() -> String) -> String {
+ match self {
+ Self::Markdown => markdown(),
+ Self::PlainText => plain.to_owned(),
+ }
+ }
+
+ fn push_prose(self, out: &mut String, plain: &str, markdown: impl FnOnce() -> String) {
+ match self {
+ Self::Markdown => push_prose_fragment(out, &markdown()),
+ Self::PlainText => out.push_str(plain),
+ }
+ }
+}
+
// A fixed, deduplicated style order gives each nested wrapper a distinct delimiter family.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Inline {
@@ -298,9 +320,29 @@ impl SelectedLine {
});
}
}
+
+ fn separator(&self, output: SelectionOutput) -> &str {
+ if output == SelectionOutput::PlainText && self.separator.starts_with(" \n") {
+ &self.separator[2..]
+ } else {
+ &self.separator
+ }
+ }
}
pub(crate) fn selection(lines: &[SelectedLine], plain: &str) -> (String, CopyFormat) {
+ render_selection(lines, plain, SelectionOutput::Markdown)
+}
+
+pub(crate) fn literal_selection(lines: &[SelectedLine], plain: &str) -> String {
+ render_selection(lines, plain, SelectionOutput::PlainText).0
+}
+
+fn render_selection(
+ lines: &[SelectedLine],
+ plain: &str,
+ output: SelectionOutput,
+) -> (String, CopyFormat) {
// Soft wraps and streamed fragments of the same logical line are already coalesced.
if let [line] = lines
&& line
@@ -380,7 +422,7 @@ pub(crate) fn selection(lines: &[SelectedLine], plain: &str) -> (String, CopyFor
let mut indentation: Option<usize> = None;
while let Some(line) = lines.next() {
if !first {
- out.push_str(&line.separator);
+ out.push_str(line.separator(output));
}
let prefix = line.source.copy.as_ref().map_or("", |copy| {
if indentation.is_none() && !line.range.is_empty() && lines.peek().is_some() {
@@ -422,7 +464,7 @@ pub(crate) fn selection(lines: &[SelectedLine], plain: &str) -> (String, CopyFor
selected.extend(lines.next());
}
let entire_selection = first && lines.peek().is_none();
- let (mut body, format) = table::render(&selected, table, entire_selection);
+ let (mut body, format) = table::render(&selected, table, entire_selection, output);
if format == CopyFormat::PlainText {
body.retain(|ch| !ch.is_control() || matches!(ch, '\n' | '\t'));
return (body, format);
@@ -451,15 +493,17 @@ pub(crate) fn selection(lines: &[SelectedLine], plain: &str) -> (String, CopyFor
}
} else if line.source.copy_as_prose {
let text = &line.source.text[line.range.clone()];
- push_prose_fragment(&mut out, &escape(text));
+ output.push_prose(&mut out, text, || escape(text));
} else if let Some(copy) = &line.source.copy
&& !copy.code
{
if line.range.start == 0 || first && lines.peek().is_some() {
out.push_str(&prefix);
}
- let body = copy.render(&line.source.text, line.range.clone(), /*depth*/ 0);
- push_prose_fragment(&mut out, &body);
+ let text = &line.source.text[line.range.clone()];
+ output.push_prose(&mut out, text, || {
+ copy.render(&line.source.text, line.range.clone(), /*depth*/ 0)
+ });
} else {
// Preserve whitespace and Markdown-looking tool output within mixed selections.
let mut code = line.source.text[line.range.clone()].to_owned();
@@ -485,10 +529,16 @@ pub(crate) fn selection(lines: &[SelectedLine], plain: &str) -> (String, CopyFor
.map_or("", |copy| copy.continuation.as_str())
== continuation
{
- code.push_str(&next.separator);
+ code.push_str(next.separator(output));
code.push_str(&next.source.text[next.range.clone()]);
lines.next();
}
+ if output == SelectionOutput::PlainText {
+ out.push_str(&prefix);
+ out.push_str(&code);
+ first = false;
+ continue;
+ }
let fence = fence(&code, /*minimum*/ 3);
if !out.is_empty() && !out.ends_with('\n') {
out.push('\n');
diff --git a/codex-rs/tui/src/markdown_copy/table.rs b/codex-rs/tui/src/markdown_copy/table.rs
index 54ff6d11b8..e4f3b375b3 100644
--- a/codex-rs/tui/src/markdown_copy/table.rs
+++ b/codex-rs/tui/src/markdown_copy/table.rs
@@ -6,6 +6,7 @@
use super::CopyLine;
use super::SelectedLine;
+use super::SelectionOutput;
use crate::clipboard_copy::CopyFormat;
use crate::terminal_hyperlinks::HyperlinkLine;
use crate::terminal_hyperlinks::LogicalLineSource;
@@ -105,6 +106,7 @@ pub(super) fn render(
lines: &[&SelectedLine],
table: &TableLine,
entire_selection: bool,
+ output: SelectionOutput,
) -> (String, CopyFormat) {
let mut cells: BTreeMap<(usize, usize), Vec<LogicalLineSource>> = BTreeMap::new();
for line in lines {
@@ -180,14 +182,17 @@ pub(super) fn render(
let text = parts
.into_iter()
.map(|source| {
- source.copy.as_ref().map_or_else(
- || super::escape(&source.text[source.range.clone()]),
- |copy| {
- let mut copy = (**copy).clone();
- copy.table_cell = !standalone;
- copy.render(&source.text, source.range.clone(), /*depth*/ 0)
- },
- )
+ let text = &source.text[source.range.clone()];
+ output.render(text, || {
+ source.copy.as_ref().map_or_else(
+ || super::escape(text),
+ |copy| {
+ let mut copy = (**copy).clone();
+ copy.table_cell = !standalone;
+ copy.render(&source.text, source.range.clone(), /*depth*/ 0)
+ },
+ )
+ })
})
.collect::<Vec<_>>()
.join(" ");
@@ -204,7 +209,10 @@ pub(super) fn render(
return (
lines
.iter()
- .map(|line| super::escape(&line.source.text[line.range.clone()]))
+ .map(|line| {
+ let text = &line.source.text[line.range.clone()];
+ output.render(text, || super::escape(text))
+ })
.collect::<Vec<_>>()
.join("\n"),
CopyFormat::Markdown,
diff --git a/codex-rs/tui/src/transcript_view/copy_mode_tests.rs b/codex-rs/tui/src/transcript_view/copy_mode_tests.rs
index 27c37bdf0c..ffce6a76e3 100644
--- a/codex-rs/tui/src/transcript_view/copy_mode_tests.rs
+++ b/codex-rs/tui/src/transcript_view/copy_mode_tests.rs
@@ -387,7 +387,7 @@ fn find_and_shift_click_release_copy_payload() {
.unwrap() as u16;
view.extend_selection(/*column*/ 6, row);
assert!(view.copy_mode.is_none());
- assert_eq!(payload(&mut view, &cells), "**bold**");
+ assert_eq!(payload(&mut view, &cells), "bold");
}
#[test]
diff --git a/codex-rs/tui/src/transcript_view/markdown_copy_tests.rs b/codex-rs/tui/src/transcript_view/markdown_copy_tests.rs
index 9c965bae02..5ac501163d 100644
--- a/codex-rs/tui/src/transcript_view/markdown_copy_tests.rs
+++ b/codex-rs/tui/src/transcript_view/markdown_copy_tests.rs
@@ -16,7 +16,7 @@ mod elements;
#[test]
fn selected_markdown_preserves_lists_and_inline_code() {
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(AgentMarkdownCell::new(
- "- setting `closeRequested_`,\n- removing the tailer from `tailers_`,\n- clearing its live/discovery state.".into(),
+ "- setting `closeRequested_`,\n- removing the tailer from `tailers_`,\n- clearing /repo/my_notes!.txt.".into(),
Path::new("/"),
))];
let mut view = TranscriptView::default();
@@ -53,11 +53,13 @@ fn selected_markdown_preserves_lists_and_inline_code() {
&plain,
/*clear_selection*/ true,
|text, format| {
- assert_eq!(format, CopyFormat::Markdown);
+ let CopyFormat::MarkdownSelection(source) = format else {
+ panic!("expected rich selection");
+ };
insta::assert_snapshot!(text);
insta::assert_snapshot!(
"selected_list_html",
- crate::clipboard_html::render_markdown(text)
+ crate::clipboard_html::render_markdown(&source)
);
Ok(crate::clipboard_copy::CopyStatus::Confirmed)
},
@@ -414,12 +416,15 @@ fn explicit_hard_breaks_survive_only_when_selected() {
#[test]
fn task_lists_and_transformed_tables_keep_their_meaning() {
- for (source, expected) in [
- ("- [x] done\n- [ ] next", "- [x] done\n- [ ] next"),
- ("1. [x] done\n2. [ ] next", "1. [x] done\n2. [ ] next"),
- ] {
+ for source in ["- [x] done\n- [ ] next", "1. [x] done\n2. [ ] next"] {
let layout = markdown_layout(source, /*width*/ 80);
- assert_eq!(payload(&layout, 0..layout.text().len()).0, expected);
+ let mut lines = Vec::new();
+ layout.copy_lines(0..layout.text().len(), "", &mut lines);
+ assert_eq!(payload(&layout, 0..layout.text().len()).0, source);
+ assert_eq!(
+ crate::markdown_copy::literal_selection(&lines, "unused"),
+ source
+ );
}
let layout = markdown_layout(
"Prose\n\n| A | B |\n| - | - |\n| x | y |",
@@ -554,9 +559,12 @@ fn selected_hard_breaks_survive_surrounding_blocks() {
view.extend_selection(/*column*/ 79, /*row*/ 39);
let plain = view.selected_text(&cells).unwrap();
view.copy_selected_text_with(&cells, &plain, /*clear_selection*/ true, |text, format| {
- assert_eq!(format, CopyFormat::Markdown);
+ let CopyFormat::MarkdownSelection(source) = format else {
+ panic!("expected rich selection");
+ };
+ assert_eq!(text, "First paragraph.\n\nSecond paragraph with a hard break:\nnext line.\n\n> quoted words\n> next quote line\n\nFinal paragraph.");
assert_eq!(
- crate::clipboard_html::render_markdown(text),
+ crate::clipboard_html::render_markdown(&source),
"<p>First paragraph.</p>\n<p>Second paragraph with a hard break:<br />\nnext line.</p>\n<blockquote>\n<p>quoted <strong>words</strong><br />\nnext quote line</p>\n</blockquote>\n<p>Final paragraph.</p>\n"
);
Ok(crate::clipboard_copy::CopyStatus::Confirmed)
@@ -590,8 +598,11 @@ fn selected_open_code_fence_keeps_streamed_rows_in_one_block() {
&plain,
/*clear_selection*/ true,
|text, format| {
- assert_eq!(format, CopyFormat::Markdown);
- insta::assert_snapshot!(crate::clipboard_html::render_markdown(text), @r#"
+ let CopyFormat::MarkdownSelection(source) = format else {
+ panic!("expected rich selection");
+ };
+ assert_eq!(text, "Prose\n\nlet a = 1;\nlet b = 2;");
+ insta::assert_snapshot!(crate::clipboard_html::render_markdown(&source), @r#"
<p>Prose</p>
<pre><code>let a = 1;
let b = 2;
diff --git a/codex-rs/tui/src/transcript_view/selection.rs b/codex-rs/tui/src/transcript_view/selection.rs
index 26b8a2ae1f..8e62595d3a 100644
--- a/codex-rs/tui/src/transcript_view/selection.rs
+++ b/codex-rs/tui/src/transcript_view/selection.rs
@@ -358,8 +358,17 @@ impl TranscriptView {
.map(|text| (text.clone(), crate::clipboard_copy::CopyFormat::PlainText))
}
});
- let (text, format) =
- override_payload.unwrap_or_else(|| crate::markdown_copy::selection(&lines, text));
+ let (text, format) = override_payload.unwrap_or_else(|| {
+ let (serialized, format) = crate::markdown_copy::selection(&lines, text);
+ if format == CopyFormat::Markdown {
+ (
+ crate::markdown_copy::literal_selection(&lines, text),
+ CopyFormat::MarkdownSelection(serialized.into()),
+ )
+ } else {
+ (serialized, format)
+ }
+ });
let characters = text.chars().count();
let result = copy(&text, format);
self.show_copy_feedback(&result, characters);
diff --git a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__selected_list_html.snap b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__selected_list_html.snap
index 1247ca2848..2becf50a81 100644
--- a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__selected_list_html.snap
+++ b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__selected_list_html.snap
@@ -1,10 +1,10 @@
---
source: tui/src/transcript_view/markdown_copy_tests.rs
-assertion_line: 27
-expression: "crate::clipboard_html::render_markdown(text)"
+assertion_line: 61
+expression: "crate::clipboard_html::render_markdown(&source)"
---
<ul>
<li>setting <code>closeRequested_</code>,</li>
<li>removing the tailer from <code>tailers_</code>,</li>
-<li>clearing its live/discovery state.</li>
+<li>clearing /repo/my_notes!.txt.</li>
</ul>
diff --git a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__selected_markdown_preserves_lists_and_inline_code.snap b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__selected_markdown_preserves_lists_and_inline_code.snap
index 12a2e10c89..46d5fbc2b0 100644
--- a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__selected_markdown_preserves_lists_and_inline_code.snap
+++ b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__selected_markdown_preserves_lists_and_inline_code.snap
@@ -1,8 +1,8 @@
---
source: tui/src/transcript_view/markdown_copy_tests.rs
-assertion_line: 26
+assertion_line: 59
expression: text
---
-- setting `closeRequested_`,
-- removing the tailer from `tailers_`,
-- clearing its live/discovery state.
+- setting closeRequested_,
+- removing the tailer from tailers_,
+- clearing /repo/my_notes!.txt.
diff --git a/codex-rs/tui/src/transcript_view/table_copy_tests.rs b/codex-rs/tui/src/transcript_view/table_copy_tests.rs
index aaecaaae7f..2a42e567b5 100644
--- a/codex-rs/tui/src/transcript_view/table_copy_tests.rs
+++ b/codex-rs/tui/src/transcript_view/table_copy_tests.rs
@@ -7,20 +7,28 @@ const TABLE: &str = "| Task | Status | Next step |\n|---|---|---|\n| Task 1 | Co
#[test]
fn table_copy_preserves_structure_across_grid_and_record_layouts() {
+ let table = TABLE.replace("Finish implementation", "Finish my_long_file_name!.txt");
let source = format!(
- "The project is moving forward, with one task complete and two still to finish.\n\n{TABLE}\n\nThe next priority is to finish Task 2 while gathering the requirements needed to begin Task 3."
+ "The project is moving forward, with one task complete and two still to finish.\n\n{table}\n\nThe next priority is to finish Task 2 while gathering the requirements needed to begin Task 3."
);
+ let markdown = source.replace("my_long_file_name!.txt", r"my\_long\_file\_name\!.txt");
for width in [12, 24, 40, 80, 120] {
let layout = markdown_layout(&source, width);
+ let mut lines = Vec::new();
+ layout.copy_lines(0..layout.text().len(), "", &mut lines);
assert_eq!(
payload(&layout, 0..layout.text().len()),
- (source.clone(), CopyFormat::Markdown),
+ (markdown.clone(), CopyFormat::Markdown),
"width {width}"
);
+ assert_eq!(
+ crate::markdown_copy::literal_selection(&lines, "unused"),
+ source
+ );
let rewrapped = layout.rewrap(/*width*/ 17);
assert_eq!(
payload(&rewrapped, 0..rewrapped.text().len()).0,
- source,
+ markdown.clone(),
"rewrapped {width}"
);
}
@@ -198,7 +206,7 @@ fn empty_selected_rows_keep_copy_spacing_without_newline_highlights() {
(text, format),
(
format!("Before\n\n{TABLE}\n\nAfter").as_str(),
- CopyFormat::Markdown
+ CopyFormat::MarkdownSelection(format!("Before\n\n{TABLE}\n\nAfter").into())
)
);
Ok(crate::clipboard_copy::CopyStatus::Confirmed)