From 9d11b38fe77f2f981eb4aa1db2556105ed3f557a Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Fri, 13 Nov 2026 18:59:55 +0000 Subject: [PATCH] Add cell-aware mouse selection to transcript tables (#61380) ## What changed - Keep drags within a wrapped table cell scoped to that cell's text. Dragging into another cell selects a rectangle of complete cells. - Let triple-click select an entire cell, including from its padding, and extend or shrink the selection by dragging. - Preserve table structure, empty rows, alignment, and escaped literal pipes when copying rectangles. Keep inline Markdown formatting when copying cell text. - Support grid and stacked record layouts, and return to ordinary text selection when a character drag leaves the table or selection continues with the keyboard. ## Testing Add regression tests and highlight snapshots covering wrapped cells, reverse and repeated drags, padding, empty cells, stacked records, copy-on-select, clipboard formatting, and selection after resizing. GitOrigin-RevId: 32e9a6e7781b0a25914907a0ef8f8c28bbaa21f5 --- .../tui/src/inline_visualization_tests.rs | 3 +- codex-rs/tui/src/markdown_copy.rs | 32 +- codex-rs/tui/src/markdown_copy/table.rs | 59 +++- codex-rs/tui/src/markdown_render.rs | 19 ++ .../src/markdown_render/table_key_value.rs | 11 + codex-rs/tui/src/transcript_view/input.rs | 21 +- .../transcript_view/markdown_copy_tests.rs | 32 +- codex-rs/tui/src/transcript_view/selection.rs | 236 +++++++++++++-- ...g_selects_only_the_wrapped_table_cell.snap | 10 + ...ects_wrapped_cell_text_and_rectangles.snap | 22 ++ .../src/transcript_view/table_copy_tests.rs | 278 +++++++++++++++++- codex-rs/tui/src/transcript_view/text.rs | 191 +++++++++++- 12 files changed, 836 insertions(+), 78 deletions(-) create mode 100644 codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__tables__mouse_drag_selects_only_the_wrapped_table_cell.snap create mode 100644 codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__tables__mouse_selects_wrapped_cell_text_and_rectangles.snap diff --git a/codex-rs/tui/src/inline_visualization_tests.rs b/codex-rs/tui/src/inline_visualization_tests.rs index 43e562fa1e..40a496c2d0 100644 --- a/codex-rs/tui/src/inline_visualization_tests.rs +++ b/codex-rs/tui/src/inline_visualization_tests.rs @@ -434,7 +434,8 @@ fn finalized_agent_cell_replays_visualization_link() { start..start + "file://".len(), "", ); - let (copied, format) = crate::markdown_copy::selection(&selected, "file://"); + let (copied, format) = + crate::markdown_copy::selection(&selected, "file://", /*rectangle_rows*/ None); assert_eq!( (copied.as_str(), format), ("file://", crate::clipboard_copy::CopyFormat::Markdown) diff --git a/codex-rs/tui/src/markdown_copy.rs b/codex-rs/tui/src/markdown_copy.rs index 624621b268..6ba17914a0 100644 --- a/codex-rs/tui/src/markdown_copy.rs +++ b/codex-rs/tui/src/markdown_copy.rs @@ -6,6 +6,7 @@ //! rather than reproducing the complete response's source spelling (available through `/copy`). use std::ops::Range; +use std::ops::RangeInclusive; use std::sync::Arc; use pulldown_cmark::Event; @@ -382,21 +383,31 @@ impl SelectedLine { } } -pub(crate) fn selection(lines: &[SelectedLine], plain: &str) -> (String, CopyFormat) { - render_selection(lines, plain, SelectionOutput::Markdown) +pub(crate) fn selection( + lines: &[SelectedLine], + plain: &str, + rectangle_rows: Option<&RangeInclusive>, +) -> (String, CopyFormat) { + render_selection(lines, plain, rectangle_rows, SelectionOutput::Markdown) } -pub(crate) fn literal_selection(lines: &[SelectedLine], plain: &str) -> String { - render_selection(lines, plain, SelectionOutput::PlainText).0 +pub(crate) fn literal_selection( + lines: &[SelectedLine], + plain: &str, + rectangle_rows: Option<&RangeInclusive>, +) -> String { + render_selection(lines, plain, rectangle_rows, SelectionOutput::PlainText).0 } fn render_selection( lines: &[SelectedLine], plain: &str, + rectangle_rows: Option<&RangeInclusive>, output: SelectionOutput, ) -> (String, CopyFormat) { // Soft wraps and streamed fragments of the same logical line are already coalesced. - if let [line] = lines + if rectangle_rows.is_none() + && let [line] = lines && line .source .copy @@ -454,8 +465,8 @@ fn render_selection( } else { lines }; - let rich = lines.iter().any(|line| { - !line.range.is_empty() + let rich = lines.iter().enumerate().any(|(index, line)| { + (!line.range.is_empty() || index == 0 && rectangle_rows.is_some()) && line .source .copy @@ -491,7 +502,9 @@ fn render_selection( indentation = Some(indentation.map_or(spaces, |previous| previous.min(spaces))); } let prefix = dedent(prefix, indentation.unwrap_or(/*default*/ 0)); - if line.range.is_empty() { + // 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.source.text.is_empty() { out.push_str(prefix.trim_end()); } @@ -516,7 +529,8 @@ fn render_selection( selected.extend(lines.next()); } let entire_selection = first && lines.peek().is_none(); - let (mut body, format) = table::render(&selected, table, entire_selection, output); + let (mut body, format) = + table::render(&selected, table, entire_selection, rectangle, output); if format == CopyFormat::PlainText { body.retain(|ch| !ch.is_control() || matches!(ch, '\n' | '\t')); return (body, format); diff --git a/codex-rs/tui/src/markdown_copy/table.rs b/codex-rs/tui/src/markdown_copy/table.rs index e4f3b375b3..8e00fb5337 100644 --- a/codex-rs/tui/src/markdown_copy/table.rs +++ b/codex-rs/tui/src/markdown_copy/table.rs @@ -12,6 +12,7 @@ use crate::terminal_hyperlinks::HyperlinkLine; use crate::terminal_hyperlinks::LogicalLineSource; use std::collections::BTreeMap; use std::ops::Range; +use std::ops::RangeInclusive; use std::sync::Arc; #[cfg(test)] @@ -21,6 +22,10 @@ mod tests; #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct TableLine { pub(crate) table: Arc<[&'static str]>, + // Exclusive column boundaries shared by every visual line in the grid. + pub(crate) grid_columns: Option>, + /// Body row displayed by this occurrence of a stacked record. + pub(crate) record_row: Option, fragments: Vec, } @@ -33,9 +38,42 @@ struct Fragment { } impl TableLine { + pub(crate) fn cell_at(&self, offset: usize, column: usize) -> Option<(usize, usize)> { + // A byte offset inside a fragment identifies the cell's text. + if let Some(fragment) = self.fragments.iter().find(|f| f.output.contains(&offset)) { + return Some((fragment.row, fragment.column)); + } + // In a grid, use terminal column boundaries to resolve padding hits. + if let Some(ends) = &self.grid_columns { + let index = ends.partition_point(|end| *end <= column); + return (index < ends.len()).then_some((self.fragments.first()?.row, index)); + } + // In record and pipe layouts, check the space beside each fragment. + self.fragments + .iter() + .find(|f| (f.output.start.saturating_sub(1)..=f.output.end).contains(&offset)) + .map(|f| (f.row, f.column)) + } + + pub(crate) fn cell_range( + &self, + rows: &RangeInclusive, + columns: &RangeInclusive, + ) -> Option> { + let mut fragments = self + .fragments + .iter() + .filter(|fragment| rows.contains(&fragment.row) && columns.contains(&fragment.column)); + let first = fragments.next()?; + let last = fragments.next_back().unwrap_or(first); + Some(first.output.start..last.output.end) + } + pub(crate) fn empty(table: &Arc<[&'static str]>) -> Self { Self { table: Arc::clone(table), + grid_columns: None, + record_row: None, fragments: Vec::new(), } } @@ -55,6 +93,8 @@ pub(crate) fn annotate_cell( line, Some(TableLine { table: Arc::clone(table), + grid_columns: None, + record_row: None, fragments: vec![Fragment { output: source.range.clone(), row, @@ -92,9 +132,10 @@ pub(crate) fn append(output: &mut Option, source: &LogicalLineSource, let mut cell = fragment.source.clone(); cell.range = cell.range.start + start - fragment.output.start ..cell.range.start + end - fragment.output.start; + let start = offset + source.prefix_bytes + start - source.range.start; + let end = start + cell.range.len(); output.fragments.push(Fragment { - output: offset + source.prefix_bytes + start - source.range.start - ..offset + source.prefix_bytes + end - source.range.start, + output: start..end, row: fragment.row, column: fragment.column, source: cell, @@ -106,6 +147,7 @@ pub(super) fn render( lines: &[&SelectedLine], table: &TableLine, entire_selection: bool, + rectangle: Option<&RangeInclusive>, output: SelectionOutput, ) -> (String, CopyFormat) { let mut cells: BTreeMap<(usize, usize), Vec> = BTreeMap::new(); @@ -161,7 +203,7 @@ pub(super) fn render( .and_then(|copy| copy.table.as_ref()) .is_some_and(|table| table.fragments.is_empty()) }); - let standalone = cells.len() == 1 && !includes_separator; + let standalone = rectangle.is_none() && cells.len() == 1 && !includes_separator; if entire_selection && standalone && let Some(parts) = cells.values().next() @@ -183,6 +225,9 @@ pub(super) fn render( .into_iter() .map(|source| { let text = &source.text[source.range.clone()]; + if rectangle.is_some() && output == SelectionOutput::PlainText { + return text.replace('\\', "\\\\").replace('|', "\\|"); + } output.render(text, || { source.copy.as_ref().map_or_else( || super::escape(text), @@ -205,7 +250,7 @@ pub(super) fn render( CopyFormat::Markdown, ); } - if cells.is_empty() { + if cells.is_empty() && rectangle.is_none() { return ( lines .iter() @@ -224,6 +269,12 @@ pub(super) fn render( rows.entry(*row) .or_insert_with(|| vec![""; table.table.len()])[*column] = text; } + if let Some(rectangle) = rectangle { + for row in rectangle.clone() { + rows.entry(row) + .or_insert_with(|| vec![""; table.table.len()]); + } + } let mut out = String::new(); for (row, values) in rows { if !out.is_empty() { diff --git a/codex-rs/tui/src/markdown_render.rs b/codex-rs/tui/src/markdown_render.rs index d06cd5c05e..242f472e10 100644 --- a/codex-rs/tui/src/markdown_render.rs +++ b/codex-rs/tui/src/markdown_render.rs @@ -1601,6 +1601,25 @@ impl<'a, 'policy> Writer<'a, 'policy> { )); } } + // Include columns whose text ends before a neighbor wraps or whose value is empty. + let mut end = 0; + let edges: std::sync::Arc<[usize]> = column_widths + .iter() + .map(|width| { + end += width + 2 * TABLE_CELL_PADDING + TABLE_COLUMN_GAP; + end - TABLE_COLUMN_GAP / 2 + }) + .collect(); + for line in &mut out { + if let Some(table) = line + .source + .as_mut() + .and_then(|source| source.copy.as_mut()) + .and_then(|copy| std::sync::Arc::make_mut(copy).table.as_mut()) + { + table.grid_columns = Some(std::sync::Arc::clone(&edges)); + } + } RenderedTableLines { table_lines: out, table_lines_prewrapped: true, diff --git a/codex-rs/tui/src/markdown_render/table_key_value.rs b/codex-rs/tui/src/markdown_render/table_key_value.rs index 63bd72d843..303c7d44e0 100644 --- a/codex-rs/tui/src/markdown_render/table_key_value.rs +++ b/codex-rs/tui/src/markdown_render/table_key_value.rs @@ -122,6 +122,7 @@ pub(super) fn render_records( let mut out = Vec::new(); for (row_index, row) in rows.iter().enumerate() { + let start = out.len(); for (header, value) in headers.iter().zip(row) { if aligned_fields { render_aligned_field( @@ -136,6 +137,16 @@ pub(super) fn render_records( render_stacked_field(&mut out, header, value, available_width, label_style); } } + for line in &mut out[start..] { + if let Some(table) = line + .source + .as_mut() + .and_then(|source| source.copy.as_mut()) + .and_then(|copy| std::sync::Arc::make_mut(copy).table.as_mut()) + { + table.record_row = Some(row_index + 1); + } + } if row_index + 1 < rows.len() { let width = available_width.unwrap_or_else(|| widest_line_width(&out)); out.push(HyperlinkLine::new(Line::from(Span::styled( diff --git a/codex-rs/tui/src/transcript_view/input.rs b/codex-rs/tui/src/transcript_view/input.rs index 59183c42ac..5ebc730ce4 100644 --- a/codex-rs/tui/src/transcript_view/input.rs +++ b/codex-rs/tui/src/transcript_view/input.rs @@ -380,6 +380,8 @@ impl TranscriptView { return self.pointer_down(event, cells, mode); } MouseEventKind::Drag(MouseButton::Left) if dragging => { + // A drag ends the click sequence even when the next press is at the same spot. + self.last_click = None; self.extend_selection(event.column, event.row); } MouseEventKind::Up(MouseButton::Left) if dragging => { @@ -541,13 +543,18 @@ impl TranscriptView { } let clicks = crate::text_selection::click_count(&mut self.last_click, event.column, event.row); - if clicks >= 2 - && visible - .layout - .position_at(visible.row, event.column.saturating_sub(self.area.x)) - == visible.layout.position_at(visible.row, u16::MAX) - { - return None; + if clicks >= 2 { + let column = event.column.saturating_sub(self.area.x); + let layout = &visible.layout; + let offset = layout.position_at(visible.row, column); + let at_row_end = offset == layout.position_at(visible.row, u16::MAX); + let can_select_from_padding = at_row_end + && clicks == 3 + && !self.is_select_mode() + && layout.table_cell_at(visible.row, column, offset).is_some(); + if at_row_end && !can_select_from_padding { + return None; + } } let link = (mode == MouseMode::Interactive && clicks == 1 && event.modifiers.is_empty()) .then(|| self.link_at(event.column, event.row)) 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 a626a13f4c..69f754906a 100644 --- a/codex-rs/tui/src/transcript_view/markdown_copy_tests.rs +++ b/codex-rs/tui/src/transcript_view/markdown_copy_tests.rs @@ -78,8 +78,8 @@ fn markdown_layout(markdown: &str, width: u16) -> TextLayout { fn payload(layout: &TextLayout, range: std::ops::Range) -> (String, CopyFormat) { let mut lines = Vec::new(); - layout.copy_lines(range.clone(), "", &mut lines); - crate::markdown_copy::selection(&lines, &layout.text()[range]) + layout.copy_lines(range.clone(), "", &[], &mut lines); + crate::markdown_copy::selection(&lines, &layout.text()[range], /*rectangle_rows*/ None) } #[test] @@ -291,9 +291,10 @@ fn mixed_plain_output_remains_literal_in_html() { /*width*/ 40, ); let mut lines = Vec::new(); - layout.copy_lines(0..layout.text().len(), "", &mut lines); - output.copy_lines(0..output.text().len(), "\n", &mut lines); - let (copy, format) = crate::markdown_copy::selection(&lines, "unused"); + layout.copy_lines(0..layout.text().len(), "", &[], &mut lines); + output.copy_lines(0..output.text().len(), "\n", &[], &mut lines); + let (copy, format) = + crate::markdown_copy::selection(&lines, "unused", /*rectangle_rows*/ None); assert_eq!(format, CopyFormat::Markdown); assert_eq!( crate::clipboard_html::render_markdown(©), @@ -429,9 +430,10 @@ fn mixed_user_prose_preserves_literal_text_without_code_fences() { for layouts in [[&user, &answer, &tool], [&answer, &tool, &user]] { let mut lines = Vec::new(); for layout in layouts { - layout.copy_lines(0..layout.text().len(), "\n\n", &mut lines); + layout.copy_lines(0..layout.text().len(), "\n\n", &[], &mut lines); } - let (text, format) = crate::markdown_copy::selection(&lines, "unused"); + let (text, format) = + crate::markdown_copy::selection(&lines, "unused", /*rectangle_rows*/ None); assert_eq!(format, CopyFormat::Markdown); copies.push(crate::clipboard_html::render_markdown(&text)); } @@ -518,10 +520,10 @@ fn task_lists_and_transformed_tables_keep_their_meaning() { for source in ["- [x] done\n- [ ] next", "1. [x] done\n2. [ ] next"] { let layout = markdown_layout(source, /*width*/ 80); let mut lines = Vec::new(); - layout.copy_lines(0..layout.text().len(), "", &mut lines); + 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"), + crate::markdown_copy::literal_selection(&lines, "unused", /*rectangle_rows*/ None), source ); } @@ -719,18 +721,18 @@ fn cross_cell_selection_keeps_boundary_breaks() { let second = markdown_layout("**second**", /*width*/ 40); for (left, right, expected) in [(5..5, 0..6, "\n**second**"), (0..5, 0..0, "first\n")] { let mut lines = Vec::new(); - first.copy_lines(left, "", &mut lines); - second.copy_lines(right, "\n", &mut lines); + first.copy_lines(left, "", &[], &mut lines); + second.copy_lines(right, "\n", &[], &mut lines); assert_eq!( - crate::markdown_copy::selection(&lines, "unused").0, + crate::markdown_copy::selection(&lines, "unused", /*rectangle_rows*/ None).0, expected ); } let rule = markdown_layout("---", /*width*/ 40); let mut lines = Vec::new(); - first.copy_lines(0..first.text().len(), "", &mut lines); - rule.copy_lines(0..rule.text().len(), "\n", &mut lines); - let copied = crate::markdown_copy::selection(&lines, "unused").0; + first.copy_lines(0..first.text().len(), "", &[], &mut lines); + rule.copy_lines(0..rule.text().len(), "\n", &[], &mut lines); + let copied = crate::markdown_copy::selection(&lines, "unused", /*rectangle_rows*/ None).0; assert_eq!( crate::clipboard_html::render_markdown(&copied), "

first

\n
\n" diff --git a/codex-rs/tui/src/transcript_view/selection.rs b/codex-rs/tui/src/transcript_view/selection.rs index 9cd9793034..a83b67f6e1 100644 --- a/codex-rs/tui/src/transcript_view/selection.rs +++ b/codex-rs/tui/src/transcript_view/selection.rs @@ -3,8 +3,12 @@ use crossterm::event::KeyCode; use ratatui::layout::Position as ScreenPosition; +use std::ops::Range; +use std::ops::RangeInclusive; use unicode_segmentation::UnicodeSegmentation; +use super::text::TableCellHit; +use super::text::TableEndpoint; use super::*; use crate::clipboard_copy::CopyFormat; use crate::clipboard_copy::worker::CopyResult; @@ -22,6 +26,77 @@ struct PendingCopy { characters: usize, } +struct TableSelection { + anchor: TableCellHit, + // A head marks a whole-cell drag. Returning to its anchor selects the whole cell again. + head: Option, + ranges: Vec>, +} + +impl TableSelection { + fn rectangle_rows(&self) -> Option> { + let anchor = self.anchor.endpoint; + let head = self.head?; + let (first, last) = (anchor.display_row(), head.display_row()); + (head != anchor).then(|| first.min(last)..=first.max(last)) + } + + fn bounds(&self) -> Range { + self.ranges[0].start..self.ranges[self.ranges.len() - 1].end + } + + fn drag( + &mut self, + layout: &TextLayout, + row: usize, + column: u16, + pointer: Anchor, + origin: (Anchor, Anchor), + ) -> Option<(Anchor, Anchor)> { + if pointer.key != origin.0.key || !layout.is_table_row(row, pointer.offset, &self.anchor) { + return None; + } + if let Some(hit) = layout.table_cell_at(row, column, pointer.offset) + && self.anchor.same_table(&hit) + { + let hit = if hit.endpoint == self.anchor.endpoint { + &self.anchor + } else { + &hit + }; + let endpoint = hit.endpoint; + if self.head.unwrap_or(self.anchor.endpoint) != endpoint { + self.ranges = layout.table_selection_ranges(&self.anchor, hit); + self.head = Some(endpoint); + } + } + let at = |offset| Anchor { offset, ..origin.0 }; + let bounds = self.bounds(); + if let Some(head) = self.head { + let start = at(bounds.start); + let end = at(bounds.end); + return Some( + if (head.display_row(), head.cell.1) + < ( + self.anchor.endpoint.display_row(), + self.anchor.endpoint.cell.1, + ) + { + (end, start) + } else { + (start, end) + }, + ); + } + let range = layout.table_cell_pointer_range(&self.ranges, row, pointer.offset); + Some(if range.start < origin.0.offset { + (origin.1, at(range.start)) + } else { + (origin.0, at(range.end)) + }) + } +} + pub(super) struct Selection { pending_copy: Option, primary_owner: Option>, @@ -36,6 +111,7 @@ pub(super) struct Selection { pub(super) pointer: Option, pub(super) pressed_link: Option, origin: (Anchor, Anchor), + table_cell: Option, unit: SelectionUnit, preferred_column: Option, } @@ -56,12 +132,24 @@ impl Selection { pointer: None, pressed_link: None, origin: (cursor, cursor), + table_cell: None, unit: SelectionUnit::Character, preferred_column: None, } } + fn clear_table_cell_scope(&mut self) { + if self.table_cell.take().is_some() { + if self.unit == SelectionUnit::Character { + self.origin.1 = self.origin.0; + } + self.pending_copy = None; + self.primary_owner = None; + } + } + pub(super) fn set_keyboard_range(&mut self, start: Anchor, end: Anchor) { + self.clear_table_cell_scope(); if (self.start, self.end) != (start, end) { self.primary_owner = None; self.pending_copy = None; @@ -127,6 +215,7 @@ impl TranscriptView { pointer: None, pressed_link: None, origin: (start, end), + table_cell: None, unit: SelectionUnit::Character, preferred_column: None, }); @@ -141,12 +230,34 @@ impl TranscriptView { clicks: u8, ) { self.copy_mode = None; - let Some((anchor, layout)) = self.hit_test(column, row) else { + let Some((anchor, layout, layout_row)) = self.hit_test(column, row) else { return; }; self.cancel_beginning(); let unit = SelectionUnit::from_clicks(clicks); - let range = unit.range(layout.text(), anchor.offset); + let table_cell = if self.select_mode.is_none() + && matches!(clicks, 1 | 3) + && let Some(cell) = layout.table_cell_at( + layout_row, + column.saturating_sub(self.area.x), + anchor.offset, + ) { + let ranges = layout.table_selection_ranges(&cell, &cell); + Some(TableSelection { + head: (clicks == 3).then_some(cell.endpoint), + anchor: cell, + ranges, + }) + } else { + None + }; + let range = match &table_cell { + Some(table) if table.head.is_some() => table.bounds(), + Some(table) => { + layout.table_cell_pointer_range(&table.ranges, layout_row, anchor.offset) + } + None => unit.range(layout.text(), anchor.offset), + }; let snapshot = self.capture_snapshot(cells); self.held_reading = None; let start = Anchor { @@ -163,8 +274,9 @@ impl TranscriptView { primary_owner: None, snapshot, start, - end, + end: if clicks == 1 { start } else { end }, origin: (start, end), + table_cell, unit, preferred_column: None, dragging: true, @@ -229,37 +341,58 @@ impl TranscriptView { } pub(super) fn extend_selection(&mut self, column: u16, row: u16) { - let Some((end, layout)) = self.hit_test(column, row) else { + let Some((end, layout, layout_row)) = self.hit_test(column, row) else { return; }; let Some(mut selection) = self.selection.take() else { return; }; self.copy_mode = None; - // A Shift-click starts a new pointer gesture while retaining the text anchor. + // Shift-click extends the retained anchor across cells or entries. if !selection.dragging { + selection.clear_table_cell_scope(); selection.pointer_origin_row = row; selection.moved_vertically = false; } let cells = Arc::clone(&selection.snapshot.cells); - let range = selection.unit.range(layout.text(), end.offset); - let origin = selection.origin; - let backwards = (self.resolve(&cells, end), end.offset) - < (self.resolve(&cells, origin.0), origin.0.offset); let previous = (selection.start, selection.end); - selection.start = if backwards { origin.1 } else { origin.0 }; - selection.end = Anchor { - offset: if backwards { range.start } else { range.end }, - ..end - }; - selection.snapshot.pinned.entry(end.key).or_insert(layout); + let table_head = |selection: &Selection| selection.table_cell.as_ref()?.head; + let previous_head = table_head(&selection); + let table_range = selection.table_cell.as_mut().and_then(|table| { + table.drag( + &layout, + layout_row, + column.saturating_sub(self.area.x), + end, + selection.origin, + ) + }); + (selection.start, selection.end) = table_range.unwrap_or_else(|| { + if selection.table_cell.is_some() && selection.unit == SelectionUnit::Line { + return previous; + } + selection.clear_table_cell_scope(); + let origin = selection.origin; + let range = selection.unit.range(layout.text(), end.offset); + selection.snapshot.pinned.entry(end.key).or_insert(layout); + let backwards = (self.resolve(&cells, end), end.offset) + < (self.resolve(&cells, origin.0), origin.0.offset); + ( + if backwards { origin.1 } else { origin.0 }, + Anchor { + offset: if backwards { range.start } else { range.end }, + ..end + }, + ) + }); selection.moved = true; selection.moved_vertically |= selection.pointer_origin_row != row; selection.pointer = Some(ScreenPosition::new(column, row)); selection.preferred_column = None; self.pin_selection_range(&cells, &mut selection); - if previous != (selection.start, selection.end) { + if previous != (selection.start, selection.end) || previous_head != table_head(&selection) { selection.primary_owner = None; + selection.pending_copy = None; } self.selection = Some(selection); } @@ -269,6 +402,11 @@ impl TranscriptView { self.selection.as_ref().is_some_and(|selection| { selection.start.key != selection.end.key || selection.start.offset != selection.end.offset + || selection + .table_cell + .as_ref() + .and_then(TableSelection::rectangle_rows) + .is_some() }) } @@ -289,9 +427,6 @@ impl TranscriptView { if (start.index, start.offset) > (end.index, end.offset) { std::mem::swap(&mut start, &mut end); } - if start == end { - return None; - } let mut ranges = Vec::new(); for index in start.index..=end.index { let layout = self.layout(cells, index)?; @@ -313,7 +448,17 @@ impl TranscriptView { Some(ranges) } + fn table_selection(&self) -> Option<&TableSelection> { + self.selection.as_ref()?.table_cell.as_ref() + } + pub(crate) fn selected_text(&mut self, cells: &[Arc]) -> Option { + if let Some(table) = self.table_selection() { + let rectangle_rows = table.rectangle_rows(); + let lines = self.selected_copy_lines(cells); + let text = crate::markdown_copy::literal_selection(&lines, "", rectangle_rows.as_ref()); + return (!text.is_empty()).then_some(text); + } let mut text = String::new(); let mut previous: Option> = None; for (layout, range) in self.selected_ranges(cells)? { @@ -349,6 +494,26 @@ impl TranscriptView { } } + fn selected_copy_lines( + &mut self, + cells: &[Arc], + ) -> Vec { + let ranges = self.selected_ranges(cells).unwrap_or_default(); + let cell_ranges = self + .table_selection() + .map_or(&[][..], |table| &table.ranges); + let mut lines = Vec::new(); + let mut previous: Option> = None; + for (layout, range) in ranges { + let separator = previous + .as_ref() + .map_or("", |previous| previous.separator_after(&layout)); + layout.copy_lines(range, separator, cell_ranges, &mut lines); + previous = Some(layout); + } + lines + } + /// Deselect only after confirmed delivery when the current copy policy requests it. /// Failures and unacknowledged terminal writes retain the selection. pub(crate) fn copy_selected_text_with( @@ -361,15 +526,10 @@ impl TranscriptView { crate::clipboard_copy::CopyFormat, ) -> Result, ) -> Result { - let mut lines = Vec::new(); - let mut previous: Option> = None; - for (layout, range) in self.selected_ranges(cells).unwrap_or_default() { - let separator = previous - .as_ref() - .map_or("", |previous| previous.separator_after(&layout)); - layout.copy_lines(range, separator, &mut lines); - previous = Some(layout); - } + 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)| { @@ -385,10 +545,11 @@ impl TranscriptView { } }); let (text, format) = override_payload.unwrap_or_else(|| { - let (serialized, format) = crate::markdown_copy::selection(&lines, text); + let (serialized, format) = + crate::markdown_copy::selection(&lines, text, rectangle_rows.as_ref()); if format == CopyFormat::Markdown { ( - crate::markdown_copy::literal_selection(&lines, text), + crate::markdown_copy::literal_selection(&lines, text, rectangle_rows.as_ref()), CopyFormat::MarkdownSelection(serialized.into()), ) } else { @@ -591,6 +752,7 @@ impl TranscriptView { return true; }; if let Some(mut selection) = self.selection.take() { + selection.clear_table_cell_scope(); if selection.end != next { selection.primary_owner = None; } @@ -698,6 +860,17 @@ impl TranscriptView { } continue; } + if let Some(table) = &selection.table_cell { + if let Some(fragment) = visible.layout.table_cell_on_row(&table.ranges, visible.row) + { + let start = fragment.start.max(begin); + let end = fragment.end.min(finish); + if start < end { + visible.layout.highlight(start..end, area, buf, visible.row); + } + } + continue; + } let next = (visible.index + 1..=end.index) .filter_map(|index| { selection @@ -716,7 +889,7 @@ impl TranscriptView { } } - pub(super) fn hit_test(&self, column: u16, row: u16) -> Option<(Anchor, Arc)> { + fn hit_test(&self, column: u16, row: u16) -> Option<(Anchor, Arc, usize)> { let row = row.saturating_sub(self.area.y) as usize; let visible = self .visible @@ -731,6 +904,7 @@ impl TranscriptView { row_bias: 0, }, Arc::clone(&visible.layout), + visible.row, )) } diff --git a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__tables__mouse_drag_selects_only_the_wrapped_table_cell.snap b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__tables__mouse_drag_selects_only_the_wrapped_table_cell.snap new file mode 100644 index 0000000000..fc27ac98df --- /dev/null +++ b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__tables__mouse_drag_selects_only_the_wrapped_table_cell.snap @@ -0,0 +1,10 @@ +--- +source: tui/src/transcript_view/table_copy_tests.rs +expression: highlight +--- + First change Adds cell selection for a viewer +332 + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + who reads the room history with + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 界 characters. + ^^^^^^^^^^^^^^ diff --git a/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__tables__mouse_selects_wrapped_cell_text_and_rectangles.snap b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__tables__mouse_selects_wrapped_cell_text_and_rectangles.snap new file mode 100644 index 0000000000..a8c49f8901 --- /dev/null +++ b/codex-rs/tui/src/transcript_view/snapshots/codex_tui__transcript_view__markdown_copy_tests__tables__mouse_selects_wrapped_cell_text_and_rectangles.snap @@ -0,0 +1,22 @@ +--- +source: tui/src/transcript_view/table_copy_tests.rs +expression: rectangle_highlight +--- + First change Adds cell selection for a viewer +332 + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + who reads the room history with + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 界 characters. + ^^^^^^^^^^^^^^ + ────────────── ────────────────────────────────── ────── + + Pending + + ────────────── ────────────────────────────────── ────── + + Awaiting TBD + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ────────────── ────────────────────────────────── ────── + + Next change Connects the reader. +434 + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 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 2a42e567b5..4d1c9541a5 100644 --- a/codex-rs/tui/src/transcript_view/table_copy_tests.rs +++ b/codex-rs/tui/src/transcript_view/table_copy_tests.rs @@ -1,10 +1,119 @@ //! Selection regressions through the real Markdown renderer, layout, and clipboard serializer. use super::*; +use crate::transcript_view::tests::render; use pretty_assertions::assert_eq; const TABLE: &str = "| Task | Status | Next step |\n|---|---|---|\n| Task 1 | Complete | Review results |\n| Task 2 | In progress | Finish implementation |\n| Task 3 | Planned | Confirm requirements |"; +fn symbol_position(buffer: &Buffer, symbol: &str) -> (u16, u16) { + let index = buffer + .content() + .iter() + .position(|cell| cell.symbol() == symbol) + .unwrap(); + buffer.pos_of(index) +} + +fn table_cells(markdown: impl Into) -> [Arc; 1] { + [Arc::new(AgentMarkdownCell::new( + markdown.into(), + Path::new("/"), + ))] +} + +#[test] +fn diagonal_cell_drag_in_stacked_records_copies_both_complete_rows() { + let first_two = "| Left | Right |\n|---|---|\n| alpha | Beta |\n| Gamma | delta |"; + let source = format!("{first_two}\n| omega | last |"); + let expected = "| | |\n|---|---|\n| alpha | Beta |\n| Gamma | delta |"; + let cells = table_cells(&source); + let mut view = TranscriptView::default(); + let buffer = render(&mut view, &cells, /*width*/ 10, /*height*/ 24); + let (right, left) = (symbol_position(&buffer, "B"), symbol_position(&buffer, "G")); + for ((x, y), (to_x, to_y)) in [(right, left), (left, right)] { + view.begin_selection(&cells, x, y, /*clicks*/ 3); + view.extend_selection(to_x, to_y); + assert_eq!(view.selected_text(&cells).as_deref(), Some(expected)); + } + + let first = symbol_position(&buffer, "R"); + let last_label = buffer + .content() + .iter() + .rposition(|cell| cell.symbol() == "R"); + let third = buffer.pos_of(last_label.unwrap()); + assert_ne!(first, third); + view.begin_selection(&cells, left.0, left.1, /*clicks*/ 3); + for ((x, y), expected) in [ + (first, first_two), + ( + third, + "| Left | Right |\n|---|---|\n| Gamma | delta |\n| omega | last |", + ), + ] { + view.extend_selection(x, y); + assert_eq!(view.selected_text(&cells).as_deref(), Some(expected)); + } + let (x, y) = symbol_position(&buffer, "a"); + view.begin_selection(&cells, x, y, /*clicks*/ 1); + view.extend_selection(third.0, third.1); + assert_eq!(view.selected_text(&cells).as_deref(), Some(source.as_str())); +} + +#[test] +fn table_drag_falls_back_to_text_and_keeps_the_release_endpoint() { + let cells = + table_cells("| A | B |\n|---|---|\n| alpha | Beta |\n| Gamma | delta |\n\nParagraph."); + let mut view = TranscriptView::default(); + let buffer = render(&mut view, &cells, /*width*/ 40, /*height*/ 14); + let (x, y) = symbol_position(&buffer, "d"); + let (period, last) = symbol_position(&buffer, "."); + view.begin_selection(&cells, x, y, /*clicks*/ 1); + view.extend_selection(period + 1, last); + let text = view.selected_text(&cells).unwrap(); + assert!( + text.starts_with("delta") && text.ends_with("Paragraph."), + "{text:?}" + ); + + let (left, top) = symbol_position(&buffer, "a"); + view.begin_selection(&cells, x, y, /*clicks*/ 1); + view.extend_selection(left, top); + view.end_drag(); + assert!(view.selection_key(&cells, crossterm::event::KeyCode::Right)); + let text = view.selected_text(&cells).unwrap(); + assert!(text.starts_with("lpha")); + assert!(text.ends_with("delta")); +} + +#[test] +fn rectangular_clipboard_text_escapes_literal_pipes() { + let cells = table_cells("| A | B |\n|---|---|\n| a\\|b | Value |"); + let mut view = TranscriptView::default(); + let buffer = render(&mut view, &cells, /*width*/ 40, /*height*/ 10); + let (x, y) = symbol_position(&buffer, "a"); + let (right, row) = symbol_position(&buffer, "V"); + view.begin_selection(&cells, x, y, /*clicks*/ 1); + view.extend_selection(right, row); + let text = view.selected_text(&cells).unwrap(); + let expected = "| | |\n|---|---|\n| a\\|b | Value |"; + assert_eq!(text, expected); + view.copy_selected_text_with( + &cells, + &text, + /*clear_selection*/ false, + |plain, format| { + assert_eq!( + (plain, format), + (expected, CopyFormat::MarkdownSelection(expected.into())) + ); + Ok(crate::clipboard_copy::CopyStatus::Confirmed) + }, + ) + .unwrap(); +} + #[test] fn table_copy_preserves_structure_across_grid_and_record_layouts() { let table = TABLE.replace("Finish implementation", "Finish my_long_file_name!.txt"); @@ -15,14 +124,14 @@ fn table_copy_preserves_structure_across_grid_and_record_layouts() { 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); + layout.copy_lines(0..layout.text().len(), "", &[], &mut lines); assert_eq!( payload(&layout, 0..layout.text().len()), (markdown.clone(), CopyFormat::Markdown), "width {width}" ); assert_eq!( - crate::markdown_copy::literal_selection(&lines, "unused"), + crate::markdown_copy::literal_selection(&lines, "unused", /*rectangle_rows*/ None), source ); let rewrapped = layout.rewrap(/*width*/ 17); @@ -114,6 +223,16 @@ fn table_cells_keep_inline_formatting_alignment_and_literal_pipes() { } } +#[test] +fn triple_click_below_a_short_grid_header_selects_its_text() { + let source = "| ID | A longer heading that wraps across many display lines |\n|---|---|"; + let cells = table_cells(source); + let mut view = TranscriptView::default(); + render(&mut view, &cells, /*width*/ 30, /*height*/ 8); + view.begin_selection(&cells, /*column*/ 3, /*row*/ 2, /*clicks*/ 3); + assert_eq!(view.selected_text(&cells).as_deref(), Some("ID")); +} + #[test] fn header_only_and_empty_cells_keep_their_table_positions() { for source in [ @@ -215,3 +334,158 @@ fn empty_selected_rows_keep_copy_spacing_without_newline_highlights() { .unwrap(); insta::assert_snapshot!(highlighted.join("\n")); } + +#[test] +fn mouse_selects_wrapped_cell_text_and_rectangles() { + use crate::transcript_view::tests::text; + use crossterm::event::KeyModifiers; + use crossterm::event::MouseButton::Left; + use crossterm::event::MouseEvent; + use crossterm::event::MouseEventKind; + + let rich = + "Adds **cell selection** for a viewer who reads the room history with 界 characters."; + let full = rich.replace("**", ""); + let table_header = "| | | |\n|---|---|---:|"; + let markdown = format!( + "| PR | What it adds | Size |\n|---|---|---:|\n| First change | {rich} | +332 |\n| Pending | | |\n| Awaiting | | TBD |\n| Next change | Connects the reader. | +434 |" + ); + let cells = table_cells(markdown); + let mut view = TranscriptView { + copy_on_select: true, + ..Default::default() + }; + let buffer = render(&mut view, &cells, /*width*/ 60, /*height*/ 12); + let position = |symbol| symbol_position(&buffer, symbol); + let start @ (first, first_row) = position("A"); + let end @ (period, last_row) = position("."); + let highlighted_rows = |view: &mut TranscriptView, last: u16| { + let buffer = render(view, &cells, /*width*/ 60, /*height*/ 12); + let display = text(&buffer); + let mut rows = Vec::new(); + for (row, line) in (first_row..=last).zip(display.lines().skip(first_row.into())) { + let mut mask = String::new(); + for x in 0..buffer.area.width { + let selected = buffer[(x, row)].modifier.contains(Modifier::REVERSED); + mask.push(if selected { '^' } else { ' ' }); + } + rows.push(format!("{line}\n{}", mask.trim_end())); + } + rows.join("\n") + }; + let mouse = |view: &mut TranscriptView, kind, (column, row)| { + view.handle_mouse( + MouseEvent { + kind, + column, + row, + modifiers: KeyModifiers::NONE, + }, + &cells, + ) + }; + let two_cells = format!("{table_header}\n| | {full} | +332 |"); + let suffix = full.strip_prefix("Adds ").unwrap(); + let partial = ((first + 5, first_row), end, suffix); + for (from, to, expected) in [ + (position("+"), end, two_cells.as_str()), + partial, + partial, // Repeating a drag from the same spot starts a fresh selection. + ((first - 2, first_row), end, full.as_str()), + (end, start, full.as_str()), + ((period + 5, last_row), start, full.as_str()), + ] { + mouse(&mut view, MouseEventKind::Down(Left), from); + mouse(&mut view, MouseEventKind::Drag(Left), to); + let Some(ViewAction::CopyOnSelect(copied)) = mouse(&mut view, MouseEventKind::Up(Left), to) + else { + panic!("expected a copy on release for {from:?} → {to:?}"); + }; + assert_eq!(copied, expected, "{from:?} → {to:?}"); + } + let highlight = highlighted_rows(&mut view, last_row); + insta::assert_snapshot!("mouse_drag_selects_only_the_wrapped_table_cell", highlight); + + // The short size cell owns its column beside the wrapped description. + view.begin_selection(&cells, position("+").0, last_row, /*clicks*/ 3); + assert_eq!(view.selected_text(&cells).as_deref(), Some("+332")); + + // The third press selects the cell immediately. Hold it to grow or shrink the rectangle. + let down = MouseEventKind::Down(Left); + let up = MouseEventKind::Up(Left); + for kind in [down, up, down, up, down] { + mouse(&mut view, kind, (period + 1, last_row)); + } + assert_eq!(view.selected_text(&cells).as_deref(), Some(full.as_str())); + assert_eq!(highlighted_rows(&mut view, last_row), highlight); + let size_column = position("+").0; + let final_row = position("4").1; + let pending_row = text(&buffer) + .lines() + .position(|line| line.contains("Pending")) + .unwrap() as u16; + let pending_description = format!("{table_header}\n| | {full} | |\n| | | |"); + let pending_size = format!("{two_cells}\n| | | |"); + let rectangle = + format!("{two_cells}\n| | | |\n| | | TBD |\n| | Connects the reader. | +434 |"); + let with_empty_endpoint = format!("{table_header}\n| | {full} | |\n| | | |\n| | | |"); + let description_column = format!("{with_empty_endpoint}\n| | Connects the reader. | |"); + let blank = (first, position("T").1); + for (to, expected) in [ + ((size_column, last_row), two_cells.as_str()), // Blank space below +332. + ((first, pending_row), pending_description.as_str()), + ((size_column, pending_row), pending_size.as_str()), + ((size_column, final_row), rectangle.as_str()), + ((first, final_row), description_column.as_str()), + (blank, with_empty_endpoint.as_str()), + (end, full.as_str()), + ] { + mouse(&mut view, MouseEventKind::Drag(Left), to); + assert_eq!(view.selected_text(&cells).as_deref(), Some(expected)); + if expected == rectangle { + let rectangle_highlight = highlighted_rows(&mut view, final_row); + insta::assert_snapshot!(rectangle_highlight); + } + } + mouse(&mut view, up, end); + + render(&mut view, &cells, /*width*/ 32, /*height*/ 12); + assert_eq!(view.selected_text(&cells).as_deref(), Some(full.as_str())); + view.copy_selected_text_with( + &cells, + &full, + /*clear_selection*/ false, + |text, format| { + assert_eq!( + (text, format), + (full.as_str(), CopyFormat::MarkdownSelection(rich.into())) + ); + Ok(crate::clipboard_copy::CopyStatus::Confirmed) + }, + ) + .unwrap(); + + render(&mut view, &cells, /*width*/ 60, /*height*/ 12); + view.begin_selection(&cells, first, final_row, /*clicks*/ 3); + view.extend_selection(blank.0, blank.1); + assert_eq!( + view.selected_text(&cells), + Some(format!( + "{table_header}\n| | | |\n| | Connects the reader. | |" + )) + ); + + view.begin_selection(&cells, first, pending_row, /*clicks*/ 3); + view.extend_selection(size_column, pending_row); + assert_eq!( + view.selected_text(&cells), + Some(format!("{table_header}\n| | | |")) + ); + + view.begin_selection(&cells, first, first_row, /*clicks*/ 1); + view.extend_selection(first, pending_row); + assert_eq!( + view.selected_text(&cells).as_deref(), + Some(pending_description.as_str()) + ); +} diff --git a/codex-rs/tui/src/transcript_view/text.rs b/codex-rs/tui/src/transcript_view/text.rs index 93c50c8b6b..a557efad45 100644 --- a/codex-rs/tui/src/transcript_view/text.rs +++ b/codex-rs/tui/src/transcript_view/text.rs @@ -8,6 +8,7 @@ use std::borrow::Cow; use std::ops::Range; +use std::sync::Arc; #[path = "text_logical.rs"] mod logical; @@ -76,6 +77,30 @@ struct TextRow { tabs: tabs::TabStops, } +pub(super) struct TableCellHit { + table: Arc<[&'static str]>, + pub(super) endpoint: TableEndpoint, + line: Range, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) struct TableEndpoint { + pub(super) cell: (usize, usize), + pub(super) record_row: Option, +} + +impl TableEndpoint { + pub(super) fn display_row(self) -> usize { + self.record_row.unwrap_or(self.cell.0) + } +} + +impl TableCellHit { + pub(super) fn same_table(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.table, &other.table) + } +} + impl TextLayout { pub(super) fn copy_block_ranges(&self) -> Vec<(Range, &'static str, Option)> { let mut ranges = Vec::new(); @@ -326,26 +351,166 @@ impl TextLayout { } } + fn logical_sources(&self) -> impl Iterator { + self.logical.iter().scan(0, |offset, line| { + let start = *offset; + *offset += line.origin.range.len() + 1; + Some((start, &line.origin)) + }) + } + + pub(super) fn table_cell_at( + &self, + row: usize, + column: u16, + offset: usize, + ) -> Option { + let display_row = self.rows.get(row)?; + if usize::from(column) < display_row.first_column { + return None; + } + let (position, origin) = self + .logical_sources() + .find(|(start, source)| (*start..=*start + source.range.len()).contains(&offset))?; + let table = origin.copy.as_ref()?.table.as_ref()?; + // The grid omits trailing blanks on short continuations. Recover the pointer's + // distance into that padding without introducing spaces into the logical text. + let trailing = if offset != display_row.source.end { + 0 + } else if display_row.line_end == Some(offset) { + column.saturating_sub(self.column_for_offset_on_row(row, offset)) + } else { + return None; + }; + let byte = origin.range.start + offset - position; + let column = display_width(&origin.text[..byte]) + usize::from(trailing); + let cell = table.cell_at(byte + usize::from(trailing), column)?; + Some(TableCellHit { + table: Arc::clone(&table.table), + endpoint: TableEndpoint { + cell, + record_row: table.record_row, + }, + line: position..position + origin.range.len(), + }) + } + + pub(super) fn is_table_row(&self, row: usize, offset: usize, hit: &TableCellHit) -> bool { + self.rows + .get(row) + .is_some_and(|row| row.source.start <= offset && offset <= row.source.end) + && self.logical_sources().any(|(start, source)| { + (start..=start + source.range.len()).contains(&offset) + && source + .copy + .as_ref() + .and_then(|copy| copy.table.as_ref()) + .is_some_and(|table| Arc::ptr_eq(&table.table, &hit.table)) + }) + } + + /// One span per logical line. Repeated labels contribute only from selected records. + pub(super) fn table_selection_ranges( + &self, + anchor: &TableCellHit, + head: &TableCellHit, + ) -> Vec> { + let (row, col) = anchor.endpoint.cell; + let (head_row, head_col) = head.endpoint.cell; + let first = anchor + .endpoint + .display_row() + .min(head.endpoint.display_row()); + let last = anchor + .endpoint + .display_row() + .max(head.endpoint.display_row()); + let records = first..=last; + let rows = if anchor.endpoint == head.endpoint && row == 0 { + 0..=0 + } else if row == 0 || head_row == 0 { + 0..=last + } else { + records.clone() + }; + let columns = col.min(head_col)..=col.max(head_col); + let mut ranges = Vec::new(); + for (start, source) in self.logical_sources() { + let fragment = source + .copy + .as_ref() + .and_then(|copy| copy.table.as_ref()) + .filter(|line| Arc::ptr_eq(&line.table, &anchor.table)) + .filter(|line| { + line.record_row + .is_none_or(|record| records.contains(&record)) + }) + .and_then(|line| line.cell_range(&rows, &columns)) + .map(|range| range.start.max(source.range.start)..range.end.min(source.range.end)); + if let Some(fragment) = fragment.filter(|range| range.start <= range.end) { + ranges.push( + start + fragment.start - source.range.start + ..start + fragment.end - source.range.start, + ); + } + } + if ranges.is_empty() { + // A rectangle can consist entirely of cells omitted after the last visible value. + ranges.push(anchor.line.end..anchor.line.end); + } + ranges + } + + pub(super) fn table_cell_on_row( + &self, + ranges: &[Range], + row: usize, + ) -> Option> { + table_cell_intersection(ranges, &self.rows.get(row)?.source) + } + + /// A drag includes the glyph under the pointer. Padding snaps to the nearest text edge. + pub(super) fn table_cell_pointer_range( + &self, + ranges: &[Range], + row: usize, + offset: usize, + ) -> Range { + let limits = self + .table_cell_on_row(ranges, row) + .unwrap_or_else(|| ranges[0].start..ranges[ranges.len() - 1].end); + offset.clamp(limits.start, limits.end) + ..self + .after_cursor_grapheme(row, offset) + .clamp(limits.start, limits.end) + } + + /// A nonempty set of cell ranges limits copying to those spans. pub(super) fn copy_lines( &self, range: Range, separator: &str, + cell_ranges: &[Range], output: &mut Vec, ) { - let mut offset = 0; - for (index, line) in self.logical.iter().enumerate() { - let end = offset + line.origin.range.len(); + for (offset, source) in self.logical_sources() { + let end = offset + source.range.len(); if range.start <= end && range.end >= offset { - let selected = line.origin.range.start + range.start.saturating_sub(offset) - ..line.origin.range.start + range.end.min(end) - offset; + let mut selected = range.start.max(offset)..range.end.min(end); + if !cell_ranges.is_empty() { + selected = match table_cell_intersection(cell_ranges, &selected) { + Some(fragment) => fragment, + None => continue, + }; + } crate::markdown_copy::SelectedLine::append( output, - line.origin.clone(), - selected, - if index == 0 { separator } else { "\n" }, + source.clone(), + source.range.start + selected.start - offset + ..source.range.start + selected.end - offset, + if offset == 0 { separator } else { "\n" }, ); } - offset = end + 1; } } @@ -628,6 +793,14 @@ impl TextLayout { } } +fn table_cell_intersection(ranges: &[Range], within: &Range) -> Option> { + let fragment = ranges.get(ranges.partition_point(|range| range.end < within.start))?; + let start = within.start.max(fragment.start); + let end = within.end.min(fragment.end); + // An empty cell still contributes a row when copying a rectangle. + (start < end || start == end && fragment.is_empty()).then_some(start..end) +} + fn layout_line(logical: &LogicalLine, text_start: usize, width: u16) -> Vec { let content_width = width.saturating_sub(logical.right_reserve).max(/*other*/ 1); let mut logical = Cow::Borrowed(logical);