Select and copy Markdown blocks in the transcript (#63047)

## What changed

Press `m` in transcript selection mode to mark the Markdown block at the cursor. Move between sibling blocks with `h` and `l`, or extend the selection with `j` and `k`. Use `Tab` to expand to an enclosing block or heading section and `Shift+Tab` to shrink the selection.

Copy with `y` to retain Markdown structure, including list markers, code fence languages, and table formatting. For example, you can copy a fenced code block on its own from inside a blockquote.

## Testing

Add coverage for wrapped blocks, nested lists and sections, table selection, copying from the displayed revision during streaming, and conflicts with customized keybindings.

GitOrigin-RevId: 5d4d873c0e378294128c128f472e4dae122831c6
This commit is contained in:
Felipe Coury
2026-11-21 21:51:31 +00:00
committed by copyberry
parent 704ffed1c5
commit 9302bb553e
26 changed files with 1274 additions and 125 deletions
@@ -137,7 +137,7 @@ async fn configured_ctrl_space_submit_wins_over_transcript_selection() -> Result
}
#[tokio::test]
async fn markdown_chord_and_remapped_find_work_in_transcript_selection() -> Result<()> {
async fn markdown_shortcut_respects_remapped_find_and_explicit_chords() -> Result<()> {
let mut app = crate::app::test_support::make_test_app().await;
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
let mut tui = crate::tui::test_support::make_test_tui()?;
@@ -145,13 +145,15 @@ async fn markdown_chord_and_remapped_find_work_in_transcript_selection() -> Resu
let size = Size::new(/*width*/ 80, /*height*/ 16);
tui.terminal.resize(size)?;
for (config, prefix) in [
for (config, find, prefix) in [
(
serde_json::json!({"pager": {"find": "c"}}),
serde_json::json!({"pager": {"find": "m"}}),
'm',
KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL),
),
(
serde_json::json!({"global": {"leader": "f6"}, "pager": {"find": "c"}}),
serde_json::json!({"global": {"leader": "f6"}, "pager": {"find": "c", "mark_markdown": "leader v"}}),
'c',
KeyCode::F(6).into(),
),
] {
@@ -169,7 +171,7 @@ async fn markdown_chord_and_remapped_find_work_in_transcript_selection() -> Resu
app.handle_tui_event(
&mut tui,
&mut server,
TuiEvent::Key(KeyCode::Char('c').into()),
TuiEvent::Key(KeyCode::Char(find).into()),
)
.await?;
assert!(app.transcript_view.is_search_editing());
@@ -244,7 +244,7 @@ async fn document_preview_scenario() -> Result<()> {
side_frame(&mut app, &mut tui, size)?;
let sidebar = app.conversation_frame.panel_area().expect("document panel");
let footer = visible_sidebar_row(&tui, sidebar, sidebar.bottom() - 1);
insta::assert_snapshot!(footer, @"v mark · enter/q close");
insta::assert_snapshot!(footer, @"m mark paragraph · q close");
for key in [KeyCode::Char('v'), KeyCode::Right] {
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key.into()))).await?;
}
@@ -182,7 +182,7 @@ async fn offline_selection_reserves_keys_and_preserves_draft_and_backtrack_state
}
#[tokio::test]
async fn markdown_chord_marks_whole_cells_in_the_transcript_overlay() -> Result<()> {
async fn markdown_key_marks_whole_cells_in_the_transcript_overlay() -> Result<()> {
let mut app = crate::app::test_support::make_test_app().await;
let mut app_server = start_config_write_test_app_server(&app).await?;
let mut tui = crate::tui::test_support::make_test_tui()?;
@@ -215,8 +215,7 @@ async fn markdown_chord_marks_whole_cells_in_the_transcript_overlay() -> Result<
TuiEvent::Paste("Be".into()),
TuiEvent::Draw,
TuiEvent::Key(KeyCode::Enter.into()),
TuiEvent::Key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)),
TuiEvent::Key(KeyCode::Char('v').into()),
TuiEvent::Key(KeyCode::Char('m').into()),
] {
app.handle_tui_event(&mut tui, &mut app_server, event)
.await?;
+1 -1
View File
@@ -73,7 +73,7 @@ impl App {
"open_presets" => (2, "Presets ›"),
"find_transcript" => (2, "Find text"),
"select_transcript" => (2, "Select transcript"),
"mark_markdown" => (2, "Mark table cell"),
"mark_markdown" => (2, "Mark Markdown block"),
"focus_conversation_composer" => (2, "Composer"),
other => (2, other),
};
+2 -2
View File
@@ -1857,7 +1857,7 @@ impl RuntimeKeymap {
});
}
}
resolved.configure_search(keymap)?;
resolved.configure_transcript_and_vim_defaults(keymap)?;
chords::leader_defaults::register(keymap, &mut resolved, workspace);
resolved.validate_conflicts()?;
chords::validate_chord_conflicts(&resolved)?;
@@ -2176,7 +2176,7 @@ impl RuntimeKeymap {
close: default_bindings![plain(KeyCode::Char('q')), ctrl(KeyCode::Char('c'))],
close_transcript: default_bindings![ctrl(KeyCode::Char('t'))],
find: default_bindings![plain(KeyCode::F(3)), plain(KeyCode::Char('/'))],
mark_markdown: Vec::new(),
mark_markdown: default_bindings![plain(KeyCode::Char('m'))],
chord_hints: Arc::default(),
},
list: ListKeymap {
@@ -68,6 +68,7 @@ pub(in crate::keymap) fn register(
action: name,
};
if (!workspace && (action.is_side_pane() || name == "open_agents"))
|| (name == "mark_markdown" && !resolved.pager.mark_markdown.is_empty())
|| !matches!(
super::configured_binding_for_action(keymap, action),
Some(None)
+20 -19
View File
@@ -1,5 +1,4 @@
//! Transcript and Vim search defaults yield to explicit bindings; explicit search conflicts
//! remain configuration errors.
//! Defaults for transcript actions and Vim search yield to explicit bindings.
use super::bindings::configured_binding_for_action;
use super::*;
@@ -26,25 +25,26 @@ impl Default for VimSearchKeymap {
}
impl RuntimeKeymap {
pub(super) fn configure_search(&mut self, config: &TuiKeymap) -> Result<(), String> {
for context in [KeymapContext::Global, KeymapContext::Pager] {
let setting = match context {
KeymapContext::Global => &config.global.find_transcript,
_ => &config.pager.find,
pub(super) fn configure_transcript_and_vim_defaults(
&mut self,
config: &TuiKeymap,
) -> Result<(), String> {
for (context, name) in [
(KeymapContext::Global, "find_transcript"),
(KeymapContext::Pager, "find"),
(KeymapContext::Pager, "mark_markdown"),
] {
let target = bindings::KeymapActionId {
context,
action: name,
};
if setting.is_some() {
if configured_binding_for_action(config, target).is_some_and(Option::is_some) {
continue;
}
let find_action = bindings::KeymapActionId {
context,
action: if context == KeymapContext::Global {
"find_transcript"
} else {
"find"
},
};
let conflicts = |action: bindings::KeymapActionId| {
action.overlaps(find_action)
action.overlaps(target)
|| name == "mark_markdown"
&& KeymapContextSet::transcript().contains_action(action)
|| context == KeymapContext::Global && action.context == KeymapContext::Approval
};
let configured: Vec<_> = runtime_action_bindings(self)
@@ -62,8 +62,9 @@ impl RuntimeKeymap {
.map(|chord| chord.chord.prefix),
)
.collect();
let bindings = match context {
KeymapContext::Global => &mut self.app.find_transcript,
let bindings = match name {
"find_transcript" => &mut self.app.find_transcript,
"mark_markdown" => &mut self.pager.mark_markdown,
_ => &mut self.pager.find,
};
bindings.retain(|binding| {
+1 -1
View File
@@ -279,7 +279,7 @@ define_keymap_actions! {
close => "Close the pager overlay.",
close_transcript => "Close the transcript overlay.",
find => "Find text in a transcript pager.",
mark_markdown => "Mark table cells in transcript selection mode.",
mark_markdown => "Mark Markdown blocks in transcript selection mode.",
}
list "List" {
move_up => "Move list selection up.",
+86 -14
View File
@@ -15,6 +15,7 @@ use pulldown_cmark::Tag;
use crate::clipboard_copy::CopyFormat;
use crate::terminal_hyperlinks::LogicalLineSource;
pub(crate) mod block;
pub(crate) mod table;
/// A transformed fenced block and its coordinates in the renderer input.
@@ -40,21 +41,39 @@ pub(crate) const MAX_COPY_DEPTH: usize = 64;
#[derive(Clone, Copy, PartialEq, Eq)]
enum SelectionOutput {
Blocks(usize),
Markdown,
PlainText,
}
impl SelectionOutput {
fn prefix(self, prefix: &str, indentation: Option<usize>) -> String {
let Self::Blocks(outer) = self else {
return dedent(prefix, indentation.unwrap_or_default());
};
let prefix = prefix.get(outer..).unwrap_or_default();
// Checkboxes extend their marker but do not increase the continuation indent.
if outer > 0 {
prefix
.strip_prefix("[x] ")
.or_else(|| prefix.strip_prefix("[ ] "))
.unwrap_or(prefix)
} else {
prefix
}
.to_owned()
}
fn render(self, plain: &str, markdown: impl FnOnce() -> String) -> String {
match self {
Self::Markdown => markdown(),
Self::Blocks(_) | 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::Blocks(_) | Self::Markdown => push_prose_fragment(out, &markdown()),
Self::PlainText => out.push_str(plain),
}
}
@@ -96,11 +115,14 @@ impl Inline {
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct CopyLine {
pub(crate) block: Option<Arc<block::Block>>,
pub(crate) prefix: String,
pub(crate) continuation: String,
/// Restore the containing item when a multiline selection starts in its later paragraph.
pub(crate) item_prefix: String,
pub(crate) 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.
pub(crate) code_source: Option<Arc<str>>,
/// Outer quote source, retained even when it contains only code.
@@ -149,6 +171,10 @@ pub(crate) fn has_visible_markup(
}
impl CopyLine {
pub(crate) fn has_list_marker(&self) -> bool {
self.prefix != self.continuation
}
pub(crate) fn push(&mut self, length: usize, inline: &[Inline]) {
if length == 0 {
return;
@@ -319,6 +345,10 @@ pub(crate) struct SelectedLine {
}
impl SelectedLine {
fn block(&self) -> Option<&Arc<block::Block>> {
self.source.copy.as_ref()?.block.as_ref()
}
pub(crate) fn append(
lines: &mut Vec<Self>,
source: LogicalLineSource,
@@ -391,6 +421,16 @@ pub(crate) fn selection(
render_selection(lines, plain, rectangle_rows, SelectionOutput::Markdown)
}
pub(crate) fn block_selection(lines: &[SelectedLine], outer_prefix: usize) -> String {
render_selection(
lines,
"",
/*rectangle_rows*/ None,
SelectionOutput::Blocks(outer_prefix),
)
.0
}
pub(crate) fn literal_selection(
lines: &[SelectedLine],
plain: &str,
@@ -405,8 +445,10 @@ fn render_selection(
rectangle_rows: Option<&RangeInclusive<usize>>,
output: SelectionOutput,
) -> (String, CopyFormat) {
let blocks = matches!(output, SelectionOutput::Blocks(_));
// Soft wraps and streamed fragments of the same logical line are already coalesced.
if rectangle_rows.is_none()
if !blocks
&& rectangle_rows.is_none()
&& let [line] = lines
&& line
.source
@@ -424,7 +466,8 @@ fn render_selection(
!line.range.is_empty() && !line.source.copy.as_ref().is_some_and(|copy| copy.omit)
})
.peekable();
let quote_only = content.peek().is_some()
let quote_only = !blocks
&& content.peek().is_some()
&& content.all(|line| {
line.source
.copy
@@ -473,7 +516,7 @@ fn render_selection(
.as_ref()
.is_some_and(|copy| !copy.code && !copy.omit)
});
if !rich {
if !rich && !blocks {
return (plain.to_owned(), CopyFormat::PlainText);
}
let mut out = String::new();
@@ -488,25 +531,40 @@ fn render_selection(
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() {
if !blocks && indentation.is_none() && !line.range.is_empty() && lines.peek().is_some()
{
&copy.item_prefix
} else {
&copy.prefix
}
});
if !line.range.is_empty() {
if !blocks && !line.range.is_empty() {
let spaces = prefix
.split("> ")
.map(|part| part.len() - part.trim_start_matches(' ').len())
.sum();
indentation = Some(indentation.map_or(spaces, |previous| previous.min(spaces)));
}
let prefix = dedent(prefix, indentation.unwrap_or(/*default*/ 0));
let prefix = output.prefix(prefix, indentation);
let task_marker = prefix.ends_with("[ ] ") || prefix.ends_with("[x] ");
// A rectangle is scoped to the table at the start of the selection.
let rectangle = rectangle_rows.filter(|_| first);
if line.range.is_empty() && rectangle.is_none() {
if line.range.is_empty()
&& rectangle.is_none()
&& !(blocks
&& line
.source
.copy
.as_ref()
.is_some_and(|copy| copy.code || copy.table.is_some()))
{
if line.source.text.is_empty() {
out.push_str(prefix.trim_end());
// Keep the space after an empty checkbox so it still parses as a task item.
out.push_str(if blocks && task_marker {
&prefix
} else {
prefix.trim_end()
});
}
first = false;
continue;
@@ -540,7 +598,7 @@ fn render_selection(
.copy
.as_ref()
.map_or("", |copy| copy.continuation.as_str());
let continuation = dedent(continuation, indentation.unwrap_or(/*default*/ 0));
let continuation = output.prefix(continuation, indentation);
for (index, row) in body.lines().enumerate() {
if index > 0 {
out.push('\n');
@@ -578,7 +636,12 @@ fn render_selection(
.copy
.as_ref()
.map_or("", |copy| copy.continuation.as_str());
let block = line.block();
while let Some(next) = lines.peek()
&& (!blocks
|| block
.zip(next.block())
.is_some_and(|(a, b)| Arc::ptr_eq(a, b)))
&& !next.source.copy_as_prose
&& next.source.copy.is_some() == line.source.copy.is_some()
&& next.source.copy.as_ref().is_none_or(|copy| copy.code)
@@ -609,16 +672,25 @@ fn render_selection(
if !out.is_empty() && !out.ends_with('\n') {
out.push('\n');
}
let continuation = dedent(continuation, indentation.unwrap_or(/*default*/ 0));
let continuation = output.prefix(continuation, indentation);
// A checkbox label must precede the fence on its own line.
if prefix.ends_with("[ ] ") || prefix.ends_with("[x] ") {
if task_marker {
out.push_str(prefix.trim_end());
out.push('\n');
out.push_str(&continuation);
} else {
out.push_str(&prefix);
}
out.push_str(&format!("{fence}\n"));
let language = if blocks {
line.source
.copy
.as_ref()
.and_then(|copy| copy.code_language.as_deref())
.unwrap_or_default()
} else {
""
};
out.push_str(&format!("{fence}{language}\n"));
for row in code.split_inclusive('\n') {
out.push_str(&continuation);
out.push_str(row);
+94
View File
@@ -0,0 +1,94 @@
//! Block ancestry shared by logical lines of a render. Pointer identity distinguishes
//! adjacent blocks with identical contents. Wrapping shares the original annotations.
use pulldown_cmark::HeadingLevel;
use pulldown_cmark::Tag;
use pulldown_cmark::TagEnd;
use std::sync::Arc;
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Block {
pub(crate) parent: Option<Arc<Block>>,
pub(crate) kind: Kind,
/// Bytes of container syntax to drop when copying this block on its own.
pub(crate) outer_prefix: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Kind {
Paragraph,
Heading(HeadingLevel),
Code,
Quote,
List,
Item,
Table,
}
impl Kind {
pub(crate) fn label(self) -> &'static str {
match self {
Self::Paragraph => "paragraph",
Self::Heading(_) => "heading",
Self::Code => "code block",
Self::Quote => "blockquote",
Self::List => "list",
Self::Item => "list item",
Self::Table => "table",
}
}
}
#[derive(Default)]
pub(crate) struct Stack {
current: Option<Arc<Block>>,
depth: usize,
}
impl Stack {
pub(crate) fn current(&self) -> Option<Arc<Block>> {
self.current.clone()
}
pub(crate) fn kind(tag: &Tag<'_>) -> Option<Kind> {
Some(match tag {
Tag::Paragraph => Kind::Paragraph,
Tag::Heading { level, .. } => Kind::Heading(*level),
Tag::BlockQuote => Kind::Quote,
Tag::CodeBlock(_) => Kind::Code,
Tag::List(_) => Kind::List,
Tag::Item => Kind::Item,
Tag::Table(_) => Kind::Table,
_ => return None,
})
}
pub(crate) fn push(&mut self, kind: Kind, outer_prefix: usize) {
self.depth += 1;
if self.depth <= super::MAX_COPY_DEPTH {
self.current = Some(Arc::new(Block {
parent: self.current.take(),
kind,
outer_prefix,
}));
}
}
pub(crate) fn end(&mut self, tag: TagEnd) {
if matches!(
tag,
TagEnd::Paragraph
| TagEnd::Heading(_)
| TagEnd::BlockQuote
| TagEnd::CodeBlock
| TagEnd::List(_)
| TagEnd::Item
| TagEnd::Table
) {
if self.depth <= super::MAX_COPY_DEPTH {
self.current = self.current.take().and_then(|block| block.parent.clone());
}
self.depth = self.depth.saturating_sub(1);
}
}
}
+4 -1
View File
@@ -220,7 +220,10 @@ pub(super) fn render(
.and_then(|copy| copy.table.as_ref())
.is_some_and(|table| table.fragments.is_empty())
});
let standalone = rectangle.is_none() && cells.len() == 1 && !includes_separator;
let standalone = !matches!(output, SelectionOutput::Blocks(_))
&& rectangle.is_none()
&& cells.len() == 1
&& !includes_separator;
if entire_selection
&& standalone
&& let Some(parts) = cells.values().next()
+19 -2
View File
@@ -535,6 +535,7 @@ struct Writer<'a, 'policy> {
styles: MarkdownStyles,
inline_styles: Vec<Style>,
copy_inline: Vec<crate::markdown_copy::Inline>,
blocks: crate::markdown_copy::block::Stack,
copy_line: crate::markdown_copy::CopyLine,
quote_sources: Vec<std::sync::Arc<str>>,
code_sources: Vec<crate::markdown_copy::SourceBlock>,
@@ -582,6 +583,7 @@ impl<'a, 'policy> Writer<'a, 'policy> {
styles: MarkdownStyles::default(),
inline_styles: Vec::new(),
copy_inline: Vec::new(),
blocks: Default::default(),
copy_line: Default::default(),
quote_sources: Vec::new(),
code_sources: Vec::new(),
@@ -658,8 +660,17 @@ impl<'a, 'policy> Writer<'a, 'policy> {
)
);
match event {
Event::Start(tag) => self.start_tag(tag, range, iter),
Event::End(tag) => self.end_tag(tag, range),
Event::Start(tag) => {
if let Some(kind) = crate::markdown_copy::block::Stack::kind(&tag) {
let prefix = self.copy_prefix(/*pending_marker_line*/ false).len();
self.blocks.push(kind, prefix);
}
self.start_tag(tag, range, iter);
}
Event::End(tag) => {
self.end_tag(tag, range);
self.blocks.end(tag);
}
Event::Text(text) => {
if self.in_code_block {
self.code_block_content.start = self.code_block_content.start.min(range.start);
@@ -1240,6 +1251,9 @@ impl<'a, 'policy> Writer<'a, 'policy> {
} else {
None
};
let code_language: Option<std::sync::Arc<str>> = diagram
.is_none()
.then(|| lang.split('`').next().unwrap_or_default().into());
let highlighted = match diagram {
Some(diagram) => diagram,
None => highlight_code_to_lines(&code, &lang),
@@ -1257,6 +1271,7 @@ impl<'a, 'policy> Writer<'a, 'policy> {
for hl_line in highlighted {
self.push_line(Line::default());
self.copy_line.code_source = Some(std::sync::Arc::clone(&source));
self.copy_line.code_language = code_language.clone();
for span in hl_line.spans {
self.push_span(span);
}
@@ -2575,6 +2590,7 @@ impl<'a, 'policy> Writer<'a, 'policy> {
.and_then(|source| source.copy.as_deref())
.cloned()
.unwrap_or_default();
copy.block = self.blocks.current();
copy.code_source = self.transformed_code_source.clone();
copy.quote_source = self.quote_sources.first().cloned();
copy.prefix = self.copy_prefix(pending_marker_line);
@@ -2607,6 +2623,7 @@ impl<'a, 'policy> Writer<'a, 'policy> {
self.current_subsequent_indent = self.prefix_spans(/*pending_marker_line*/ false);
self.current_line_style = style;
self.copy_line = crate::markdown_copy::CopyLine::default();
self.copy_line.block = self.blocks.current();
self.copy_line.prefix = self.copy_prefix(was_pending);
self.copy_line.continuation = self.copy_prefix(/*pending_marker_line*/ false);
self.copy_line.item_prefix = self.copy_prefix(/*pending_marker_line*/ true);
@@ -5,9 +5,9 @@ expression: "render_picker(params, 120)"
Keymap
All configurable shortcuts.
158 actions, 1 customized, 8 unbound.
158 actions, 1 customized, 7 unbound.
All Common Customized (1) Unbound (8) App Composer Editor Vim Navigation Agents Approval ›
All Common Customized (1) Unbound (7) App Composer Editor Vim Navigation Agents Approval ›
Type to search shortcuts
+21 -11
View File
@@ -53,7 +53,9 @@ impl TranscriptView {
});
}
if self.select_mode.is_some() {
let hints = if let Some(mark) = self.table_mark() {
let hints = if let Some(hints) = self.block_mark_hints() {
hints
} else if let Some(mark) = self.table_mark() {
let (full, short, minimal) =
if mark.kind == super::select_mode::table::TableMarkKind::Text {
(
@@ -63,14 +65,17 @@ impl TranscriptView {
)
} else {
(
"arrows/hjkl extend cells · v mark text · o swap · y copy · esc clear",
"arrows move · v mark text · y copy",
concat!(
"arrows/hjkl extend cells · tab expand to table",
" · v mark text · o swap · y copy · esc clear"
),
"arrows extend · v mark text · y copy",
"v mark text · y copy",
)
};
[full, short, minimal, "esc clear"].map(str::to_owned)
} else if !has_selected_text
&& self.select_cursor_is_on_table()
&& let Some(label) = self.block_hint()
&& let Some(mark) = self
.disclosure
.keymap
@@ -79,11 +84,11 @@ impl TranscriptView {
let mark = mark.display_label();
[
format!(
"arrows/hjkl move · v mark text · V mark lines · {mark} mark cell · / find · q close"
"arrows/hjkl move · v mark text · V mark lines · {mark} mark {label} · / find · q close"
),
format!("arrows move · {mark} mark cell · v mark text"),
format!("{mark} mark cell · q close"),
format!("{mark} mark cell"),
format!("arrows move · {mark} mark {label} · v mark text"),
format!("{mark} mark {label} · q close"),
format!("{mark} mark {label}"),
]
} else if has_selected_text {
let copy = crate::key_hint::ctrl(KeyCode::Char('c')).display_label();
@@ -307,9 +312,9 @@ pub(super) fn navigation_line(navigation: &str) -> Line<'static> {
" clear selection",
" copy+↓",
" extend cells",
" mark cell",
" mark text",
" mark lines",
" extend",
" expand",
" shrink",
" move in cell",
" move",
" ends",
@@ -335,6 +340,11 @@ pub(super) fn navigation_line(navigation: &str) -> Line<'static> {
if let Some(action) = action {
spans.extend(key_label_spans(&hint[..hint.len() - action.len()]));
spans.push(action.dim());
} else if let Some(at) = hint.rfind(" mark ").or_else(|| hint.rfind(" expand to ")) {
// The Markdown target can be several words (e.g. "list item").
let (key, action) = hint.split_at(at);
spans.extend(key_label_spans(key));
spans.push(action.to_owned().dim());
} else if hint == "esc" {
spans.extend(key_label_spans(hint));
} else {
+1 -1
View File
@@ -333,7 +333,7 @@ impl TranscriptView {
mode.table_caret = origin.table_caret;
mode.preferred_column = origin.preferred_column;
selection.set_keyboard_range(origin.start, origin.end);
if self.table_mark().is_some() {
if self.table_mark().is_some() || self.marked_block().is_some() {
self.sync_select_range(cells);
}
}
+50 -19
View File
@@ -15,6 +15,7 @@ use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use unicode_segmentation::UnicodeSegmentation;
mod blocks;
mod motion;
pub(super) mod table;
@@ -33,7 +34,34 @@ pub(super) struct Mark {
anchor_edges: Option<(Anchor, Anchor)>,
active_edges: Option<(Anchor, Anchor)>,
unit: SelectionUnit,
table: Option<table::TableMark>,
scope: Scope,
}
#[derive(Clone, Copy)]
enum Scope {
Text,
Table(table::TableMark),
Block(blocks::BlockMark),
}
impl Mark {
fn at(cursor: Anchor, unit: SelectionUnit) -> Self {
Self {
anchor: cursor,
active: cursor,
anchor_edges: None,
active_edges: None,
unit,
scope: Scope::Text,
}
}
fn table(self) -> Option<table::TableMark> {
match self.scope {
Scope::Table(table) => Some(table),
Scope::Text | Scope::Block(_) => None,
}
}
}
#[derive(Clone, Copy)]
@@ -93,7 +121,7 @@ impl SelectMode {
self.table_caret = self
.mark
.take()
.and_then(|mark| mark.table)
.and_then(Mark::table)
.map(|table| table.active)
.or(self.table_caret);
self.preferred_column = None;
@@ -105,7 +133,7 @@ impl SelectMode {
fn padding_column(self, width: u16) -> Option<u16> {
self.mark
.and_then(|mark| mark.table.map(|table| table.active))
.and_then(|mark| mark.table().map(|table| table.active))
.or(self.table_caret)
.and_then(|cell| cell.padding_column)
.map(|column| column.min(width.saturating_sub(1)))
@@ -241,10 +269,13 @@ impl TranscriptView {
}
if pressed
&& self.disclosure.keymap.pager.mark_markdown.is_pressed(key)
&& self.start_select_table(cells)
&& self.toggle_markdown(cells)
{
return Some(ViewAction::Changed);
}
if pressed && self.change_block_level(cells, code, modifiers) {
return Some(ViewAction::Changed);
}
if pressed && code == KeyCode::Char('o') && modifiers == KeyModifiers::NONE {
self.swap_select_ends(cells);
return Some(ViewAction::Changed);
@@ -271,6 +302,8 @@ impl TranscriptView {
) => {
if matches!(code, KeyCode::Up | KeyCode::Down) {
CursorMotion::Rows(if code == KeyCode::Up { -1 } else { 1 })
} else if shift_arrow && self.marked_block().is_some() {
return Some(ViewAction::Changed);
} else {
CursorMotion::Character(code)
}
@@ -333,24 +366,17 @@ impl TranscriptView {
};
let cursor = mode.cursor(selection);
mode.mark = match mode.mark {
Some(mark) if mark.unit == unit && mark.table.is_none() => {
Some(mark) if mark.unit == unit && matches!(mark.scope, Scope::Text) => {
self.clear_select_mark();
return;
}
Some(mark) if mark.table.is_none() => Some(Mark {
Some(mark) if matches!(mark.scope, Scope::Text) => Some(Mark {
anchor_edges: None,
active_edges: None,
unit,
..mark
}),
_ => Some(Mark {
anchor: cursor,
active: cursor,
anchor_edges: None,
active_edges: None,
unit,
table: None,
}),
_ => Some(Mark::at(cursor, unit)),
};
mode.preferred_column = None;
mode.table_caret = None;
@@ -381,8 +407,10 @@ impl TranscriptView {
};
std::mem::swap(&mut mark.anchor, &mut mark.active);
std::mem::swap(&mut mark.anchor_edges, &mut mark.active_edges);
if let Some(table) = &mut mark.table {
std::mem::swap(&mut table.anchor, &mut table.active);
match &mut mark.scope {
Scope::Text => {}
Scope::Table(table) => std::mem::swap(&mut table.anchor, &mut table.active),
Scope::Block(block) => block.swap(),
}
mode.preferred_column = None;
self.sync_select_range(cells);
@@ -467,7 +495,7 @@ impl TranscriptView {
anchor_edges: Some((start, anchor_end)),
active_edges: Some((active_start, end)),
unit,
table: None,
scope: Scope::Text,
}
} else {
let anchor = self.before_grapheme(cells, start);
@@ -483,7 +511,7 @@ impl TranscriptView {
anchor_edges: Some((anchor_start, start)),
active_edges: Some((end, active_end)),
unit,
table: None,
scope: Scope::Text,
}
}
});
@@ -531,7 +559,10 @@ impl TranscriptView {
}
mode.preferred_column = None;
mode.table_caret = None;
if mode.mark.is_some_and(|mark| mark.table.is_some()) {
if mode
.mark
.is_some_and(|mark| !matches!(mark.scope, Scope::Text))
{
mode.mark = None;
}
if let Some(mark) = &mut mode.mark {
@@ -0,0 +1,356 @@
//! A structural mark covers siblings in a single frozen layout. Horizontal motion moves
//! both ends to one sibling, while vertical motion moves the active end. The caret
//! offsets remember where to descend after selecting a parent, even for equal-sized blocks.
use super::*;
use crate::transcript_view::text::blocks::BlockRange;
#[derive(Clone, Copy)]
pub(super) struct BlockMark {
anchor: usize,
active: usize,
// Expanding a rectangle to its table can be reversed until a sibling move.
table: Option<table::TableMark>,
// The range that entered section expansion. The path from it to the current
// range lets BackTab restore the previous level, even when both cover the same text.
section_origin: Option<(usize, usize)>,
}
impl BlockMark {
pub(super) fn swap(&mut self) {
std::mem::swap(&mut self.anchor, &mut self.active);
if let Some((anchor, active)) = &mut self.section_origin {
std::mem::swap(anchor, active);
}
if let Some(table) = &mut self.table {
std::mem::swap(&mut table.anchor, &mut table.active);
}
}
fn expansion_target(self, blocks: &[BlockRange]) -> Option<usize> {
let active = blocks.get(self.active)?;
let anchor = blocks.get(self.anchor)?;
if active.expand_to() == anchor.expand_to() {
active.expand_to()
} else if active.parent == anchor.parent {
active.parent
} else {
None
}
}
}
impl TranscriptView {
fn block_context(&self) -> Option<(BlockMark, Anchor, &TextLayout)> {
let mark = self.select_mode?.mark?;
let Scope::Block(block) = mark.scope else {
return None;
};
let layout = self
.selection
.as_ref()?
.snapshot
.pinned
.get(&mark.active.key)?;
Some((block, mark.active, layout))
}
pub(in crate::transcript_view) fn marked_block(&self) -> Option<&BlockRange> {
let (block, _, layout) = self.block_context()?;
layout.blocks().get(block.active)
}
pub(in crate::transcript_view) fn block_mark_hints(&self) -> Option<[String; 4]> {
let (block, cursor, layout) = self.block_context()?;
let blocks = layout.blocks();
let current = blocks.get(block.active)?;
let label = if block.anchor == block.active {
current.label()
} else if current.heading.is_some() {
"sections"
} else {
"blocks"
};
let (expand, compact_expand) = match block.expansion_target(blocks) {
Some(parent) => (
format!(" · tab expand to {}", blocks[parent].label()),
" · tab expand",
),
None => (String::new(), ""),
};
let can_shrink = block.anchor == block.active
&& (current.heading.is_some()
|| block.section_origin.is_some()
|| block.table.is_some()
|| layout.block_at(cursor.offset) != Some(block.active));
let shrink = if can_shrink {
let backtab = crate::key_hint::shift(KeyCode::Tab).display_label();
format!(" · {backtab} shrink")
} else {
String::new()
};
let motion = "←→/hl move · ↑↓/jk extend";
Some([
format!(
"Markdown {label} · {motion}{expand}{shrink} · v mark text · y copy · esc clear"
),
format!("{label} · {motion}{compact_expand}{shrink} · y copy"),
format!("{label} · ←→ move · ↑↓ extend · y copy"),
format!("{label} · y copy"),
])
}
pub(in crate::transcript_view) fn block_hint(&self) -> Option<&'static str> {
if self.select_cursor_is_on_table() {
return Some("cell");
}
let cursor = self.select_mode?.cursor(self.selection.as_ref()?);
let layout = &self
.visible
.iter()
.find(|row| row.key == cursor.key)?
.layout;
let id = layout.block_at(cursor.offset)?;
Some(layout.blocks()[id].label())
}
pub(super) fn toggle_markdown(&mut self, cells: &[Arc<dyn HistoryCell>]) -> bool {
if self.marked_block().is_some() {
self.clear_select_mark();
return true;
}
if self.start_select_table(cells) {
return true;
}
let (Some(mode), Some(selection)) = (self.select_mode, self.selection.as_ref()) else {
return false;
};
let cursor = mode.cursor(selection);
let snapshot = self.snapshot_cells();
let cells = snapshot.as_deref().unwrap_or(cells);
let Some(layout) = self.layout(cells, self.resolve(cells, cursor)) else {
return false;
};
let Some(id) = layout.block_at(cursor.offset) else {
return false;
};
let mark = Mark::at(cursor, SelectionUnit::Character);
self.install_blocks(
cells,
mark,
BlockMark {
anchor: id,
active: id,
table: None,
section_origin: None,
},
);
true
}
fn install_blocks(&mut self, cells: &[Arc<dyn HistoryCell>], mut mark: Mark, block: BlockMark) {
mark.scope = Scope::Block(block);
self.cancel_beginning();
self.cancel_pending_select_search();
if let Some(mode) = &mut self.select_mode {
mode.mark = Some(mark);
mode.table_caret = None;
mode.preferred_column = None;
}
self.sync_select_range(cells);
self.reveal_select_cursor(cells);
}
pub(super) fn sync_block_range(
&mut self,
cells: &[Arc<dyn HistoryCell>],
mark: Mark,
block: BlockMark,
) {
let index = self.resolve(cells, mark.anchor);
let Some(layout) = self.layout(cells, index) else {
return;
};
let blocks = layout.blocks();
let (Some(a), Some(b)) = (blocks.get(block.anchor), blocks.get(block.active)) else {
self.clear_select_mark();
return;
};
let endpoint = |offset| Anchor {
index,
offset,
row_bias: 0,
..mark.anchor
};
if let Some(selection) = &mut self.selection {
selection.set_keyboard_block_range(
endpoint(a.range.start.min(b.range.start)),
endpoint(a.range.end.max(b.range.end)),
layout,
);
}
}
pub(super) fn change_block_level(
&mut self,
cells: &[Arc<dyn HistoryCell>],
code: KeyCode,
modifiers: KeyModifiers,
) -> bool {
let expand = match (code, modifiers) {
(KeyCode::Up, KeyModifiers::ALT) | (KeyCode::Tab, KeyModifiers::NONE) => true,
(KeyCode::Down, KeyModifiers::ALT) | (KeyCode::BackTab, KeyModifiers::NONE) => false,
_ => return false,
};
let Some(mut mark) = self.select_mode.and_then(|mode| mode.mark) else {
return false;
};
let snapshot = self.snapshot_cells();
let cells = snapshot.as_deref().unwrap_or(cells);
let Some(layout) = self.layout(cells, self.resolve(cells, mark.active)) else {
return false;
};
let blocks = layout.blocks();
match mark.scope {
Scope::Table(table) if expand => {
if let Some(id) = layout.block_at(mark.active.offset) {
self.install_blocks(
cells,
mark,
BlockMark {
anchor: id,
active: id,
table: Some(table),
section_origin: None,
},
);
}
}
Scope::Text | Scope::Table(_) => return false,
Scope::Block(mut block) => {
let Some(current) = blocks.get(block.active) else {
return false;
};
if expand {
if let Some(parent) = block.expansion_target(blocks) {
if blocks[parent].heading.is_some() || current.heading.is_some() {
block
.section_origin
.get_or_insert((block.anchor, block.active));
}
block.anchor = parent;
block.active = parent;
self.install_blocks(cells, mark, block);
}
} else if block.active == block.anchor {
let origins = block.section_origin.or_else(|| {
layout
.block_at(mark.anchor.offset)
.zip(layout.block_at(mark.active.offset))
});
let child = |mut id: usize| {
while id != block.active {
let parent = if block.section_origin.is_some() {
blocks[id].expand_to()
} else {
blocks[id].parent
}?;
if parent == block.active {
return Some(id);
}
id = parent;
}
None
};
let children = origins.and_then(|(a, b)| child(a).zip(child(b)));
if let Some((anchor, active)) = children {
if block.section_origin == Some((anchor, active))
&& blocks[active].heading.is_none()
{
block.section_origin = None;
}
block.anchor = anchor;
block.active = active;
self.install_blocks(cells, mark, block);
} else if let Some(heading) = current.heading {
block.anchor = heading;
block.active = heading;
block.section_origin = None;
self.install_blocks(cells, mark, block);
} else if let Some(table) = block.table {
mark.scope = Scope::Table(table);
if let Some(mode) = &mut self.select_mode {
mode.mark = Some(mark);
}
self.sync_select_range(cells);
}
}
}
}
true
}
pub(super) fn move_block(
&mut self,
cells: &[Arc<dyn HistoryCell>],
mut mark: Mark,
block: BlockMark,
motion: CursorMotion,
) {
let Some(layout) = self.layout(cells, self.resolve(cells, mark.active)) else {
return;
};
let blocks = layout.blocks();
let Some(current) = blocks.get(block.active) else {
return;
};
let mut siblings = blocks.iter().enumerate().filter(|(_, b)| {
b.parent == current.parent && b.heading.is_some() == current.heading.is_some()
});
let next = match motion {
CursorMotion::Character(KeyCode::Left) => siblings.rfind(|(id, _)| *id < block.active),
CursorMotion::Character(KeyCode::Right) => siblings.find(|(id, _)| *id > block.active),
CursorMotion::Rows(n) if n < 0 => siblings
.rev()
.filter(|(id, _)| *id < block.active)
.take(n.unsigned_abs())
.last(),
CursorMotion::Rows(n) => siblings
.filter(|(id, _)| *id > block.active)
.take(n.unsigned_abs())
.last(),
CursorMotion::Beginning | CursorMotion::LineStart => siblings.next(),
CursorMotion::End | CursorMotion::LineEnd => siblings.next_back(),
CursorMotion::Character(_)
| CursorMotion::WordForward
| CursorMotion::WordBackward
| CursorMotion::WordEnd => None,
};
if let Some((id, next)) = next
&& id != block.active
&& blocks.get(block.anchor).is_some()
{
mark.active = Anchor {
offset: next.range.start,
row_bias: 0,
..mark.active
};
let anchor = if matches!(motion, CursorMotion::Character(_)) {
mark.anchor = mark.active;
id
} else {
block.anchor
};
self.install_blocks(
cells,
mark,
BlockMark {
anchor,
active: id,
table: None,
section_origin: None,
},
);
}
}
}
@@ -24,8 +24,16 @@ impl TranscriptView {
let cursor = mode.cursor(selection);
let snapshot = self.snapshot_cells();
let cells = snapshot.as_deref().unwrap_or(cells);
if let Some(mark) = mode.mark
&& let Scope::Block(block) = mark.scope
{
self.move_block(cells, mark, block, motion);
return;
}
let next = match motion {
_ if let Some((mark, table)) = mode.mark.and_then(|mark| Some((mark, mark.table?))) => {
_ if let Some((mark, table)) =
mode.mark.and_then(|mark| Some((mark, mark.table()?))) =>
{
if table.kind == TableMarkKind::Cells {
self.move_select_table(cells, mode, mark, motion);
return;
@@ -319,7 +327,11 @@ impl TranscriptView {
};
let snapshot = self.snapshot_cells();
let cells = snapshot.as_deref().unwrap_or(cells);
if let Some(table) = mark.table {
if let Scope::Block(block) = mark.scope {
self.sync_block_range(cells, mark, block);
return;
}
if let Some(table) = mark.table() {
self.sync_select_table(cells, mark, table);
return;
}
@@ -35,7 +35,7 @@ fn table_hit(layout: &TextLayout, cursor: Anchor) -> Option<TableCellHit> {
impl TranscriptView {
pub(in crate::transcript_view) fn table_mark(&self) -> Option<TableMark> {
self.select_mode?.mark?.table
self.select_mode?.mark?.table()
}
pub(in crate::transcript_view) fn select_cursor_is_on_table(&self) -> bool {
@@ -71,7 +71,7 @@ impl TranscriptView {
};
let cell = mode
.mark
.and_then(|mark| mark.table.map(|table| table.active))
.and_then(|mark| mark.table().map(|table| table.active))
.or(mode.table_caret)
.or_else(|| {
table_hit(&layout, cursor).map(|hit| CellPosition {
@@ -84,16 +84,12 @@ impl TranscriptView {
self.cancel_pending_select_search();
self.cancel_beginning();
mode.mark = Some(Mark {
anchor: cursor,
active: cursor,
anchor_edges: None,
active_edges: None,
unit: SelectionUnit::Character,
table: Some(TableMark {
scope: Scope::Table(TableMark {
anchor: cell,
active: cell,
kind: TableMarkKind::Cells,
}),
..Mark::at(cursor, SelectionUnit::Character)
});
mode.preferred_column = None;
self.select_mode = Some(mode);
@@ -105,7 +101,7 @@ impl TranscriptView {
let Some(mut mode) = self.select_mode else {
return;
};
let Some((mut mark, table)) = mode.mark.and_then(|mark| Some((mark, mark.table?))) else {
let Some((mut mark, table)) = mode.mark.and_then(|mark| Some((mark, mark.table()?))) else {
return;
};
if table.kind == TableMarkKind::Text {
@@ -141,7 +137,7 @@ impl TranscriptView {
};
mark.anchor = cursor;
mark.active = cursor;
mark.table = Some(TableMark {
mark.scope = Scope::Table(TableMark {
anchor: cell,
active: cell,
kind: TableMarkKind::Text,
@@ -275,7 +271,9 @@ impl TranscriptView {
mut mark: Mark,
motion: CursorMotion,
) {
let Some(table) = &mut mark.table else { return };
let Scope::Table(table) = &mut mark.scope else {
return;
};
let (row, column) = table.active.cell;
let cell = match motion {
CursorMotion::Character(KeyCode::Left) => column.checked_sub(1).map(|col| (row, col)),
@@ -806,11 +806,7 @@ fn select_mode_renders_cursor_and_scannable_footer_hints() {
));
}
fn select_table_at_match(
cells: &[Arc<dyn HistoryCell>],
width: u16,
query: &str,
) -> TranscriptView {
fn select_at_match(cells: &[Arc<dyn HistoryCell>], width: u16, query: &str) -> TranscriptView {
let mut view = TranscriptView::default();
crate::transcript_view::tests::render(&mut view, cells, width, /*height*/ 32);
assert!(view.begin_select_mode(cells));
@@ -821,14 +817,8 @@ fn select_table_at_match(
view
}
// These view tests receive the semantic event produced by the app's chord router.
fn mark_markdown(view: &mut TranscriptView, cells: &[Arc<dyn HistoryCell>]) {
let key = crate::keymap::dispatch_event(crate::keymap::KeymapActionId {
context: crate::keymap::KeymapContext::Pager,
action: "mark_markdown",
})
.unwrap();
press(view, cells, key.code);
press(view, cells, KeyCode::Char('m'));
}
#[test]
@@ -837,7 +827,7 @@ fn keyboard_table_mark_selects_cells_and_swaps_rectangle_corners() {
"| Left | Right |\n|---|---|\n| alpha | Beta |\n| Gamma | delta |".into(),
std::path::Path::new("/"),
))];
let mut view = select_table_at_match(&cells, /*width*/ 32, "Beta");
let mut view = select_at_match(&cells, /*width*/ 32, "Beta");
let footer = |view: &TranscriptView| {
view.footer_with_navigation(/*width*/ 32, crate::motion::MotionMode::Reduced, "")
.unwrap()
@@ -898,7 +888,7 @@ fn keyboard_table_header_rectangle_excludes_record_values() {
std::path::Path::new("/"),
)) as Arc<dyn HistoryCell>];
for width in [10, 32] {
let mut view = select_table_at_match(&cells, width, "Left");
let mut view = select_at_match(&cells, width, "Left");
mark_markdown(&mut view, &cells);
press(&mut view, &cells, KeyCode::Right);
assert_eq!(
@@ -916,7 +906,7 @@ fn shift_click_extends_from_the_fixed_in_cell_text_anchor() {
std::path::Path::new("/"),
)) as Arc<dyn HistoryCell>];
for (motion, target, expected) in [(KeyCode::Left, "e", "bcd"), (KeyCode::Right, "a", "ab")] {
let mut view = select_table_at_match(&cells, /*width*/ 32, "bcd");
let mut view = select_at_match(&cells, /*width*/ 32, "bcd");
mark_markdown(&mut view, &cells);
press(&mut view, &cells, KeyCode::Char('v'));
press(&mut view, &cells, motion);
@@ -953,7 +943,7 @@ fn in_cell_word_motion_projects_boundaries_past_escaped_pipes() {
format!("| {header} | B |\n|---|---|"),
std::path::Path::new("/"),
)) as Arc<dyn HistoryCell>];
let mut view = select_table_at_match(&cells, /*width*/ 8, query);
let mut view = select_at_match(&cells, /*width*/ 8, query);
mark_markdown(&mut view, &cells);
press(&mut view, &cells, KeyCode::Char('v'));
press(&mut view, &cells, KeyCode::Char(motion));
@@ -970,7 +960,7 @@ fn shift_click_replaces_the_cell_mark_at_the_same_endpoint() {
"| Left | Right |\n|---|---|\n| alpha | Beta |\n| Gamma | delta |".into(),
std::path::Path::new("/"),
)) as Arc<dyn HistoryCell>];
let mut view = select_table_at_match(&cells, /*width*/ 32, "Beta");
let mut view = select_at_match(&cells, /*width*/ 32, "Beta");
mark_markdown(&mut view, &cells);
press(&mut view, &cells, KeyCode::Down);
crate::transcript_view::tests::render(&mut view, &cells, /*width*/ 32, /*height*/ 12);
@@ -1009,7 +999,7 @@ fn keyboard_cell_word_motion_crosses_a_wrapped_identifier() {
"| Name | Value |\n|---|---|\n| abcdefghijklmnop next | 1 |".into(),
std::path::Path::new("/"),
)) as Arc<dyn HistoryCell>];
let mut view = select_table_at_match(&cells, /*width*/ 12, "abcd");
let mut view = select_at_match(&cells, /*width*/ 12, "abcd");
mark_markdown(&mut view, &cells);
press(&mut view, &cells, KeyCode::Char('v'));
press(&mut view, &cells, KeyCode::Char('e'));
@@ -1032,7 +1022,7 @@ fn keyboard_table_motion_skips_record_labels_and_reaches_empty_cells() {
std::path::Path::new("/"),
))];
for width in [32, 10] {
let mut view = select_table_at_match(&cells, width, "Beta");
let mut view = select_at_match(&cells, width, "Beta");
mark_markdown(&mut view, &cells);
press(&mut view, &cells, KeyCode::Char('j'));
press(&mut view, &cells, KeyCode::Char('j'));
@@ -1068,7 +1058,7 @@ fn keyboard_cell_text_crosses_wraps_without_selecting_neighbors() {
std::path::Path::new("/"),
))];
for width in [34, 12] {
let mut view = select_table_at_match(&cells, width, "界");
let mut view = select_at_match(&cells, width, "界");
mark_markdown(&mut view, &cells);
press(&mut view, &cells, KeyCode::Char('v'));
assert_eq!(view.selected_text(&cells).as_deref(), Some("界"));
@@ -1116,3 +1106,364 @@ fn keyboard_cell_text_crosses_wraps_without_selecting_neighbors() {
);
}
}
fn marked_markdown_at(
markdown: &str,
width: u16,
query: &str,
) -> (TranscriptView, [Arc<dyn HistoryCell>; 1]) {
let cells: [Arc<dyn HistoryCell>; 1] = [Arc::new(AgentMarkdownCell::new(
markdown.into(),
std::path::Path::new("/"),
))];
let mut view = select_at_match(&cells, width, query);
mark_markdown(&mut view, &cells);
(view, cells)
}
#[test]
fn markdown_mark_copies_wrapped_siblings_from_the_displayed_revision() {
let (mut view, cells) = marked_markdown_at(
"## Release notes\n\nRead the **界 changes** before updating.\n\nRead the **界 changes** before updating.",
/*width*/ 20,
"Release",
);
assert_eq!(
view.selected_text(&cells).as_deref(),
Some("## Release notes")
);
press(&mut view, &cells, KeyCode::Down);
let pair = "## Release notes\n\nRead the **界 changes** before updating.";
assert_eq!(view.selected_text(&cells).as_deref(), Some(pair));
press(&mut view, &cells, KeyCode::Tab);
let section = format!("{pair}\n\nRead the **界 changes** before updating.");
press(&mut view, &cells, KeyCode::Char('/'));
press(&mut view, &cells, KeyCode::Esc);
let updated = [cell(&["new revision"])];
let painted = crate::transcript_view::tests::render(
&mut view, &updated, /*width*/ 24, /*height*/ 8,
);
let hints = [120, 45].map(|width| {
view.footer_with_navigation(width, crate::motion::MotionMode::Reduced, "")
.unwrap()
.text
.to_string()
});
let selected = painted
.content()
.chunks(24)
.map(|row| {
row.iter()
.filter(|c| c.modifier.contains(ratatui::style::Modifier::REVERSED))
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
.trim_end()
.to_owned()
})
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(format!("{}\n{}", selected.trim_end(), hints.join("\n")));
let Some(ViewAction::Copy(text)) = view.handle_key(KeyCode::Char('y').into(), &updated) else {
panic!("expected copy")
};
view.copy_selected_text_with(
&updated,
&text,
/*clear_selection*/ false,
|text, format| {
assert_eq!(
(text, format),
(
section.as_str(),
crate::clipboard_copy::CopyFormat::Markdown
)
);
Ok(CopyStatus::Confirmed)
},
)
.unwrap();
press(&mut view, &updated, KeyCode::BackTab);
assert_eq!(view.selected_text(&updated).as_deref(), Some(pair));
press(&mut view, &updated, KeyCode::Char('o'));
press(&mut view, &updated, KeyCode::Down);
assert_eq!(
view.selected_text(&updated).as_deref(),
Some("Read the **界 changes** before updating.")
);
}
#[test]
fn markdown_mark_expands_and_moves_between_sections() {
let macos = "### macOS\n\nOpen the **disk image**.\n\nDrag the app.";
let linux = "### Linux\n\nUnpack the archive.\n\n***";
let platforms = format!("{macos}\n\n{linux}");
let install = format!("## Install\n\n{platforms}");
let (mut view, cells) = marked_markdown_at(
&format!("{install}\n\n## Usage"),
/*width*/ 32,
"macOS",
);
assert_eq!(view.selected_text(&cells).as_deref(), Some("### macOS"));
for (key, expected) in [
(KeyCode::Right, "Open the **disk image**."),
(KeyCode::Left, "### macOS"),
(KeyCode::Tab, macos),
(KeyCode::Char('l'), linux),
(KeyCode::BackTab, "### Linux"),
(KeyCode::Tab, linux),
(KeyCode::Char('h'), macos),
(KeyCode::Char('j'), platforms.as_str()),
(KeyCode::Tab, install.as_str()),
(KeyCode::BackTab, platforms.as_str()),
(KeyCode::Char('k'), macos),
(KeyCode::Tab, install.as_str()),
(KeyCode::BackTab, macos),
] {
press(&mut view, &cells, key);
assert_eq!(
view.selected_text(&cells).as_deref(),
Some(expected),
"{key:?}"
);
}
}
#[test]
fn markdown_sections_respect_heading_rank_and_parser_containers() {
let (mut view, cells) = marked_markdown_at(
"# Guide\n\n> Intro\n> -----\n>\n> #### Example\n>\n> ```sh\n> # a comment\n> ```\n\nOutside the quote.\n\n# Usage",
/*width*/ 40,
"Example",
);
for (key, expected) in [
(KeyCode::Tab, "#### Example\n\n```sh\n# a comment\n```"),
(
KeyCode::Tab,
"## Intro\n\n#### Example\n\n```sh\n# a comment\n```",
),
(KeyCode::BackTab, "#### Example\n\n```sh\n# a comment\n```"),
(KeyCode::BackTab, "#### Example"),
] {
press(&mut view, &cells, key);
assert_eq!(
view.selected_text(&cells).as_deref(),
Some(expected),
"{key:?}"
);
}
}
#[test]
fn markdown_mark_expands_nested_items_and_recovers_original_sibling_range() {
let (mut view, cells) = marked_markdown_at(
"- First\n- Parent\n - **Nested**\n - Second\n - Third\n- Last",
/*width*/ 32,
"Nested",
);
assert_eq!(view.selected_text(&cells).as_deref(), Some("- **Nested**"));
press(&mut view, &cells, KeyCode::Char('j'));
let pair = "- **Nested**\n- Second";
assert_eq!(view.selected_text(&cells).as_deref(), Some(pair));
// Move from the active end of the pair, staying within the nested list.
for (key, expected) in [
(KeyCode::Char('l'), "- Third"),
(KeyCode::Right, "- Third"),
(KeyCode::Left, "- Second"),
(KeyCode::Tab, "- **Nested**\n- Second\n- Third"),
(KeyCode::BackTab, "- Second"),
(KeyCode::Char('h'), "- **Nested**"),
(KeyCode::Left, "- **Nested**"),
(KeyCode::Right, "- Second"),
(KeyCode::Char('k'), pair),
] {
press(&mut view, &cells, key);
assert_eq!(
view.selected_text(&cells).as_deref(),
Some(expected),
"{key:?}"
);
}
press(&mut view, &cells, KeyCode::Char('o'));
press(&mut view, &cells, KeyCode::Tab);
assert_eq!(
view.selected_text(&cells).as_deref(),
Some("- **Nested**\n- Second\n- Third")
);
let hints = [120, 40].map(|width| {
use ratatui::style::Modifier;
let footer = view
.footer_with_navigation(width, crate::motion::MotionMode::Reduced, "")
.unwrap();
footer.text.lines[0]
.spans
.iter()
.map(|span| {
if span.style.add_modifier.contains(Modifier::BOLD) {
format!("**{}**", span.content)
} else {
span.content.to_string()
}
})
.collect::<String>()
});
insta::assert_snapshot!("markdown_list_footer", hints.join("\n"));
press(&mut view, &cells, KeyCode::Tab);
assert_eq!(
view.selected_text(&cells).as_deref(),
Some("- Parent\n - **Nested**\n - Second\n - Third")
);
press(&mut view, &cells, KeyCode::BackTab);
press(&mut view, &cells, KeyCode::BackTab);
assert_eq!(view.selected_text(&cells).as_deref(), Some(pair));
press(&mut view, &cells, KeyCode::Char('v'));
assert_eq!(view.selected_text(&cells).as_deref(), Some("S"));
}
#[test]
fn markdown_mark_copies_code_with_language_and_only_selected_quote_levels() {
let (mut view, cells) = marked_markdown_at(
"> > ```rust\n> > let example = 1;\n> >\n> > example\n> > ```",
/*width*/ 16,
"example",
);
let code = "```rust\nlet example = 1;\n\nexample\n```";
assert_eq!(view.selected_text(&cells).as_deref(), Some(code));
view.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::ALT), &cells);
assert_eq!(
view.selected_text(&cells).as_deref(),
Some("> ```rust\n> let example = 1;\n> \n> example\n> ```")
);
view.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::ALT), &cells);
assert_eq!(view.selected_text(&cells).as_deref(), Some(code));
}
#[test]
fn markdown_mark_copies_empty_items_at_the_edges_of_a_list() {
let (mut view, cells) =
marked_markdown_at("- [ ] \n- [x] Done\n- [ ] ", /*width*/ 32, "Done");
press(&mut view, &cells, KeyCode::Tab); // Paragraph to item.
press(&mut view, &cells, KeyCode::Tab); // Item to list.
assert_eq!(
view.selected_text(&cells).as_deref(),
Some("- [ ] \n- [x] Done\n- [ ] ")
);
let buffer = render(&mut view, &cells);
let highlighted: Vec<_> = buffer
.content()
.chunks(usize::from(buffer.area.width))
.map(|row| {
row.iter()
.filter(|cell| cell.modifier.contains(ratatui::style::Modifier::REVERSED))
.map(ratatui::buffer::Cell::symbol)
.collect::<String>()
})
.map(|row| row.trim().to_owned())
.filter(|row| !row.is_empty())
.collect();
insta::assert_snapshot!(highlighted.join("\n"), @"
• ☐
☑ Done
☐
");
press(&mut view, &cells, KeyCode::BackTab);
press(&mut view, &cells, KeyCode::Right);
assert_eq!(view.selected_text(&cells).as_deref(), Some("- [ ] "));
}
#[test]
fn markdown_mark_can_start_on_a_list_with_no_item_text() {
let cells: [Arc<dyn HistoryCell>; 1] = [Arc::new(AgentMarkdownCell::new(
"- [ ] \n- [x] ".into(),
std::path::Path::new("/"),
))];
let mut view = TranscriptView::default();
render(&mut view, &cells);
assert!(view.begin_select_mode(&cells));
mark_markdown(&mut view, &cells);
assert_eq!(view.selected_text(&cells).as_deref(), Some("- [x] "));
press(&mut view, &cells, KeyCode::Tab);
assert_eq!(
view.selected_text(&cells).as_deref(),
Some("- [ ] \n- [x] ")
);
}
#[test]
fn markdown_mark_fences_rendered_mermaid_as_plain_code() {
let (mut view, cells) = marked_markdown_at(
"```mermaid\nflowchart LR\nA[Start] --> B[Finish]\n```",
/*width*/ 80,
"Finish",
);
let text = view.selected_text(&cells).unwrap();
let body = text
.strip_prefix("```\n")
.and_then(|text| text.strip_suffix("\n```"))
.unwrap();
assert!(body.contains("Start") && body.contains("Finish"));
assert!(!body.contains("flowchart LR"));
}
#[test]
fn markdown_mark_can_round_trip_from_rectangle_to_table() {
let table = "| Left | Right |\n|---|---|\n| alpha | **Beta** |\n| Gamma | delta |";
for width in [10, 32] {
let (mut view, cells) = marked_markdown_at(table, width, "Beta");
press(&mut view, &cells, KeyCode::Down);
let rectangle = view.selected_text(&cells).unwrap();
press(&mut view, &cells, KeyCode::Tab);
assert_eq!(view.selected_text(&cells).as_deref(), Some(table));
press(&mut view, &cells, KeyCode::BackTab);
assert_eq!(view.selected_text(&cells), Some(rectangle));
}
}
#[test]
fn markdown_mark_copies_the_visible_task_label_and_only_the_selected_container() {
let (mut view, cells) = marked_markdown_at(
"- [x] :codex-followup[Check **status**]{prompt=\"hidden instruction\"}\n\n Read the logs.\n\n- [ ] Retry",
/*width*/ 24,
"status",
);
assert_eq!(
view.selected_text(&cells).as_deref(),
Some("Check **status**")
);
press(&mut view, &cells, KeyCode::Tab);
assert_eq!(
view.selected_text(&cells).as_deref(),
Some("- [x] Check **status**\n\n Read the logs.")
);
}
#[test]
fn markdown_mark_expands_the_live_table_at_the_revision_seen_before_the_next_delta() {
let mut stream = crate::streaming::controller::StreamController::new(
/*width*/ Some(32),
std::path::Path::new("/"),
crate::history_cell::HistoryRenderMode::Rich,
);
stream.push("| Left | Right |\n|---|---|\n| alpha | **Beta** |\n");
let mut view = TranscriptView::default();
view.sync_live_tail(
/*width*/ 32,
/*key*/ None,
|_| Some(stream.current_tail_lines()),
);
render(&mut view, &[]);
assert!(view.begin_select_mode(&[]));
mark_markdown(&mut view, &[]);
stream.push("| newer | delta |\n");
view.sync_live_tail(
/*width*/ 32,
/*key*/ None,
|_| Some(stream.current_tail_lines()),
);
render(&mut view, &[]);
press(&mut view, &[], KeyCode::Tab);
assert_eq!(
view.selected_text(&[]).as_deref(),
Some("| Left | Right |\n|---|---|\n| alpha | **Beta** |")
);
}
+32 -8
View File
@@ -168,6 +168,19 @@ impl Selection {
self.preferred_column = None;
}
pub(super) fn set_keyboard_block_range(
&mut self,
start: Anchor,
end: Anchor,
layout: Arc<TextLayout>,
) {
self.snapshot.pinned.entry(start.key).or_insert(layout);
self.set_keyboard_range(start, end);
// A parent and child can have identical bounds but different clipboard syntax.
self.primary_owner = None;
self.pending_copy = None;
}
pub(super) fn set_keyboard_table_range(
&mut self,
entry: Anchor,
@@ -465,7 +478,7 @@ impl TranscriptView {
&mut self,
cells: &[Arc<dyn HistoryCell>],
) -> Option<Vec<(Arc<TextLayout>, std::ops::Range<usize>)>> {
if !self.has_selection_range() {
if !self.has_selection_range() && self.marked_block().is_none() {
return None;
}
let snapshot = self.snapshot_cells();
@@ -504,6 +517,12 @@ impl TranscriptView {
}
pub(crate) fn selected_text(&mut self, cells: &[Arc<dyn HistoryCell>]) -> Option<String> {
if let Some(block) = self.marked_block() {
let outer_prefix = block.outer_prefix;
let lines = self.selected_copy_lines(cells);
let text = crate::markdown_copy::block_selection(&lines, outer_prefix);
return (!text.is_empty()).then_some(text);
}
if let Some(table) = self.table_selection() {
let rectangle_rows = table.rectangle_rows();
let lines = self.selected_copy_lines(cells);
@@ -577,10 +596,6 @@ impl TranscriptView {
crate::clipboard_copy::CopyFormat,
) -> Result<crate::clipboard_copy::CopyStatus, String>,
) -> Result<crate::clipboard_copy::CopyStatus, String> {
let lines = self.selected_copy_lines(cells);
let rectangle_rows = self
.table_selection()
.and_then(TableSelection::rectangle_rows);
let override_payload = self.copy_mode.as_ref().and_then(|mode| {
if mode.whole {
mode.response.as_ref().map(|(_, text)| {
@@ -596,6 +611,13 @@ impl TranscriptView {
}
});
let (text, format) = override_payload.unwrap_or_else(|| {
if self.marked_block().is_some() {
return (text.to_owned(), CopyFormat::Markdown);
}
let lines = self.selected_copy_lines(cells);
let rectangle_rows = self
.table_selection()
.and_then(TableSelection::rectangle_rows);
let (serialized, format) =
crate::markdown_copy::selection(&lines, text, rectangle_rows.as_ref());
if format == CopyFormat::Markdown {
@@ -881,6 +903,7 @@ impl TranscriptView {
} else {
(selection.end, selection.start)
};
let marked_block = self.marked_block().is_some();
for (y, visible) in self.visible.iter().enumerate() {
if visible.index < start.index || visible.index > end.index {
continue;
@@ -901,9 +924,10 @@ impl TranscriptView {
self.area.width,
/*height*/ 1,
);
if self.copy_mode.is_some() {
// Full-entry selections include final padding; partial ranges stay half-open.
let last = if begin == 0 && finish == visible.layout.text().len() {
if self.copy_mode.is_some() || marked_block {
// Block ranges end on the final logical line, even when it is marker-only.
let last = if marked_block || (begin == 0 && finish == visible.layout.text().len())
{
finish
} else {
finish.saturating_sub(/*rhs*/ 1)
@@ -1,9 +1,8 @@
---
source: tui/src/transcript_view/select_mode_tests.rs
assertion_line: 881
expression: "format!(\"{before}\\n{highlight}\\n{}\", footer(&view))"
---
⌃x v mark cell · q close
m mark cell · q close
alpha Beta
@@ -0,0 +1,6 @@
---
source: tui/src/transcript_view/select_mode_tests.rs
expression: hints.join("\n")
---
Markdown list · **←→/hl** move · **↑↓/jk** extend · **tab** expand to list item · **⇧tab** shrink · **v** mark text · **y** copy · **esc** clear
list · **←→** move · **↑↓** extend · **y** copy
@@ -0,0 +1,14 @@
---
source: tui/src/transcript_view/select_mode_tests.rs
assertion_line: 1165
expression: "format!(\"{}\\n{}\", selected.trim_end(), hints.join(\"\\n\"))"
---
• ## Release notes
Read the 界 changes
before updating.
Read the 界 changes
before updating.
Markdown section · ←→/hl move · ↑↓/jk extend · ⇧tab shrink · v mark text · y copy · esc clear
section · ←→ move · ↑↓ extend · y copy
+15
View File
@@ -10,6 +10,8 @@ use std::borrow::Cow;
use std::ops::Range;
use std::sync::Arc;
#[path = "text_blocks.rs"]
pub(super) mod blocks;
#[path = "text_logical.rs"]
mod logical;
@@ -46,6 +48,7 @@ use ratatui::text::Line;
/// One cell's logical text and its width-dependent display rows.
pub(crate) struct TextLayout {
blocks: std::sync::OnceLock<blocks::BlockIndex>,
pub(super) image: Option<std::sync::Arc<crate::transcript_image::TranscriptImage>>,
pub(super) image_left_aligned: bool,
logical: Vec<LogicalLine>,
@@ -78,6 +81,7 @@ struct TextRow {
content_width: u16,
first_column: usize,
prefix_columns: usize,
marker_only: bool,
tabs: tabs::TabStops,
}
@@ -350,6 +354,7 @@ impl TextLayout {
content_width: self.width,
first_column: indent,
prefix_columns: indent,
marker_only: false,
tabs: tabs::TabStops::default(),
},
);
@@ -724,6 +729,9 @@ impl TextLayout {
/// Return the first selectable source grapheme on a display row, excluding synthetic rows.
pub(super) fn first_cursor_position(&self, row: usize) -> Option<usize> {
let row = self.rows.get(row)?;
if row.marker_only {
return Some(row.source.start);
}
self.text[row.source.clone()]
.grapheme_indices(/*is_extended*/ true)
.next()
@@ -963,6 +971,7 @@ impl TextLayout {
}
}
Self {
blocks: Default::default(),
image: None,
image_left_aligned: false,
logical,
@@ -1060,6 +1069,12 @@ fn layout_line(logical: &LogicalLine, text_start: usize, width: u16) -> Vec<Text
content_width,
first_column: first_column + prefix_columns,
prefix_columns,
marker_only: logical.origin.range.is_empty()
&& logical
.origin
.copy
.as_ref()
.is_some_and(|copy| copy.has_list_marker()),
tabs,
}
})
@@ -0,0 +1,144 @@
//! Index Markdown ancestry in the same logical byte offsets as the transcript caret.
//! Section ranges share the index. They are added after the parser's blocks so marking
//! a caret still finds a block, while expansion can opt into heading-aware navigation.
use super::TextLayout;
use crate::markdown_copy::block::Kind;
use pulldown_cmark::HeadingLevel;
use std::collections::HashMap;
use std::ops::Range;
use std::sync::Arc;
pub(in crate::transcript_view) struct BlockRange {
pub(in crate::transcript_view) parent: Option<usize>,
pub(in crate::transcript_view) range: Range<usize>,
pub(in crate::transcript_view) outer_prefix: usize,
/// A section points to the parser block for its title.
pub(in crate::transcript_view) heading: Option<usize>,
kind: Kind,
section: Option<usize>,
}
impl BlockRange {
pub(in crate::transcript_view) fn label(&self) -> &'static str {
if self.heading.is_some() {
"section"
} else {
self.kind.label()
}
}
pub(in crate::transcript_view) fn expand_to(&self) -> Option<usize> {
self.section.or(self.parent)
}
}
pub(super) struct BlockIndex {
ranges: Vec<BlockRange>,
parser_blocks: usize,
}
impl TextLayout {
pub(in crate::transcript_view) fn blocks(&self) -> &[BlockRange] {
&self.block_index().ranges
}
fn block_index(&self) -> &BlockIndex {
self.blocks.get_or_init(|| {
let mut ids = HashMap::new();
let mut blocks: Vec<BlockRange> = Vec::new();
let mut path = Vec::new();
for (start, source) in self.logical_sources() {
let Some(copy) = &source.copy else { continue };
// Empty items carry their visible marker in the prefix.
if copy.omit || source.range.is_empty() && !copy.code && !copy.has_list_marker() {
continue;
}
let mut node = copy.block.as_ref();
while let Some(block) = node {
path.push(block);
node = block.parent.as_ref();
}
let mut parent = None;
while let Some(block) = path.pop() {
let id = *ids.entry(Arc::as_ptr(block)).or_insert_with(|| {
blocks.push(BlockRange {
parent,
range: start..start,
outer_prefix: block.outer_prefix,
heading: None,
kind: block.kind,
section: None,
});
blocks.len() - 1
});
blocks[id].range.end = start + source.range.len();
parent = Some(id);
}
}
let parser_blocks = blocks.len();
// Open headings are tracked per parser container. A nested quote or list
// item can start its own sections without cutting off the outer section.
let mut open: HashMap<Option<usize>, Vec<(HeadingLevel, usize)>> = HashMap::new();
for id in 0..parser_blocks {
let container = blocks[id].parent;
if let Kind::Heading(level) = blocks[id].kind {
let sections = open.entry(container).or_default();
while let Some(&(rank, section)) = sections.last()
&& rank >= level
{
// A standalone rule can appear between blocks without a parser
// block of its own. Keep it and drop only the trailing breaks.
let end = self.text()[..blocks[id].range.start]
.trim_end_matches('\n')
.len();
blocks[section].range.end = blocks[section].range.end.max(end);
sections.pop();
}
let section = blocks.len();
blocks.push(BlockRange {
parent: sections.last().map(|(_, id)| *id).or(container),
range: blocks[id].range.clone(),
outer_prefix: blocks[id].outer_prefix,
heading: Some(id),
kind: blocks[id].kind,
section: None,
});
sections.push((level, section));
}
if let Some(sections) = open.get(&container) {
blocks[id].section = sections.last().map(|(_, id)| *id);
for &(_, section) in sections {
blocks[section].range.end = blocks[id].range.end;
}
}
}
for (container, sections) in open {
let end = container.map_or_else(
|| self.text().trim_end_matches('\n').len(),
|id| blocks[id].range.end,
);
for (_, section) in sections {
blocks[section].range.end = blocks[section].range.end.max(end);
}
}
BlockIndex {
ranges: blocks,
parser_blocks,
}
})
}
pub(in crate::transcript_view) fn block_at(&self, offset: usize) -> Option<usize> {
let index = self.block_index();
let blocks = &index.ranges[..index.parser_blocks];
let mut at = blocks
.partition_point(|b| b.range.start <= offset)
.checked_sub(1)?;
// The caret on trailing table padding can sit at the exclusive end.
while offset > blocks[at].range.end {
at = blocks[at].parent?;
}
Some(at)
}
}