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
+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();