Preserve fenced code source in TUI transcript copy mode (#63085)

## Why

An indented code block or a bare table displayed as code can match the
normalized text of a later fenced block. Copy mode could assign the fenced
block's original text to the earlier target, leaving the fenced block without
its original line endings or trailing whitespace.

## What changed

Track fenced code in both raw and rendered transcript layouts. Only match
original fenced code against copy targets that came from a fence.

## Testing

Extend copy-mode regression tests with an indented block and a bare table
that each precede a fenced block with matching normalized text.

GitOrigin-RevId: fbbce8e0feb71a449bb978aca65e1d2202da812e
This commit is contained in:
Eric Traut
2026-11-22 06:47:14 +00:00
committed by copyberry
parent 357fe240c9
commit 618d501ea0
5 changed files with 81 additions and 30 deletions
+1
View File
@@ -121,6 +121,7 @@ pub(crate) struct CopyLine {
/// Restore the containing item when a multiline selection starts in its later paragraph.
pub(crate) item_prefix: String,
pub(crate) code: bool,
pub(crate) fenced_code: bool,
/// Language of the displayed code, absent when the renderer replaces its body.
pub(crate) code_language: Option<Arc<str>>,
/// Source shared by rows when rendering replaces code with a diagram or table.
+13 -1
View File
@@ -552,6 +552,7 @@ struct Writer<'a, 'policy> {
last_task_marker_end: usize,
in_paragraph: bool,
in_code_block: bool,
fence_start: Option<usize>,
code_block_lang: Option<String>,
code_block_buffer: String,
code_block_content: Range<usize>,
@@ -600,6 +601,7 @@ impl<'a, 'policy> Writer<'a, 'policy> {
last_task_marker_end: 0,
in_paragraph: false,
in_code_block: false,
fence_start: None,
code_block_lang: None,
code_block_buffer: String::new(),
code_block_content: 0..0,
@@ -673,6 +675,12 @@ impl<'a, 'policy> Writer<'a, 'policy> {
}
Event::Text(text) => {
if self.in_code_block {
// A bare table preserved as code has no language and its text starts
// at the block boundary. A real fence without a language starts its
// text after the opener.
if self.fence_start == Some(range.start) && self.code_block_lang.is_none() {
self.fence_start = None;
}
self.code_block_content.start = self.code_block_content.start.min(range.start);
self.code_block_content.end = range.end;
}
@@ -750,7 +758,9 @@ impl<'a, 'policy> Writer<'a, 'policy> {
CodeBlockKind::Fenced(lang) => Some(lang.to_string()),
CodeBlockKind::Indented => None,
};
self.start_codeblock(lang, indent)
let fence_start = lang.as_ref().map(|_| range.start);
self.start_codeblock(lang, indent);
self.fence_start = fence_start;
}
Tag::List(start) => {
if self.pending_marker_line
@@ -1281,6 +1291,7 @@ impl<'a, 'policy> Writer<'a, 'policy> {
self.needs_newline = true;
self.in_code_block = false;
self.fence_start = None;
self.indent_stack.pop();
}
@@ -2628,6 +2639,7 @@ impl<'a, 'policy> Writer<'a, 'policy> {
self.copy_line.continuation = self.copy_prefix(/*pending_marker_line*/ false);
self.copy_line.item_prefix = self.copy_prefix(/*pending_marker_line*/ true);
self.copy_line.code = self.in_code_block;
self.copy_line.fenced_code = self.fence_start.is_some();
self.copy_line.code_source = self.transformed_code_source.clone();
self.copy_line.quote_source = self.quote_sources.first().cloned();
// Heading markers are already visible; retain them as Markdown syntax.
+42 -26
View File
@@ -120,12 +120,13 @@ impl TranscriptView {
let Some(layout) = self.layout(cells, index) else {
continue;
};
let mut ranges = if self.mode == crate::history_cell::HistoryRenderMode::Raw
&& !self.detailed
|| user.is_some_and(|user| !user.uses_markdown())
{
literal_block_ranges(layout.text(), user)
let literal = self.mode == HistoryRenderMode::Raw && !self.detailed
|| user.is_some_and(|user| !user.uses_markdown());
let mut fenced = Vec::new();
let mut ranges = if literal {
literal_block_ranges(layout.text(), user, &mut fenced)
} else {
fenced = layout.fenced_offsets();
layout.copy_block_ranges()
};
let user_source = user
@@ -156,7 +157,9 @@ impl TranscriptView {
let mut codes = targets
.iter()
.filter_map(|target| match target {
crate::markdown::CopyTarget::Code { content, .. } => Some(content),
crate::markdown::CopyTarget::Code { content, .. } => {
Some(Arc::clone(content))
}
crate::markdown::CopyTarget::Quote(_) => None,
})
.collect::<Vec<_>>();
@@ -177,25 +180,14 @@ impl TranscriptView {
_ => {}
}
}
let normalized = |text: &str| {
crate::markdown::normalize_markdown_for_rendering(text)
.lines()
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n")
.trim()
.to_owned()
};
let normalized = normalized;
for (range, label, payload) in &mut ranges {
if *label == "Code block" {
if *label == "Code block" && TextLayout::is_fenced_range(&fenced, range) {
// Match rendered text, not ordinal position: indented code and
// source-preserving tables need not have a fenced counterpart.
let displayed = payload.as_deref().unwrap_or(&layout.text()[range.clone()]);
if let Some(at) = codes
.iter()
.position(|code| normalized(code) == normalized(displayed))
{
*payload = Some(codes.remove(at).to_string());
if let Some(code) = take_matching_code(&mut codes, displayed) {
*payload = Some(code.to_string());
}
} else if *label == "Blockquote"
&& let Some(displayed) = payload.as_deref()
@@ -346,6 +338,24 @@ impl TranscriptView {
}
}
pub(super) fn take_matching_code(codes: &mut Vec<Arc<str>>, displayed: &str) -> Option<Arc<str>> {
let displayed = normalized(displayed);
let at = codes
.iter()
.position(|code| normalized(code) == displayed)?;
Some(codes.remove(at))
}
pub(super) fn normalized(text: &str) -> String {
crate::markdown::normalize_markdown_for_rendering(text)
.lines()
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n")
.trim()
.to_owned()
}
fn is_response(cell: &Arc<dyn HistoryCell>) -> bool {
cell.as_any().is::<AgentMarkdownCell>() || cell.as_any().is::<ProposedPlanCell>()
}
@@ -353,13 +363,14 @@ fn is_response(cell: &Arc<dyn HistoryCell>) -> bool {
fn literal_block_ranges(
text: &str,
user: Option<&UserHistoryCell>,
fenced: &mut Vec<usize>,
) -> Vec<(Range<usize>, &'static str, Option<String>)> {
use pulldown_cmark::Event;
use pulldown_cmark::Tag;
use pulldown_cmark::TagEnd;
let mut ranges = Vec::new();
let mut depth = 0;
let mut code: Option<(Range<usize>, String)> = None;
let mut code = None;
for (event, range) in pulldown_cmark::Parser::new(text).into_offset_iter() {
match event {
Event::Start(Tag::BlockQuote) => {
@@ -372,11 +383,11 @@ fn literal_block_ranges(
depth += 1;
}
Event::End(TagEnd::BlockQuote) => depth -= 1,
Event::Start(Tag::CodeBlock(_)) => {
code = Some((range.start..range.start, String::new()))
Event::Start(Tag::CodeBlock(kind)) => {
code = Some((range.start..range.start, String::new(), kind));
}
Event::Text(text) => {
if let Some((source, content)) = code.as_mut() {
if let Some((source, content, _)) = code.as_mut() {
content.push_str(&text);
if source.start == source.end {
source.start = range.start;
@@ -385,7 +396,12 @@ fn literal_block_ranges(
}
}
Event::End(TagEnd::CodeBlock) => {
if let Some((range, content)) = code.take().filter(|(range, _)| !range.is_empty()) {
if let Some((range, content, kind)) =
code.take().filter(|(range, _, _)| !range.is_empty())
{
if matches!(kind, pulldown_cmark::CodeBlockKind::Fenced(_)) {
fenced.push(range.start);
}
ranges.push((range, "Code block", Some(content)));
}
}
@@ -321,7 +321,8 @@ fn rendered_mermaid_copies_source() {
#[test]
fn copy_source_survives_raw_rich_rendering_and_whitespace_normalization() {
let source = "Before\r\n\r\n```sh\r\necho x \r\n \r\n```\r\n\r\n> **quote**\r\n";
let source =
"Before\r\n\r\n echo x\r\n\r\n```sh\r\necho x \r\n \r\n```\r\n\r\n> **quote**\r\n";
let displayed = crate::git_action_directives::parse_assistant_markdown(source, Path::new("/"))
.visible_markdown;
for mode in [
@@ -528,7 +529,8 @@ fn copying_a_disabled_fenced_table_uses_the_original_body() {
..original
});
let body = "| Name | Value |\r\n|---|---|\r\n| alpha | beta | \r\n";
let message = format!("Intro\r\n\r\n```md\r\n{body}```\r\n\r\n```sh\r\necho done\r\n```\r\n");
let bare = "| Name | Value |\n|---|---|\n| alpha | beta |";
let message = format!("{bare}\n\n```md\r\n{body}```\r\n\r\n```sh\r\necho done\r\n```\r\n");
let cells: Vec<Arc<dyn HistoryCell>> = vec![Arc::new(crate::history_cell::new_user_prompt(
message.clone(),
Vec::new(),
@@ -536,13 +538,15 @@ fn copying_a_disabled_fenced_table_uses_the_original_body() {
Vec::new(),
))];
let mut view = TranscriptView::default();
let buffer = render(&mut view, &cells, /*width*/ 50, /*height*/ 12);
let buffer = render(&mut view, &cells, /*width*/ 50, /*height*/ 18);
assert!(text(&buffer).contains("```md"));
view.begin_copy_mode(&cells, /*guard*/ None);
assert_eq!(payload(&mut view, &cells), "echo done\r\n");
view.move_copy_target(&cells, KeyCode::Up);
assert_eq!(payload(&mut view, &cells), body);
view.move_copy_target(&cells, KeyCode::Up);
assert_eq!(payload(&mut view, &cells), bare);
view.move_copy_target(&cells, KeyCode::Up);
assert_eq!(payload(&mut view, &cells), message.replace('\r', ""));
preferences::init(original);
}
+18
View File
@@ -228,6 +228,24 @@ impl TextLayout {
}
}
pub(super) fn fenced_offsets(&self) -> Vec<usize> {
self.logical_sources()
.filter_map(|(start, origin)| {
origin
.copy
.as_ref()
.is_some_and(|copy| copy.fenced_code || copy.code_source.is_some())
.then_some(start)
})
.collect()
}
pub(super) fn is_fenced_range(offsets: &[usize], range: &Range<usize>) -> bool {
offsets
.get(offsets.partition_point(|offset| *offset < range.start))
.is_some_and(|offset| *offset <= range.end)
}
/// Append a clipped interaction row outside the copied and searched source text.
pub(super) fn with_disclosure_control(self, label: String) -> Self {
let source_offset = self.text.len();