Open and highlight file line ranges in the TUI (#64211)

## Why

A single-line jump doesn't show where a referenced block of code ends.

## What changed

Recognize file ranges such as `src/search.ts:42-44` and
`src/search.ts#L42-L44` in Markdown links and bare prose. Opening a range
in the sidebar jumps to its start and highlights every line through its
end, including wrapped rows and blank lines. If the link specifies a
starting column, mark it too. Pressing `Esc` can clear the highlight,
and it stays cleared across reloads.

Keep each wrapped link as one keyboard navigation stop, even when
fragments from different links share a table row. Preserve hidden range
destinations when copying Markdown.

## Testing

Add coverage for malformed and out-of-bounds ranges, mouse and keyboard
navigation across wrapped links, Markdown copying, and highlight rendering
across terminal palettes.

GitOrigin-RevId: 1171533053e92a61de01f90f248c58b059b3ae32
This commit is contained in:
Felipe Coury
2026-11-26 20:24:42 +00:00
committed by copyberry
parent 475e13ab1a
commit c13a107f0e
20 changed files with 667 additions and 131 deletions
+28 -16
View File
@@ -25,6 +25,7 @@ use crate::terminal_hyperlinks::HyperlinkLine;
use crate::terminal_hyperlinks::ReaderLink;
use crate::terminal_hyperlinks::visible_lines;
use crate::transcript_view::DocumentPosition;
use crate::transcript_view::DocumentTarget;
use crate::transcript_view::TranscriptView;
use crate::transcript_view::ViewAction;
use codex_app_server_client::AppServerPath;
@@ -138,6 +139,7 @@ pub(super) struct Document {
pub(super) backend: crate::backend_id::BackendId,
link: Option<usize>,
location: Option<SourceLocation>,
highlight_dismissed: bool,
state: State,
pub(super) path_actions: PathActions,
access: DocumentAccess,
@@ -155,7 +157,7 @@ enum State {
view: Box<TranscriptView>,
cells: [Arc<dyn HistoryCell>; 1],
line_starts: Vec<usize>,
target: Option<(usize, usize)>,
target: Option<DocumentTarget>,
},
}
@@ -336,6 +338,7 @@ impl Document {
});
let target = self
.location
.filter(|_| !self.highlight_dismissed)
.and_then(|loc| source_target(&source, &line_starts, loc));
let cells: [Arc<dyn HistoryCell>; 1] = [Arc::new(FileCell { source, language })];
let mut view = Box::<TranscriptView>::default();
@@ -344,7 +347,7 @@ impl Document {
match position {
Some(DocumentPosition::Latest) => view.jump_to_latest(),
Some(DocumentPosition::Offset(offset)) => view.jump_to_offset(&cells, offset),
None => view.jump_to_offset(&cells, target.map_or(0, |(_, offset)| offset)),
None => view.jump_to_offset(&cells, target.map_or(0, |target| target.offset)),
}
State::Ready {
view,
@@ -358,11 +361,11 @@ impl Document {
}
fn go_to(&mut self, location: Option<SourceLocation>) {
let was_located = self.location.is_some();
let restore_markdown = location.is_none()
&& was_located
&& self.location.is_some()
&& crate::markdown_render::is_markdown_file(&self.title());
self.location = location;
self.highlight_dismissed = false;
self.link = None;
self.path_actions.dismiss();
let State::Ready {
@@ -384,10 +387,11 @@ impl Document {
self.loaded(Ok(DocumentContent::Text(source)));
} else {
*target = location.and_then(|location| source_target(source, line_starts, location));
if let Some((_, offset)) = target {
view.cancel_search();
if let Some(target) = target {
view.end_select_mode();
view.end_selection(cells);
view.jump_to_offset(cells, *offset);
view.cancel_search();
view.jump_to_offset(cells, target.offset);
}
}
}
@@ -491,7 +495,7 @@ impl Document {
let path =
crate::history_cell::sanitize_user_text(path.into()).replace(['\n', '\t'], " ");
let title = match self.location {
Some(location) => format!("Open {path} at line {}?", location.line),
Some(location) => format!("Open {path} at line {}?", location.start.line),
None => format!("Open {path}?"),
};
let mut lines = textwrap::wrap(&title, usize::from(body.width).max(1))
@@ -641,13 +645,13 @@ fn source_target(
source: &str,
starts: &[usize],
location: SourceLocation,
) -> Option<(usize, usize)> {
let index = (location.line - 1).min(starts.len().saturating_sub(1));
) -> Option<DocumentTarget> {
let index = (location.start.line - 1).min(starts.len().saturating_sub(1));
let start = *starts.get(index)?;
let line = source.lines().nth(index)?;
let column = line
.char_indices()
.nth(location.column - 1)
.nth(location.start.column.unwrap_or(1) - 1)
.map_or(line.len(), |(byte, _)| byte);
let column = if column == line.len() {
column
@@ -657,7 +661,14 @@ fn source_target(
.last()
.map_or(0, |(byte, _)| byte)
};
Some((index + 1, start + column))
Some(DocumentTarget {
first_line: index + 1,
last_line: location
.end
.map_or(index + 1, |end| end.line.min(starts.len())),
offset: start + column,
mark_column: location.end.is_none() || location.start.column.is_some(),
})
}
impl App {
@@ -905,6 +916,7 @@ impl App {
backend: backend_id,
link: None,
location,
highlight_dismissed: false,
state,
access,
path_actions: PathActions::default(),
@@ -999,10 +1011,10 @@ impl App {
view.cancel_search();
view.end_selection(cells);
None
} else if escape
&& (doc.link.take().is_some()
|| (!view.has_active_interaction() && target.take().is_some()))
{
} else if escape && doc.link.take().is_some() {
None
} else if escape && !view.has_active_interaction() && target.take().is_some() {
doc.highlight_dismissed = true;
None
} else if !view.is_search_editing()
&& (self.keymap.app.find_transcript.is_pressed(*key)
+109 -1
View File
@@ -501,7 +501,7 @@ async fn document_preview_scenario() -> Result<()> {
dir.path().join("main.rs"),
"// first\r\n// second\r\nlet value = 3;\r\n",
)?;
for location in [None, Some(SourceLocation { line: 3, column: 5 })] {
for location in [None, Some(SourceLocation::single(/*line*/ 3, Some(5)))] {
app.open_document(
&mut tui,
&mut server,
@@ -569,6 +569,25 @@ async fn document_preview_scenario() -> Result<()> {
.reader()
.unwrap();
assert!(view.begin_select_mode(cells));
let range = crate::markdown_render::sidebar_file_link("./main.rs#L1-L2").unwrap();
app.open_document(&mut tui, &mut server, parent, range)
.await?;
Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?;
assert_eq!(app.sidebar().unwrap().documents.len(), 2);
let doc = app.sidebar_mut().documents.get_mut(&id).unwrap();
assert!(!doc.reader().unwrap().0.has_active_interaction());
let lines = |doc: &Document| match &doc.state {
State::Ready {
target: Some(target),
..
} => target.first_line..=target.last_line,
_ => panic!("expected highlighted source"),
};
assert_eq!(lines(doc), 1..=2);
doc.loaded(Ok(DocumentContent::Text("shorter".into())));
assert_eq!(lines(doc), 1..=1);
let (view, cells) = doc.reader().unwrap();
assert!(view.begin_select_mode(cells));
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into())))
.await?;
let State::Ready { view, target, .. } = &app.sidebar().unwrap().documents[&id].state else {
@@ -581,6 +600,13 @@ async fn document_preview_scenario() -> Result<()> {
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into())))
.await?;
assert_eq!(app.sidebar().unwrap().documents.len(), remaining);
if remaining == 2 {
let doc = app.sidebar_mut().documents.get_mut(&id).unwrap();
doc.loaded(Ok(DocumentContent::Text(String::new())));
doc.loaded(Err(eyre!("temporary read failure")));
doc.loaded(Ok(DocumentContent::Text("changed again\nsecond".into())));
assert!(matches!(&doc.state, State::Ready { target: None, .. }));
}
}
app.chat_widget
.set_pet_image_support_for_tests(crate::pets::PetImageSupport::Unsupported(
@@ -909,3 +935,85 @@ fn preview_error_keeps_the_filename_visible_in_a_narrow_pane() -> Result<()> {
assert!(message("fs/readFile", "Storage offline").ends_with("Storage offline"));
Ok(())
}
#[test]
fn file_ranges_clamp_to_source_and_keep_grapheme_offsets() {
let source = "abc\r\ne\u{301}x\r\nlast";
for (dest, expected) in [
("f.rs:2:2-99:8", (2..=3, 4, true)),
("f.rs#L99-L101", (3..=3, 9, false)),
] {
let location = crate::markdown_render::sidebar_file_link(dest)
.unwrap()
.location
.unwrap();
let target = source_target(source, &[0, 4, 9], location).unwrap();
let lines = target.first_line..=target.last_line;
assert_eq!((lines, target.offset, target.mark_column), expected);
assert_eq!(source_target("", &[], location), None);
}
}
fn range_buffers(width: u16, bg: Option<(u8, u8, u8)>) -> [ratatui::buffer::Buffer; 2] {
use crate::terminal_palette::DefaultColors;
let cells: [Arc<dyn HistoryCell>; 1] = [Arc::new(FileCell {
source: "before\nlet answer = 42;\n\nlast\nafter".into(),
language: Some("rs".into()),
})];
let target = DocumentTarget {
first_line: 2,
last_line: 4,
offset: 7,
mark_column: false,
};
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, /*height*/ 8);
let starts = [0, 7, 24, 25, 30];
let colors = bg.map(|bg| DefaultColors { fg: None, bg });
crate::terminal_palette::with_test_palette(colors, || {
[None, Some(target)].map(|location| {
let mut buf = ratatui::buffer::Buffer::empty(area);
TranscriptView::default().render_document(area, &mut buf, &cells, &starts, location);
buf
})
})
}
#[test]
fn file_ranges_highlight_wrapped_rows_and_blank_lines() {
let frames = [10, 52].map(|width| {
let [plain, painted] = range_buffers(width, /*bg*/ None);
let mut frame = vec![format!("width {width}")];
for y in 0..painted.area.height {
let text: String = (0..width).map(|x| painted[(x, y)].symbol()).collect();
let tinted = painted[(width - 1, y)].bg != plain[(width - 1, y)].bg;
if tinted || !text.trim().is_empty() {
let mark = if tinted { "+" } else { "." };
frame.push(format!("{mark} {text}").trim_end().to_owned());
}
}
frame.join("\n")
});
insta::assert_snapshot!(frames.join("\n\n"));
}
#[test]
fn file_ranges_keep_syntax_foregrounds_on_light_dark_and_unknown_backgrounds() {
use ratatui::style::Color;
for bg in [Some((20, 20, 20)), Some((246, 246, 246)), None] {
let [plain, painted] = range_buffers(/*width*/ 32, bg);
let tint = painted[(0, 1)].bg;
assert_ne!(tint, plain[(0, 1)].bg);
for x in 0..painted.area.width {
let cell = &painted[(x, 1)];
let fg = plain[(x, 1)].fg;
if fg == Color::Reset && bg.is_none() {
assert_ne!(cell.fg, Color::Reset);
} else {
assert_eq!(cell.fg, fg);
}
assert!(!cell.modifier.contains(Modifier::REVERSED));
assert_eq!(cell.bg, tint);
assert_eq!(painted[(x, 0)], plain[(x, 0)]);
}
}
}
+1 -4
View File
@@ -498,10 +498,7 @@ fn sidebar_files_keeps_remote_paths_for_the_owning_reader() {
files.entries,
vec![FileLink {
path,
location: Some(SourceLocation {
line: 12,
column: 4
}),
location: Some(SourceLocation::single(/*line*/ 12, Some(4))),
}],
);
}
@@ -380,7 +380,10 @@ async fn open_in_codex_scenario() -> Result<()> {
.show(SidebarContent::Chooser, PaneFocus::Main);
let mut revisit = preview("note.md");
if let AppEvent::OpenModelSidebarDocument { document, .. } = &mut revisit {
document.location = Some(crate::markdown_render::SourceLocation { line: 1, column: 1 });
document.location = Some(crate::markdown_render::SourceLocation::single(
/*line*/ 1,
Some(1),
));
}
boxed_future!(app.handle_event(&mut tui, &mut server, revisit)).await?;
boxed_future!(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)).await?;
@@ -0,0 +1,18 @@
---
source: tui/src/app/sidebar_document_tests.rs
expression: "frames.join(\"\\n\\n\")"
---
width 10
. before
+ let answer
+ = 42;
+
+ last
. after
width 52
. 1 before
+ 2 let answer = 42;
+ 3
+ 4 last
. 5 after
+10 -3
View File
@@ -93,14 +93,21 @@ pub(crate) enum Inline {
}
impl Inline {
pub(crate) fn from_event(event: &Event<'_>) -> Option<Self> {
pub(crate) fn from_event(
event: &Event<'_>,
is_hidden_destination: &dyn Fn(&str) -> bool,
) -> Option<Self> {
match event {
Event::Start(Tag::Emphasis) => Some(Self::Delimiter("_")),
Event::Start(Tag::Strong) => Some(Self::Delimiter("**")),
Event::Start(Tag::Strikethrough) => Some(Self::Delimiter("~~")),
Event::Start(Tag::Link { dest_url, .. }) => Some(
if crate::terminal_hyperlinks::web_destination(dest_url).is_some()
&& !dest_url.starts_with(crate::inline_visualization::LINK_PLACEHOLDER_PREFIX)
if (crate::terminal_hyperlinks::web_destination(dest_url).is_some()
&& !dest_url.starts_with(crate::inline_visualization::LINK_PLACEHOLDER_PREFIX))
|| (is_hidden_destination(dest_url)
&& crate::markdown_render::sidebar_file_link(dest_url)
.and_then(|link| link.location)
.is_some_and(|location| location.end.is_some()))
{
Self::Link(dest_url.as_ref().into())
} else {
+46 -26
View File
@@ -116,24 +116,41 @@ pub(crate) use web_links::hide_web_link_destination;
pub(crate) fn file_links(input: &str, cwd: Option<&Path>) -> Vec<FileLink> {
let options = Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES;
let directives = InlineDirectives::new(input, options);
directives
.events(
Parser::new_ext(&directives.markdown, options).into_offset_iter(),
cwd,
)
.filter_map(|(event, _)| match event {
let mut links = Vec::new();
let mut literal_depth = 0usize;
let events = directives.events(
Parser::new_ext(&directives.markdown, options).into_offset_iter(),
cwd,
);
for (event, range) in DecodedTextMerge::new(events) {
match event {
Event::Start(Tag::Link { dest_url, .. } | Tag::Image { dest_url, .. }) => {
sidebar_file_link(&dest_url)
links.extend(sidebar_file_link(&dest_url));
literal_depth += 1;
}
_ => None,
})
.collect()
Event::Start(Tag::CodeBlock(_)) => literal_depth += 1,
Event::End(TagEnd::Link | TagEnd::Image | TagEnd::CodeBlock) => {
literal_depth = literal_depth.saturating_sub(1);
}
Event::Text(text) if literal_depth == 0 => {
links.extend(
local_links::bare_file_ranges(
&text,
input.get(..range.start).unwrap_or_default(),
)
.map(|(_, file)| file),
);
}
_ => {}
}
}
links
}
pub(crate) fn hide_reader_link_destination(destination: &str) -> bool {
hide_web_link_destination(destination) || local_links::sidebar_file_link(destination).is_some()
}
use web_links::style_bare_web_urls;
use web_links::style_bare_links;
const TABLE_COLUMN_GAP: usize = 2;
const TABLE_CELL_PADDING: usize = 1;
@@ -648,7 +665,8 @@ impl<'a, 'policy> Writer<'a, 'policy> {
self.transformed_code_source = source;
}
self.prepare_for_event(&event);
let copy_inline = crate::markdown_copy::Inline::from_event(&event);
let copy_inline =
crate::markdown_copy::Inline::from_event(&event, self.is_hidden_link_destination);
if let Some(inline) = &copy_inline {
self.copy_inline.push(inline.clone());
}
@@ -682,7 +700,7 @@ impl<'a, 'policy> Writer<'a, 'policy> {
self.code_block_content.start = self.code_block_content.start.min(range.start);
self.code_block_content.end = range.end;
}
self.text(text);
self.text(text, range.start);
}
Event::Code(code) => self.code(code),
Event::SoftBreak => self.soft_break(),
@@ -947,7 +965,7 @@ impl<'a, 'policy> Writer<'a, 'policy> {
self.needs_newline = true;
}
fn text(&mut self, text: CowStr<'a>) {
fn text(&mut self, text: CowStr<'a>, mut source: usize) {
if self.collecting_local_link_label() {
let style = self.inline_styles.last().copied().unwrap_or_default();
for (index, line) in text.lines().enumerate() {
@@ -960,7 +978,7 @@ impl<'a, 'policy> Writer<'a, 'policy> {
}
self.line_ends_with_local_link_target = false;
if self.in_table_cell() {
self.push_text_to_table_cell(&text);
self.push_text_to_table_cell(&text, source);
return;
}
@@ -1001,9 +1019,10 @@ impl<'a, 'policy> Writer<'a, 'policy> {
if i > 0 {
self.push_line(Line::default());
}
let content = line.to_string();
let style = self.inline_styles.last().copied().unwrap_or_default();
self.push_text_spans(&content, style);
let annotated = self.annotate_text_span(line, style, source);
self.push_annotated(annotated);
source += line.len() + 1;
}
self.needs_newline = false;
}
@@ -1479,13 +1498,14 @@ impl<'a, 'policy> Writer<'a, 'policy> {
}
}
fn push_text_to_table_cell(&mut self, text: &str) {
fn push_text_to_table_cell(&mut self, text: &str, mut source: usize) {
let style = self.inline_styles.last().copied().unwrap_or_default();
for (i, line) in text.lines().enumerate() {
if i > 0 {
self.push_table_cell_hard_break();
}
let annotated = self.annotate_text_span(line, style);
let annotated = self.annotate_text_span(line, style, source);
source += line.len() + 1;
if let Some(table_state) = self.table_state.as_mut()
&& let Some(cell) = table_state.current_cell.as_mut()
{
@@ -2707,12 +2727,7 @@ impl<'a, 'policy> Writer<'a, 'policy> {
}
}
fn push_text_spans(&mut self, text: &str, style: Style) {
let annotated = self.annotate_text_span(text, style);
self.push_annotated(annotated);
}
fn annotate_text_span(&mut self, text: &str, style: Style) -> HyperlinkLine {
fn annotate_text_span(&mut self, text: &str, style: Style, source: usize) -> HyperlinkLine {
let span = self.style_link_label(Span::styled(text.to_string(), style));
let destination = self
.link
@@ -2730,7 +2745,12 @@ impl<'a, 'policy> Writer<'a, 'policy> {
} else if self.link.is_some() || self.in_code_block {
HyperlinkLine::new(Line::from(span))
} else {
style_bare_web_urls(span, self.styles.link)
style_bare_links(
span,
self.styles.link,
self.is_hidden_link_destination,
self.input.get(..source).unwrap_or_default(),
)
}
}
+141 -23
View File
@@ -28,9 +28,56 @@ static HASH_LOCATION_SUFFIX_RE: LazyLock<Regex> =
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct SourceLocation {
pub(crate) struct SourcePoint {
pub(crate) line: usize,
pub(crate) column: usize,
pub(crate) column: Option<usize>,
}
/// One-based source coordinates. An end point denotes an inclusive range of lines.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct SourceLocation {
pub(crate) start: SourcePoint,
pub(crate) end: Option<SourcePoint>,
}
impl SourceLocation {
pub(crate) fn single(line: usize, column: Option<usize>) -> Self {
Self {
// Single locations historically treat zero coordinates as one.
start: SourcePoint {
line: line.max(1),
column: column.map(|n| n.max(1)),
},
end: None,
}
}
// The suffix matchers validate the shape and normalize both spellings to colon form.
fn parse(suffix: &str) -> Option<Self> {
let mut points = suffix.strip_prefix(':')?.split(['-', '–']);
let parse_point = |point: &str| {
let mut fields = point.split(':');
Some(SourcePoint {
line: fields.next()?.parse().ok()?,
column: fields.next().map(str::parse).transpose().ok()?,
})
};
let start = parse_point(points.next()?)?;
let Some(end) = points.next() else {
return Some(Self::single(start.line, start.column));
};
let end = parse_point(end)?;
// Missing columns span from the start of the first line to the end of the last.
let first = (start.line, start.column.unwrap_or(1));
let last = (end.line, end.column.unwrap_or(usize::MAX));
if start.line == 0 || start.column == Some(0) || end.column == Some(0) || first > last {
return None;
}
Some(Self {
start,
end: Some(end),
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
@@ -58,19 +105,13 @@ pub(crate) fn sidebar_file_link(destination: &str) -> Option<FileLink> {
if destination.starts_with("file://") && Url::parse(destination).ok()?.has_host() {
return None;
}
let (path, location) = parse_local_link_target(destination)?;
let (path, location) = parse_local_link_target(destination, /*for_navigation*/ true)?;
if destination.contains('#') && location.is_none() {
return None;
}
let location = if let Some(suffix) = location {
let start = suffix.strip_prefix(':')?.split(['-', '–']).next()?;
let (line, column) = start.split_once(':').unwrap_or((start, "1"));
Some(SourceLocation {
line: line.parse::<usize>().ok()?.max(1),
column: column.parse::<usize>().ok()?.max(1),
})
} else {
None
let location = match location {
Some(suffix) => Some(SourceLocation::parse(&suffix)?),
None => None,
};
(!path.is_empty()
&& !path.ends_with('/')
@@ -82,6 +123,64 @@ pub(crate) fn sidebar_file_link(destination: &str) -> Option<FileLink> {
.then_some(FileLink { path, location })
}
/// Recognize complete, path-shaped range tokens in prose. Explicit Markdown links also
/// support spaces and extensionless filenames. Never infer a file from a bare number or URL.
pub(super) fn bare_file_ranges<'a>(
text: &'a str,
prefix: &str,
) -> impl Iterator<Item = (std::range::Range<usize>, FileLink)> + 'a {
// A formatting boundary may split a path or URL (e.g. src/__tests__/file.ts).
// Only start a link on a complete token, including one enclosed in emphasis.
let prefix = prefix.strip_suffix('\\').unwrap_or(prefix);
let at_boundary = prefix
.trim_end_matches(['*', '_', '~'])
.chars()
.next_back()
.is_none_or(|ch| {
ch.is_whitespace() || matches!(ch, '(' | '[' | '<' | '|' | '>' | '"' | '\'')
});
text.split_whitespace().filter_map(move |token| {
if !at_boundary && text.substr_range(token)?.start == 0 {
return None;
}
let token =
token.trim_end_matches([')', ']', '>', '"', '\'', '.', ',', ';', ':', '!', '?']);
if !token.ends_with(|ch: char| ch.is_ascii_digit())
|| !token.contains(['-', '–'])
|| !token.contains([':', '#'])
{
return None;
}
// Strip unmatched prose wrappers, preserving balanced [id] and (group) directories.
let mut paren = token
.matches('(')
.count()
.saturating_sub(token.matches(')').count());
let mut bracket = token
.matches('[')
.count()
.saturating_sub(token.matches(']').count());
let candidate = token.trim_start_matches(|ch| {
let remaining = match ch {
'(' => &mut paren,
'[' => &mut bracket,
_ => return matches!(ch, '<' | '"' | '\''),
};
let trim = *remaining > 0;
*remaining = remaining.saturating_sub(1);
trim
});
let link = sidebar_file_link(candidate)?;
if link.location?.end.is_none()
|| link.path.contains("://")
|| !link.path.contains(['.', '/', '\\'])
{
return None;
}
Some((text.substr_range(candidate)?, link))
})
}
pub(super) fn is_local_path_like_link(dest_url: &str) -> bool {
dest_url.starts_with("file://")
|| dest_url.starts_with('/')
@@ -101,7 +200,8 @@ pub(super) fn is_local_path_like_link(dest_url: &str) -> bool {
/// This accepts the path shapes Codex emits today: `file://` URLs, absolute and relative paths,
/// `~/...`, Windows paths, and `#L..C..` or `:line:col` suffixes.
pub(super) fn render_local_link_target(dest_url: &str, cwd: Option<&Path>) -> Option<String> {
let (path_text, location_suffix) = parse_local_link_target(dest_url)?;
let (path_text, location_suffix) =
parse_local_link_target(dest_url, /*for_navigation*/ false)?;
let mut rendered = display_local_link_path(&path_text, cwd);
if let Some(location_suffix) = location_suffix {
rendered.push_str(&location_suffix);
@@ -115,9 +215,11 @@ pub(super) fn render_local_link_target(dest_url: &str, cwd: Option<&Path>) -> Op
/// normalization preserves home-relative paths and uses forward slashes as separators.
/// A backslash in a POSIX file URI is part of the filename and is preserved.
///
/// Returns `None` only when the destination looks like a `file://` URL but cannot be parsed into a
/// local path. Plain path-like inputs always return `Some(...)` even if they are relative.
fn parse_local_link_target(dest_url: &str) -> Option<(String, Option<String>)> {
/// Navigation rejects partial ranges before decoding the filename.
fn parse_local_link_target(
dest_url: &str,
for_navigation: bool,
) -> Option<(String, Option<String>)> {
if dest_url.starts_with("file://") {
let url = Url::parse(dest_url).ok()?;
// Infer the path's OS from the URI, not the host running the TUI.
@@ -144,14 +246,17 @@ fn parse_local_link_target(dest_url: &str) -> Option<(String, Option<String>)> {
path_text = candidate_path;
location_suffix = Some(normalized);
}
if location_suffix.is_none()
&& let Some(suffix) = extract_colon_location_suffix(path_text)
{
let path_len = path_text.len().saturating_sub(suffix.len());
path_text = &path_text[..path_len];
location_suffix = Some(suffix);
// A valid hash location disambiguates colons and dashes in POSIX filenames.
if location_suffix.is_none() {
if let Some(suffix) = extract_colon_location_suffix(path_text) {
let path_len = path_text.len().saturating_sub(suffix.len());
path_text = &path_text[..path_len];
location_suffix = Some(suffix);
}
if for_navigation && has_unparsed_range(path_text) {
return None;
}
}
let decoded_path_text =
urlencoding::decode(path_text).unwrap_or(std::borrow::Cow::Borrowed(path_text));
Some((
@@ -160,6 +265,19 @@ fn parse_local_link_target(dest_url: &str) -> Option<(String, Option<String>)> {
))
}
// After removing a valid location, a remaining point followed by a dash
// signals a malformed or extra range. Ignore directories and filename stems.
fn has_unparsed_range(path: &str) -> bool {
let tail = path.rsplit(['.', '/', '\\']).next().unwrap_or(path);
let tail = &tail[tail.rfind('#').unwrap_or(0)..];
tail.rsplit(['-', '–']).skip(1).any(|point| {
COLON_LOCATION_SUFFIX_RE.is_match(point)
|| point
.strip_prefix('#')
.is_some_and(|fragment| HASH_LOCATION_SUFFIX_RE.is_match(fragment))
})
}
/// Normalize a hash fragment like `L12` or `L12C3-L14C9` into the display suffix we render.
///
/// Returns `None` for fragments that are not location references. This deliberately ignores other
@@ -18,13 +18,10 @@ fn trailing_separator_trimming_preserves_local_roots() {
#[test]
fn sidebar_keeps_line_and_column_for_extensionless_source_links() {
assert_eq!(
sidebar_file_link("./Makefile#L12C3"),
sidebar_file_link("./logs/14:54:42-debug#L12C3"),
Some(FileLink {
path: "./Makefile".into(),
location: Some(SourceLocation {
line: 12,
column: 3
}),
path: "./logs/14:54:42-debug".into(),
location: Some(SourceLocation::single(/*line*/ 12, Some(3))),
}),
);
for path in ["Makefile", "build/Makefile"] {
@@ -38,3 +35,99 @@ fn sidebar_keeps_line_and_column_for_extensionless_source_links() {
}
assert_eq!(sidebar_file_link("https://example.org/Makefile#L12"), None);
}
#[test]
fn file_ranges_parse_both_spellings_and_keep_columns() {
for path in [
"./src/search.ts",
"C:/repo/search.ts",
"./src/C#/f.cs",
"./logs/14:54:42-debug.txt",
] {
for (suffix, cols) in [
(":42-44", (None, None)),
(":42–44", (None, None)),
("#L42-L44", (None, None)),
(":42:5-44:10", (Some(5), Some(10))),
("#L42C5-L44C10", (Some(5), Some(10))),
] {
let link = sidebar_file_link(&format!("{path}{suffix}")).unwrap();
let location = link.location.unwrap();
let end = location.end.unwrap();
assert_eq!(link.path, path);
assert_eq!((location.start.line, end.line), (42, 44));
assert_eq!((location.start.column, end.column), cols);
}
}
assert_eq!(
sidebar_file_link("file:///repo/search.ts#L42-L44"),
sidebar_file_link("/repo/search.ts:42-44")
);
assert!(sidebar_file_link("a.ts:42-42").is_some());
}
#[test]
fn file_ranges_reject_malformed_reversed_and_overflowing_coordinates() {
for suffix in [
":42-",
":42-44-48",
":42-bad",
":42-44:bad",
"#L42-L",
"#L42-L44:2",
":44-42",
"#L44-L42",
":0-2",
":42:8-42:3",
":42-9999999999999999999999999999999999999",
"#L42-L0",
] {
assert_eq!(
sidebar_file_link(&format!("./src/search.ts{suffix}")),
None,
"{suffix}"
);
}
assert_eq!(
sidebar_file_link("./literal%3A42-").unwrap().path,
"./literal:42-"
);
}
#[test]
fn file_ranges_inventory_skips_code_and_link_labels() {
let input = r"src/search.ts:42-44 (src/other.ts#L5-L7). [src/label.ts:1-2](./src/dest.ts#L8-L9)
`src/inline.ts:1-2`
```
src/code.ts:1-2
```
src/_layout.tsx:1-2 src/[id]/route.ts#L1-L2 https://example.org/[id]/route.ts#L2-L3
src/__tests__/util.ts:42-44 https://example.org/__tests__/util.ts:42-44 **src/range.ts:1-2**
See (src/app/(auth)/page.tsx:2-3). See (((group)/page.tsx:2-3)). [log](./logs/14:54:42-debug#L3)
(group)/page.tsx:2-3 [id]/route.ts#L2-L3 \_\_init\_\_.py:1-2 !https://example.org/src/search.ts#L42-L44";
let expected = [
"src/search.ts:42-44",
"src/other.ts#L5-L7",
"./src/dest.ts#L8-L9",
"src/_layout.tsx:1-2",
"src/[id]/route.ts#L1-L2",
"src/range.ts:1-2",
"src/app/(auth)/page.tsx:2-3",
"(group)/page.tsx:2-3",
"./logs/14:54:42-debug#L3",
"(group)/page.tsx:2-3",
"[id]/route.ts#L2-L3",
"__init__.py:1-2",
]
.map(|dest| sidebar_file_link(dest).unwrap());
assert_eq!(
crate::markdown_render::file_links(input, /*cwd*/ None),
expected
);
}
+26 -3
View File
@@ -1,4 +1,4 @@
//! Styling and destination visibility for web links in semantic Markdown output.
//! Styling bare links and controlling web destination visibility in semantic Markdown output.
//!
//! Terminal identity is a conservative heuristic, not end-to-end capability negotiation. Unknown
//! terminals and multiplexers retain the destination so a label never hides the only usable URL.
@@ -13,13 +13,36 @@ use ratatui::text::Span;
use unicode_segmentation::UnicodeSegmentation;
use crate::terminal_hyperlinks::HyperlinkLine;
use crate::terminal_hyperlinks::TerminalHyperlink;
use crate::terminal_hyperlinks::annotate_web_urls_in_line;
use crate::terminal_hyperlinks::source_text_width;
use crate::terminal_hyperlinks::web_destination;
use crate::width::display_width;
/// Give detected URLs the same affordance as explicit Markdown links, preserving surrounding text.
pub(super) fn style_bare_web_urls(span: Span<'static>, link_style: Style) -> HyperlinkLine {
/// Give detected links the same affordance as explicit Markdown links, preserving surrounding text.
pub(super) fn style_bare_links(
span: Span<'static>,
link_style: Style,
is_hidden_destination: &dyn Fn(&str) -> bool,
prefix: &str,
) -> HyperlinkLine {
let mut line = annotate_web_urls_in_line(Line::from(span));
let text = &line.line.spans[0].content;
let mut previous_byte = 0;
let mut previous_column = 0;
for (range, file) in super::local_links::bare_file_ranges(text, prefix) {
if !is_hidden_destination(&text[range]) {
continue;
}
let start = previous_column + source_text_width(&text[previous_byte..range.start]);
let end = start + source_text_width(&text[range]);
previous_byte = range.end;
previous_column = end;
let mut link = TerminalHyperlink::document(start..end, file);
link.markdown_source = Some(prefix.len() + range.start);
line.hyperlinks.push(link);
}
line.hyperlinks.sort_by_key(|link| link.columns.start);
if line.hyperlinks.is_empty() {
return line;
}
@@ -41,17 +41,20 @@ fn bare_urls_are_styled_without_coloring_surrounding_prose() {
}
#[test]
fn bare_url_styling_preserves_tabs_and_unicode() {
let line = super::style_bare_web_urls(
"界\t(https://example.com).".bold(),
fn bare_link_styling_preserves_tabs_and_unicode() {
let line = super::style_bare_links(
"界\t(https://example.com). لا src/a.ts:2-3".bold(),
Style::new().fg(accent_color()).underlined(),
&|_| true,
"",
);
assert_eq!(
line.line,
Line::from(vec![
"界\t(".bold(),
"https://example.com".bold().fg(accent_color()).underlined(),
").".bold(),
"). لا ".bold(),
"src/a.ts:2-3".bold().fg(accent_color()).underlined(),
]),
);
}
@@ -260,8 +263,8 @@ fn label_only_web_links_keep_targets_after_prose_and_table_wrapping() {
#[test]
fn streaming_and_full_render_agree_with_label_only_links() {
let markdown = "See [**label**](https://example.com).\n\n| Resource |\n| --- |\n| [`code`](https://example.com/code) |\n\nTrailing text.";
let display = WebLinkDisplay::LabelOnly;
let markdown = "See [**label**](https://example.com) and src/f.ts:42-44.\n\n| Resource |\n| --- |\n| [`code`](https://example.com/code) |\n| [source](./src/f.ts#L42-L44) |\n\nTrailing text.";
let hide_destination = &|_: &str| true;
for width in [12, 40] {
for end in 1..=markdown.len() {
let prefix = &markdown[..end];
@@ -269,10 +272,16 @@ fn streaming_and_full_render_agree_with_label_only_links() {
prefix,
Some(width),
/*cwd*/ None,
&|destination| display.hide_destination(destination),
hide_destination,
crate::markdown_render::ListSpacing::AfterMultiline,
);
assert_eq!(streamed.lines, render(prefix, width, display));
let full = render_markdown_lines_with_width_cwd_and_hidden_link_destinations(
prefix,
Some(width),
/*cwd*/ None,
hide_destination,
);
assert_eq!(streamed.lines, full);
}
}
}
+1 -4
View File
@@ -111,10 +111,7 @@ pub(crate) async fn execute(
.resolve_thread_file(thread_id, &original_path)
.await
.map_err(|_| McpError::invalid_params("File preview is unavailable for this path", None))?;
let location = line.map(|line| SourceLocation {
line: line.get(),
column: 1,
});
let location = line.map(|line| SourceLocation::single(line.get(), /*column*/ None));
events
.app_event_tx
.send(AppEvent::OpenModelSidebarDocument {
+1 -1
View File
@@ -49,7 +49,7 @@ pub(crate) struct TerminalHyperlink {
pub(crate) columns: Range<usize>,
pub(crate) destination: String,
destination_kind: DestinationKind,
/// Byte offset of an explicit Markdown link, preserved through wrapping.
/// Source offset identifying one Markdown link occurrence across wrapped rows.
pub(crate) markdown_source: Option<usize>,
}
+1
View File
@@ -12,6 +12,7 @@ mod copy_mode;
mod disclosure;
mod document;
pub(crate) use document::DocumentPosition;
pub(crate) use document::DocumentTarget;
mod follow_control;
mod footer;
mod input;
+53 -9
View File
@@ -1,6 +1,8 @@
//! Render source locations in the file reader using the transcript's wrapped rows.
use ratatui::style::Color;
use ratatui::style::Modifier;
use ratatui::style::Style;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Widget;
@@ -14,6 +16,40 @@ pub(crate) enum DocumentPosition {
Latest,
}
/// Resolved logical lines and the grapheme-aligned byte offset used for scrolling.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct DocumentTarget {
pub(crate) first_line: usize,
pub(crate) last_line: usize,
pub(crate) offset: usize,
pub(crate) mark_column: bool,
}
/// A terminal may not report its background. Pair the syntax theme's canvas with
/// its text color for unstyled glyphs, and preserve syntax-specific foregrounds.
fn source_highlight() -> (Style, Option<Color>) {
use crate::render::highlight::convert_syntect_color;
let (background, foreground) = match crate::terminal_palette::default_bg() {
Some(bg) => (Some(bg), None),
None => crate::render::highlight::with_syntax_theme(|theme| {
let background = match theme.settings.background.and_then(convert_syntect_color) {
Some(Color::Rgb(r, g, b)) => Some((r, g, b)),
_ => None,
};
(
background,
theme.settings.foreground.and_then(convert_syntect_color),
)
}),
};
let style = crate::style::user_message_style_for(background);
if matches!(style.bg, None | Some(Color::Reset)) {
(crate::style::selection_style(), None)
} else {
(style, foreground)
}
}
impl TranscriptView {
/// During a live resize, wrap the already rendered file instead of parsing it at every width.
pub(crate) fn set_document_resize_preview(&mut self, active: bool) {
@@ -33,7 +69,7 @@ impl TranscriptView {
buf: &mut Buffer,
cells: &[Arc<dyn HistoryCell>],
line_starts: &[usize],
target: Option<(usize, usize)>,
target: Option<DocumentTarget>,
) {
let digits = line_starts
.len()
@@ -49,6 +85,7 @@ impl TranscriptView {
if line_starts.is_empty() {
return;
}
let highlight = target.map(|target| (target, source_highlight()));
for (y, visible) in (area.top()..area.bottom()).zip(&self.visible) {
let offset = visible.layout.position_at(visible.row, /*column*/ 0);
let line = line_starts.partition_point(|start| *start <= offset);
@@ -58,18 +95,25 @@ impl TranscriptView {
.right_aligned()
.render(Rect::new(area.x, y, digits, /*height*/ 1), buf);
}
if let Some((target_line, target_offset)) = target
&& line == target_line
if let Some((target, (style, foreground))) = highlight
&& (target.first_line..=target.last_line).contains(&line)
{
let mut style = crate::style::user_message_style();
if style.bg.is_none() {
style = crate::style::selection_style();
for x in text.left()..text.right() {
let cell = &mut buf[(x, y)];
cell.set_style(style);
if let Some(fg) = foreground
&& cell.fg == Color::Reset
{
cell.set_fg(fg);
}
}
buf.set_style(Rect::new(text.x, y, text.width, /*height*/ 1), style);
if visible.row == visible.layout.row_for_offset(target_offset) {
if target.mark_column
&& line == target.first_line
&& visible.row == visible.layout.row_for_offset(target.offset)
{
let x = text
.x
.saturating_add(visible.layout.column_for_offset(target_offset));
.saturating_add(visible.layout.column_for_offset(target.offset));
if x < text.right() {
let cell = &mut buf[(x, y)];
let style = cell.style();
+9 -9
View File
@@ -162,7 +162,7 @@ impl TranscriptView {
None if forward => 0,
None => count - 1,
};
let offset = links[index].0.start;
let offset = links[index].0.first()?.start;
let row = layout.row_for_offset(offset);
if !self
.visible
@@ -195,17 +195,17 @@ impl TranscriptView {
let Some(layout) = self.layout(cells, /*index*/ 0) else {
return;
};
let Some((range, _)) = layout.document_links().into_iter().nth(index) else {
let Some((ranges, _)) = layout.document_links().into_iter().nth(index) else {
return;
};
for (row, visible) in self.visible.iter().enumerate() {
for (y, visible) in (self.area.top()..self.area.bottom()).zip(&self.visible) {
if visible.index == 0 {
visible.layout.highlight(
range.clone(),
Rect::new(self.area.x, self.area.y + row as u16, self.area.width, 1),
buf,
visible.row,
);
let area = Rect::new(self.area.x, y, self.area.width, /*height*/ 1);
for range in &ranges {
visible
.layout
.highlight(range.clone(), area, buf, visible.row);
}
}
}
}
@@ -269,7 +269,7 @@ fn workspace_file_links_show_the_title_with_subtle_hover_and_open_the_same_locat
link,
FileLink {
path: "./guide.md".to_string(),
location: Some(SourceLocation { line: 3, column: 2 }),
location: Some(SourceLocation::single(/*line*/ 3, Some(2))),
},
);
}
@@ -559,3 +559,61 @@ fn modified_clicks_still_open_immediately() {
assert!(view.selection.is_none());
}
}
#[test]
fn file_ranges_open_from_wrapped_prose_and_table_fragments() {
use crate::markdown_render::sidebar_file_link;
use crate::terminal_hyperlinks::ReaderLink;
use ratatui::style::Modifier;
crate::markdown_render::preferences::set_document_links(/*enabled*/ true);
let left = "src/app/(auth)/search_results.tsx:42-44";
let right = "src/components/search_filters.tsx#L5-L7";
let explicit = format!("[{right}]({right})");
let prose = format!("See ({left}).\n\n{explicit}");
let table = format!("| File | Related |\n|---|---|\n| ({left}). | {explicit} |");
for (source, width) in [(&prose, 36), (&table, 36), (&table, 54)] {
let (mut view, cells) = transcript(source, width);
view.document_links = true;
let area = view.area;
let mut selected = None;
let mut hit_rows = [Vec::new(), Vec::new()];
for (index, path) in [left, right].into_iter().enumerate() {
selected = view.cycle_document_link(&cells, selected, /*forward*/ true);
assert_eq!(selected, Some(index));
let expected = sidebar_file_link(path).unwrap();
let link = ReaderLink::Document(expected.clone());
assert_eq!(view.document_link(&cells, index).as_ref(), Some(&link));
let mut highlight = Buffer::empty(area);
view.paint_document_link(&cells, index, &mut highlight);
for y in area.y..area.bottom() {
let mut first = None;
for x in area.x..area.right() {
let hit = view.reader_link_at(x, y).as_ref() == Some(&link);
let focused = highlight[(x, y)].modifier.contains(Modifier::REVERSED);
assert_eq!(focused, hit, "focus at {x},{y} for {path} at width {width}");
if hit {
first.get_or_insert(x);
}
}
if let Some(x) = first {
let press = mouse(MouseEventKind::Down(MouseButton::Left), x, y);
let release = mouse(MouseEventKind::Up(MouseButton::Left), x, y);
view.handle_mouse(press, &cells);
assert!(matches!(view.handle_mouse(release, &cells),
Some(ViewAction::OpenDocument(file)) if file == expected));
hit_rows[index].push(y);
}
}
assert!(hit_rows[index].len() >= 2, "expected wrapped {path}");
}
for (forward, index) in [(true, 0), (false, 1)] {
selected = view.cycle_document_link(&cells, selected, forward);
assert_eq!(selected, Some(index));
}
if width == 54 {
// Both columns contribute a fragment to each of the first two rows.
assert_eq!(hit_rows[0][..2], hit_rows[1][..2]);
}
}
}
@@ -878,3 +878,19 @@ fn selected_list_and_code_containers_keep_their_structure() {
);
}
}
#[test]
fn file_ranges_keep_hidden_destinations_when_copying_markdown() {
crate::markdown_render::preferences::set_document_links(/*enabled*/ true);
for dest in ["./src/search.ts#L42-L44", "./src/search.ts:42:5-44:10"] {
let link = format!("[src/search.ts:42-44](<{dest}>)");
for source in [&link, &format!("| Location |\n|---|\n| {link} |")] {
for width in [12, 80] {
let layout = markdown_layout(source, width);
let (copied, _) = payload(&layout, 0..layout.text().len());
assert_eq!(copied.matches(&link).count(), 1, "{copied}");
assert!(!layout.text().contains(dest));
}
}
}
}
+21 -15
View File
@@ -1006,9 +1006,10 @@ impl TextLayout {
}
}
pub(super) fn document_links(&self) -> Vec<(Range<usize>, ReaderLink)> {
let mut stops: Vec<(Range<usize>, ReaderLink)> = Vec::new();
let mut previous_source = None;
pub(super) fn document_links(&self) -> Vec<(Vec<Range<usize>>, ReaderLink)> {
// Wrapped table cells can interleave fragments of different links on each row.
let mut stops: Vec<(Vec<Range<usize>>, ReaderLink)> = Vec::new();
let mut occurrences = std::collections::HashMap::new();
for (index, row) in self.rows.iter().enumerate() {
let inset = row.first_column - row.prefix_columns;
for link in &row.line.hyperlinks {
@@ -1022,21 +1023,26 @@ impl TextLayout {
if range.is_empty() {
continue;
}
if let Some((previous, previous_destination)) = stops.last_mut()
let index = occurrences
.entry(link.markdown_source)
.or_insert(stops.len());
if let Some((ranges, previous_destination)) = stops.get_mut(*index)
&& *previous_destination == destination
&& previous_source == link.markdown_source
&& (previous.end == range.start
|| (previous_source.is_some()
&& self
.text
.get(previous.end..range.start)
.is_some_and(|gap| gap.chars().all(char::is_whitespace))))
{
previous.end = range.end;
} else {
previous_source = link.markdown_source;
stops.push((range, destination));
// Without a Markdown source offset only touching fragments identify one link.
if let Some(previous) = ranges.last_mut()
&& previous.end == range.start
{
previous.end = range.end;
continue;
}
if link.markdown_source.is_some() {
ranges.push(range);
continue;
}
}
*index = stops.len();
stops.push((vec![range], destination));
}
}
stops
@@ -476,7 +476,13 @@ fn document_link_navigation_preserves_occurrences_across_wraps() {
let links = layout
.document_links()
.into_iter()
.map(|(range, _)| &layout.text()[range])
.map(|(ranges, _)| {
ranges
.into_iter()
.map(|range| &layout.text()[range])
.collect::<Vec<_>>()
.join(" ")
})
.collect::<Vec<_>>();
assert_eq!(links, ["first link wraps", "second link"]);
}