Open source file links at line and column targets in the TUI (#61890)

## What changed

- Extend sidebar previews beyond Markdown to source files, including extensionless files. Preserve line and column targets such as `./Makefile#L12C3`, scroll to the target, and highlight its line and character.
- Render source previews with syntax highlighting and line numbers when space permits. Keep plain Markdown links rendered as Markdown, and show source when a location is specified.
- Show local link labels without appended destinations when workspace previews are available, and emphasize links on hover. Refresh rendering when preview availability changes.
- Limit source previews to 1 MiB and 10,000 lines, and disable document previews for Windows workspaces.

## Testing

Add coverage for extensionless link parsing, matching hover and click targets, streamed file citation metadata, and source navigation with CRLF input, tab reuse, and Escape handling.

GitOrigin-RevId: c2629b122628a4f5afa17df1890f63bd1c9bbcf6
This commit is contained in:
Felipe Coury
2026-11-16 21:50:03 +00:00
committed by copyberry
parent 7c3f5e2cc2
commit 3a51865c8c
30 changed files with 846 additions and 201 deletions
@@ -0,0 +1,89 @@
//! Render source locations in the file reader using the transcript's wrapped rows.
use ratatui::style::Modifier;
use ratatui::style::Stylize;
use ratatui::text::Line;
use ratatui::widgets::Widget;
use super::*;
impl TranscriptView {
pub(crate) fn render_document(
&mut self,
area: Rect,
buf: &mut Buffer,
cells: &[Arc<dyn HistoryCell>],
line_starts: &[usize],
target: Option<(usize, usize)>,
) {
let digits = line_starts
.len()
.checked_ilog10()
.map_or(0, |n| n as u16 + 1);
let gutter = if digits > 0 && area.width > 40 + digits {
digits + 1
} else {
0
};
let text = Rect::new(area.x + gutter, area.y, area.width - gutter, area.height);
self.render(text, buf, cells);
if line_starts.is_empty() {
return;
}
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);
if gutter > 0 && line > 0 && line_starts[line - 1] == offset {
Line::from(line.to_string())
.dim()
.right_aligned()
.render(Rect::new(area.x, y, digits, /*height*/ 1), buf);
}
if let Some((target_line, target_offset)) = target
&& line == target_line
{
let mut style = crate::style::user_message_style();
if style.bg.is_none() {
style = crate::style::selection_style();
}
buf.set_style(Rect::new(text.x, y, text.width, /*height*/ 1), style);
if visible.row == visible.layout.row_for_offset(target_offset) {
let x = text
.x
.saturating_add(visible.layout.column_for_offset(target_offset));
if x < text.right() {
let cell = &mut buf[(x, y)];
let style = cell.style();
cell.set_style(if style.add_modifier.contains(Modifier::REVERSED) {
style.not_reversed()
} else {
style.reversed()
});
}
}
}
}
}
pub(crate) fn paint_document_scroll_indicators(
&mut self,
area: Rect,
buf: &mut Buffer,
cells: &[Arc<dyn HistoryCell>],
) {
if area.height < 2 || area.width < 3 {
return;
}
let start = self.start(cells);
for (visible, row, arrow) in [
(start > (0, 0), area.top(), "↑"),
(start < self.bottom_start(cells), area.bottom() - 1, "↓"),
] {
if visible {
buf[(area.right() - 1, row)]
.set_symbol(arrow)
.set_style(crate::style::secondary_text_style());
}
}
}
}
+26 -13
View File
@@ -18,6 +18,8 @@ use crossterm::event::MouseEventKind;
use ratatui::layout::Position as ScreenPosition;
use super::*;
use crate::markdown_render::FileLink;
use crate::terminal_hyperlinks::ReaderLink;
pub(crate) enum ViewAction {
Changed,
@@ -27,6 +29,16 @@ pub(crate) enum ViewAction {
PrimarySelection(String),
CopyAndFollow(String),
OpenLink(String),
OpenDocument(FileLink),
}
impl From<ReaderLink> for ViewAction {
fn from(link: ReaderLink) -> Self {
match link {
ReaderLink::External(url) => Self::OpenLink(url),
ReaderLink::Document(link) => Self::OpenDocument(link),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -106,19 +118,20 @@ impl TranscriptView {
| ViewAction::ExitSelectMode
| ViewAction::Copy(_)
| ViewAction::CopyAndFollow(_)
| ViewAction::OpenDocument(_)
| ViewAction::OpenLink(_) => SelectionCopy::EXPLICIT,
}
}
/// Resolve links in the last rendered transcript, sharing geometry with click activation.
pub(crate) fn link_at(&self, column: u16, row: u16) -> Option<String> {
if !self.area.contains(ScreenPosition::new(column, row)) {
return None;
}
let visible = self.visible.get(usize::from(row - self.area.y))?;
visible
.layout
.link_at(visible.row, column - self.area.x, self.document_links)
self.reader_link_at(column, row)
.map(ReaderLink::into_destination)
}
fn reader_link_at(&self, column: u16, row: u16) -> Option<ReaderLink> {
let (_, link) = self.raw_link_at(ScreenPosition::new(column, row))?;
link.reader_destination(self.document_links)
}
pub(crate) fn cycle_document_link(
@@ -155,7 +168,7 @@ impl TranscriptView {
&mut self,
cells: &[Arc<dyn HistoryCell>],
index: usize,
) -> Option<String> {
) -> Option<ReaderLink> {
self.layout(cells, /*index*/ 0)?
.document_links()
.into_iter()
@@ -477,7 +490,7 @@ impl TranscriptView {
None
};
let link = link.filter(|destination| {
self.link_at(event.column, event.row).as_ref() == Some(destination)
self.reader_link_at(event.column, event.row).as_ref() == Some(destination)
});
if self
.selection
@@ -492,7 +505,7 @@ impl TranscriptView {
self.end_selection(cells);
}
if let Some(link) = link {
return Some(ViewAction::OpenLink(link));
return Some(link.into());
}
if let Some(text) = selected.filter(|text| !text.is_empty()) {
if self.copy_on_select {
@@ -605,8 +618,8 @@ impl TranscriptView {
.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER)
{
return self
.link_at(event.column, event.row)
.map(ViewAction::OpenLink);
.reader_link_at(event.column, event.row)
.map(ViewAction::from);
}
if event.modifiers == KeyModifiers::SHIFT && self.has_selection_range() {
self.last_click = None;
@@ -633,7 +646,7 @@ impl TranscriptView {
}
}
let link = (mode == MouseMode::Interactive && clicks == 1 && event.modifiers.is_empty())
.then(|| self.link_at(event.column, event.row))
.then(|| self.reader_link_at(event.column, event.row))
.flatten();
self.begin_selection(cells, event.column, event.row, clicks);
if let Some(selection) = &mut self.selection {
@@ -174,6 +174,63 @@ fn hover_links_match_wrapped_click_targets_and_refresh_after_scrolling() {
);
}
#[test]
fn workspace_file_links_show_the_title_with_subtle_hover_and_open_the_same_location() {
use crate::markdown_render::FileLink;
use crate::markdown_render::SourceLocation;
use ratatui::style::Modifier;
crate::markdown_render::preferences::set_document_links(/*enabled*/ true);
let (mut view, cells) = transcript(
"[Guide](./guide.md#L3C2) and [](./guide.md#L3C2)",
/*width*/ 32,
);
view.document_links = true;
let area = view.area;
let mut idle = Buffer::empty(area);
view.render(area, &mut idle, &cells);
let title = ScreenPosition::new(area.x + 3, area.y);
let path = ScreenPosition::new(area.x + 13, area.y);
let mut observations = vec![
crate::transcript_view::tests::text(&idle)
.trim()
.to_string(),
];
for (name, point) in [("title", title), ("filename", path)] {
let mut hovered = idle.clone();
view.paint_document_links(&mut hovered, Some(point));
observations.push(format!(
"{name}: underline={}, hover bold={}, background unchanged={}",
hovered[point].modifier.contains(Modifier::UNDERLINED),
hovered[point].modifier.contains(Modifier::BOLD),
hovered[point].bg == idle[point].bg,
));
view.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), point.x, point.y),
&cells,
);
let Some(ViewAction::OpenDocument(link)) = view.handle_mouse(
mouse(MouseEventKind::Up(MouseButton::Left), point.x, point.y),
&cells,
) else {
panic!("{name} click should open a document");
};
assert_eq!(
link,
FileLink {
path: "./guide.md".to_string(),
location: Some(SourceLocation { line: 3, column: 2 }),
},
);
}
insta::assert_snapshot!(observations.join("\n"), @"
• Guide and ./guide.md:3:2
title: underline=true, hover bold=true, background unchanged=true
filename: underline=false, hover bold=true, background unchanged=true
");
}
#[test]
fn shift_click_extends_a_double_clicked_word_in_both_directions() {
let (mut view, cells) = transcript("alpha beta gamma", /*width*/ 24);
@@ -110,6 +110,7 @@ pub(super) struct LayoutCache {
#[derive(PartialEq, Eq)]
struct RenderState {
theme: u64,
document_links: bool,
foreground: Option<(u8, u8, u8)>,
background: Option<(u8, u8, u8)>,
color_level: crate::terminal_palette::StdoutColorLevel,
@@ -318,6 +319,7 @@ impl LayoutCache {
self.frame = self.frame.wrapping_add(/*rhs*/ 1);
let state = RenderState {
theme: crate::render::highlight::syntax_theme_revision(),
document_links: crate::markdown_render::preferences::document_links_enabled(),
foreground: crate::terminal_palette::default_fg(),
background: crate::terminal_palette::default_bg(),
color_level: crate::terminal_palette::stdout_color_level(),
@@ -117,7 +117,7 @@ pub(super) struct Selection {
pointer_origin_row: u16,
pub(super) resume_on_empty: bool,
pub(super) pointer: Option<ScreenPosition>,
pub(super) pressed_link: Option<String>,
pub(super) pressed_link: Option<crate::terminal_hyperlinks::ReaderLink>,
origin: (Anchor, Anchor),
table_cell: Option<TableSelection>,
unit: SelectionUnit,
@@ -661,7 +661,10 @@ impl TranscriptView {
| ViewAction::CopyOnSelect(text)
| ViewAction::PrimarySelection(text)
| ViewAction::CopyAndFollow(text) => text.as_str(),
ViewAction::Changed | ViewAction::ExitSelectMode | ViewAction::OpenLink(_) => {
ViewAction::Changed
| ViewAction::ExitSelectMode
| ViewAction::OpenLink(_)
| ViewAction::OpenDocument(_) => {
return None;
}
};
+22 -9
View File
@@ -32,6 +32,8 @@ use crate::terminal_hyperlinks::HyperlinkLine;
use crate::terminal_hyperlinks::HyperlinkParagraph;
use crate::terminal_hyperlinks::LineWrapPolicy;
use crate::terminal_hyperlinks::LogicalLineSource;
use crate::terminal_hyperlinks::ReaderLink;
use crate::terminal_hyperlinks::TerminalHyperlink;
use crate::terminal_hyperlinks::remap_source_wrapped_line;
use crate::width::display_width;
use crate::wrapping::RtOptions;
@@ -847,8 +849,8 @@ impl TextLayout {
}
}
pub(super) fn document_links(&self) -> Vec<(Range<usize>, String)> {
let mut stops: Vec<(Range<usize>, String)> = Vec::new();
pub(super) fn document_links(&self) -> Vec<(Range<usize>, ReaderLink)> {
let mut stops: Vec<(Range<usize>, ReaderLink)> = Vec::new();
let mut previous_source = None;
for (index, row) in self.rows.iter().enumerate() {
let inset = row.first_column - row.prefix_columns;
@@ -884,14 +886,25 @@ impl TextLayout {
}
/// Resolve an OSC-8 destination or a document target when the workspace enables previews.
pub(super) fn link_at(&self, row: usize, column: u16, documents: bool) -> Option<String> {
#[cfg(test)]
pub(super) fn reader_link_at(
&self,
row: usize,
column: u16,
documents: bool,
) -> Option<ReaderLink> {
self.raw_link_at(row, column)?.reader_destination(documents)
}
pub(super) fn raw_link_at(&self, row: usize, column: u16) -> Option<&TerminalHyperlink> {
let (inset, links) = self.row_links(row)?;
let column = usize::from(column).checked_sub(inset)?;
links.iter().find(|link| link.columns.contains(&column))
}
pub(super) fn row_links(&self, row: usize) -> Option<(usize, &[TerminalHyperlink])> {
let row = self.rows.get(row)?;
let column = usize::from(column).checked_sub(row.first_column - row.prefix_columns)?;
row.line
.hyperlinks
.iter()
.find(|link| link.columns.contains(&column))?
.reader_destination(documents)
Some((row.first_column - row.prefix_columns, &row.line.hyperlinks))
}
fn visible_rows(&self, area: Rect, start_row: usize) -> impl Iterator<Item = (u16, &TextRow)> {
@@ -36,13 +36,16 @@ fn styled_tabs_use_row_stops_including_the_gutter() {
assert_eq!(
(
layout
.link_at(/*row*/ 0, /*column*/ 16, /*documents*/ false)
.reader_link_at(/*row*/ 0, /*column*/ 16, /*documents*/ false)
.map(crate::terminal_hyperlinks::ReaderLink::into_destination)
.as_deref(),
layout
.link_at(/*row*/ 0, /*column*/ 24, /*documents*/ false)
.reader_link_at(/*row*/ 0, /*column*/ 24, /*documents*/ false)
.map(crate::terminal_hyperlinks::ReaderLink::into_destination)
.as_deref(),
layout
.link_at(/*row*/ 0, /*column*/ 13, /*documents*/ false)
.reader_link_at(/*row*/ 0, /*column*/ 13, /*documents*/ false)
.map(crate::terminal_hyperlinks::ReaderLink::into_destination)
.as_deref()
),
(
@@ -94,7 +97,8 @@ fn tab_stops_restart_after_wrapping_and_resize_preserves_source_and_links() {
);
assert_eq!(
layout
.link_at(/*row*/ 1, /*column*/ 8, /*documents*/ false)
.reader_link_at(/*row*/ 1, /*column*/ 8, /*documents*/ false)
.map(crate::terminal_hyperlinks::ReaderLink::into_destination)
.as_deref(),
Some("https://example.com/x")
);
+10 -4
View File
@@ -192,12 +192,13 @@ fn aligned_text_excludes_synthetic_leading_columns() {
line.push_span("wide".into(), Some("https://example.com"));
let layout = TextLayout::new(vec![line], /*width*/ 8);
assert_eq!(
layout.link_at(/*row*/ 0, /*column*/ 3, /*documents*/ false),
layout.reader_link_at(/*row*/ 0, /*column*/ 3, /*documents*/ false),
None
);
assert_eq!(
layout
.link_at(/*row*/ 0, /*column*/ 4, /*documents*/ false)
.reader_link_at(/*row*/ 0, /*column*/ 4, /*documents*/ false)
.map(crate::terminal_hyperlinks::ReaderLink::into_destination)
.as_deref(),
Some("https://example.com")
);
@@ -271,7 +272,8 @@ fn selected_revision_rewraps_both_directions_with_styles_and_indents() {
restored.render(narrow_area, &mut restored_buffer, /*start_row*/ 0);
assert_eq!(restored_buffer, original_buffer);
assert_eq!(
wide.link_at(/*row*/ 0, /*column*/ 8, /*documents*/ false)
wide.reader_link_at(/*row*/ 0, /*column*/ 8, /*documents*/ false)
.map(crate::terminal_hyperlinks::ReaderLink::into_destination)
.as_deref(),
Some("https://example.com")
);
@@ -445,7 +447,11 @@ fn rendered_markdown_file_targets_are_only_interactive_in_the_workspace() {
let layout = &layout;
(0..layout.row_count())
.flat_map(|row| {
(0..40).filter_map(move |column| layout.link_at(row, column, documents))
(0..40).filter_map(move |column| {
layout
.reader_link_at(row, column, documents)
.map(crate::terminal_hyperlinks::ReaderLink::into_destination)
})
})
.collect::<std::collections::BTreeSet<_>>()
};