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
+6 -1
View File
@@ -872,6 +872,9 @@ impl App {
event: TuiEvent,
) -> Result<AppRunControl> {
self.transcript_view.document_links = self.document_preview_available(tui, app_server);
crate::markdown_render::preferences::set_document_links(
self.transcript_view.document_links,
);
self.transcript_view
.sync_patch_approval(self.chat_widget.current_patch_approval());
// A chooser action must never decide a modal that has not been painted yet.
@@ -899,7 +902,9 @@ impl App {
tui.link_hover.observe(&event);
let current = tui.link_hover.position();
if previous != current
&& self.hovered_sidebar_target(previous) != self.hovered_sidebar_target(current)
&& (self.hovered_sidebar_target(previous) != self.hovered_sidebar_target(current)
|| previous.is_some_and(|point| self.transcript_view.has_document_link_at(point))
|| current.is_some_and(|point| self.transcript_view.has_document_link_at(point)))
{
tui.frame_requester().schedule_frame();
}
@@ -470,6 +470,7 @@ impl App {
self.app_event_tx = AppEventSender::new(self.app_event_tx.app_event_tx.clone());
self.app_server_backend_id = Some(destination.backend_id());
self.app_server_target = target;
self.refresh_transcript_document_links();
self.reconnect = Default::default();
if let Ok(mut state) = self.agents_overview.view_state.lock() {
state.connection_notice = None;
@@ -511,6 +511,7 @@ impl App {
self.chat_widget.local_settings.tui.status_line_provider =
self.local_settings.tui.status_line_provider.clone();
self.config = config;
self.refresh_transcript_document_links();
self.chat_widget.sync_plugin_mentions_config(&self.config);
Ok(())
}
+4 -4
View File
@@ -3583,15 +3583,15 @@ impl App {
Box::pin(self.open_saved_chat(tui, app_server, target)).await?;
}
}
AppEvent::OpenSidebarDocument { backend_id, source, path } => {
AppEvent::OpenSidebarDocument { backend_id, source, link } => {
if app_server.backend_id() == backend_id
&& self.current_displayed_thread_id() == Some(source)
&& self.document_preview_available(tui, app_server)
{
Box::pin(self.open_document(tui, app_server, source, path)).await?;
Box::pin(self.open_document(tui, app_server, source, link)).await?;
}
}
AppEvent::SidebarDocumentResolved { backend_id, parent, source, request, original_path, path, } => {
AppEvent::SidebarDocumentResolved { backend_id, parent, source, request, original_path, path, location, } => {
if backend_id == app_server.backend_id()
&& self.sidebar_parent() == Some(parent)
&& let Some(pane) = self.sidebars.get_mut(&Some(parent))
@@ -3605,7 +3605,7 @@ impl App {
&& self.current_displayed_thread_id() == Some(source)
&& self.document_preview_available(tui, app_server);
match path {
Ok(path) => Box::pin(self.open_resolved_document(tui, app_server, source, original_path, path, focus)).await?,
Ok(path) => Box::pin(self.open_resolved_document(tui, app_server, source, original_path, path, location, focus)).await?,
Err(error) if focus => self.chat_widget.add_error_message(format!("Could not open file: {error}")),
Err(_) => {}
}
+22 -13
View File
@@ -302,6 +302,15 @@ impl App {
.mouse
.filter(|mouse| self.pane_resize.is_none() && !tui.shortcut_hud_contains(*mouse))
.map(|mouse| (mouse.column, mouse.row).into());
let tui_link_position = pointer.filter(|_| {
tui.link_hover.mouse.is_some_and(|mouse| {
mouse.modifiers.is_empty()
|| mouse.modifiers.intersects(
crossterm::event::KeyModifiers::CONTROL
| crossterm::event::KeyModifiers::SUPER,
)
})
});
let sidebar_parent = self.sidebar_parent();
let sidebar_motion =
MotionMode::from_animations_enabled(self.local_settings.tui.animations);
@@ -342,6 +351,10 @@ impl App {
.or(self.app_server_backend_id)
.map(|owner| self.backend_registry.thread_label_style(owner))
.unwrap_or_default();
let link_pointer =
tui_link_position.filter(|_| self.chat_widget.no_modal_or_popup_active());
self.transcript_view
.paint_document_links(frame.buffer, link_pointer);
match &self.conversation_frame.sidebar {
Some(sidebar::SidebarLayout::Chat(panes)) => {
if let Some(companion) = self.side_companions.get_mut(&panes.passive_thread) {
@@ -1252,19 +1265,15 @@ impl App {
}
}
} else if let ViewAction::OpenLink(url) = action {
if url.starts_with("file://")
|| crate::terminal_hyperlinks::web_destination(&url).is_some()
{
self.open_url_in_browser(url);
} else if self.transcript_view.document_links
&& let Some(source) = self.current_displayed_thread_id()
{
self.app_event_tx.send(AppEvent::OpenSidebarDocument {
backend_id: app_server.backend_id(),
source,
path: codex_app_server_client::AppServerPath::from_app_server(url),
});
}
self.open_url_in_browser(url);
} else if let ViewAction::OpenDocument(link) = action
&& let Some(source) = self.current_displayed_thread_id()
{
self.app_event_tx.send(AppEvent::OpenSidebarDocument {
backend_id: app_server.backend_id(),
source,
link,
});
}
}
if was_select_mode && !self.transcript_view.is_select_mode() {
@@ -1554,6 +1554,7 @@ impl App {
self.drain_outgoing_thread_events().await;
}
self.store_active_thread_receiver().await;
self.refresh_transcript_document_links();
self.reset_transcript_state_after_clear();
tui.clear_pending_history_lines();
let presentation = match presentation {
+10 -8
View File
@@ -484,14 +484,16 @@ impl SidePaneLayout {
frames.schedule_frame_in(Duration::from_secs(1));
}
}
companion.view.render_parked(
transcript,
frame.buffer,
&companion.cells,
companion.display.active.as_deref(),
&companion.display.auxiliary,
collapse_turn_details,
);
crate::markdown_render::preferences::with_visible_local_paths(|| {
companion.view.render_parked(
transcript,
frame.buffer,
&companion.cells,
companion.display.active.as_deref(),
&companion.display.auxiliary,
collapse_turn_details,
);
});
frame
.image_placements
.extend(companion.view.image_placements());
+196 -21
View File
@@ -6,6 +6,8 @@ use super::*;
use crate::key_hint::KeyBinding;
use crate::keymap::KeymapContext;
use crate::keymap::RuntimeKeymap;
use crate::markdown_render::FileLink;
use crate::markdown_render::SourceLocation;
use crate::motion::MotionMode;
use crate::sidebar_tab_strip::SidebarTab;
use crate::terminal_hyperlinks::HyperlinkLine;
@@ -18,10 +20,12 @@ use codex_utils_path_uri::PathUri;
use ratatui::buffer::Buffer;
use ratatui::layout::Position;
use ratatui::widgets::Widget;
use unicode_segmentation::UnicodeSegmentation;
#[derive(Debug)]
struct FileCell {
source: String,
language: Option<String>,
}
impl HistoryCell for FileCell {
@@ -38,6 +42,12 @@ impl HistoryCell for FileCell {
}
fn display_hyperlink_lines(&self, width: u16) -> Vec<HyperlinkLine> {
if let Some(language) = &self.language {
return crate::render::highlight::highlight_code_to_lines(&self.source, language)
.into_iter()
.map(HyperlinkLine::new)
.collect();
}
crate::markdown_render::render_markdown_lines_with_width_cwd_and_hidden_link_destinations(
&self.source,
Some(width.into()),
@@ -56,6 +66,7 @@ pub(super) struct Document {
pub(super) path: PathUri,
pub(super) backend: crate::backend_id::BackendId,
link: Option<usize>,
location: Option<SourceLocation>,
state: State,
}
@@ -65,6 +76,8 @@ enum State {
Ready {
view: Box<TranscriptView>,
cells: [Arc<dyn HistoryCell>; 1],
line_starts: Vec<usize>,
target: Option<(usize, usize)>,
},
}
@@ -83,8 +96,9 @@ impl Document {
pub(super) fn allows_tab_shortcut(&self, key: KeyEvent) -> bool {
match &self.state {
State::Ready { view, .. } => {
!view.has_active_interaction() && (key.code != KeyCode::Esc || self.link.is_none())
State::Ready { view, target, .. } => {
!view.has_active_interaction()
&& (key.code != KeyCode::Esc || (self.link.is_none() && target.is_none()))
}
_ => true,
}
@@ -105,6 +119,10 @@ impl Document {
}
}
fn title(&self) -> String {
self.path.basename().unwrap_or_default()
}
pub(super) fn connection_replaced(&mut self) {
if matches!(self.state, State::Loading(_)) {
self.state = State::Failed("Connection changed. Reopen this file to try again.".into());
@@ -114,17 +132,92 @@ impl Document {
pub(super) fn loaded(&mut self, result: Result<String, String>) {
self.state = match result {
Ok(source) => {
let cells: [Arc<dyn HistoryCell>; 1] = [Arc::new(FileCell { source })];
let title = self.title();
let code =
self.location.is_some() || !crate::markdown_render::is_markdown_file(&title);
const MAX_SOURCE_BYTES: usize = 1024 * 1024;
if code && source.len() > MAX_SOURCE_BYTES {
self.state = State::Failed("Source preview limit is 1 MiB".into());
return;
}
// Like the transcript layout, count one LF per logical line, including CRLF input.
let mut start = 0;
let line_starts = if code {
source
.lines()
.map(|line| {
let offset = start;
start += line.len() + 1;
offset
})
.collect::<Vec<_>>()
} else {
Vec::new()
};
const MAX_SOURCE_LINES: usize = 10_000;
if line_starts.len() > MAX_SOURCE_LINES {
self.state =
State::Failed(format!("Source preview limit is {MAX_SOURCE_LINES} lines"));
return;
}
let language = code.then(|| {
title
.rsplit_once('.')
.map_or(title.as_str(), |(_, ext)| ext)
.to_owned()
});
let target = self
.location
.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();
view.document_links = true;
view.show_follow_control = false;
view.jump_to_beginning(&cells);
State::Ready { view, cells }
view.jump_to_offset(&cells, target.map_or(0, |(_, offset)| offset));
State::Ready {
view,
cells,
line_starts,
target,
}
}
Err(error) => State::Failed(error),
};
}
fn go_to(&mut self, location: Option<SourceLocation>) {
let was_located = self.location.is_some();
let restore_markdown = location.is_none()
&& was_located
&& crate::markdown_render::is_markdown_file(&self.title());
self.location = location;
self.link = None;
let State::Ready {
view,
cells,
line_starts,
target,
} = &mut self.state
else {
return;
};
let Some(source) = cells[0].copy_source() else {
return;
};
if restore_markdown || (location.is_some() && line_starts.is_empty()) {
// Coordinate links show source. Plain Markdown links restore rendering.
let source = source.to_owned();
self.loaded(Ok(source));
} else {
*target = location.and_then(|location| source_target(source, line_starts, location));
if let Some((_, offset)) = target {
view.cancel_search();
view.end_selection(cells);
view.jump_to_offset(cells, *offset);
}
}
}
pub(super) fn paint(
&mut self,
area: Rect,
@@ -151,7 +244,12 @@ impl Document {
.wrap(ratatui::widgets::Wrap { trim: false })
.render(body, buf);
}
State::Ready { view, cells } => {
State::Ready {
view,
cells,
line_starts,
target,
} => {
view.set_keymap_bindings(keymap);
if view.tick_selection(cells) {
frames.schedule_frame_in(std::time::Duration::from_millis(45));
@@ -177,7 +275,14 @@ impl Document {
.map(|hint| {
crate::footer_hint::shortcut(&hint.display_label(), "select")
}),
Some(crate::footer_hint::shortcut("Esc", "close")),
Some(crate::footer_hint::shortcut(
"Esc",
if target.is_some() {
"clear highlight"
} else {
"close"
},
)),
]
.into_iter()
.flatten(),
@@ -203,7 +308,13 @@ impl Document {
if content.width > 2 {
viewport.width -= 1;
}
view.render(viewport, buf, cells);
view.render_document(
viewport,
buf,
cells,
line_starts,
target.filter(|_| !view.has_active_interaction()),
);
if let Some(index) = self.link {
view.paint_document_link(cells, index, buf);
}
@@ -236,6 +347,29 @@ impl Document {
}
}
fn source_target(
source: &str,
starts: &[usize],
location: SourceLocation,
) -> Option<(usize, usize)> {
let index = (location.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)
.map_or(line.len(), |(byte, _)| byte);
let column = if column == line.len() {
column
} else {
line.grapheme_indices(/*is_extended*/ true)
.take_while(|(byte, _)| *byte <= column)
.last()
.map_or(0, |(byte, _)| byte)
};
Some((index + 1, start + column))
}
impl App {
pub(super) fn cancel_hidden_sidebar_primary(&mut self, tui: &tui::Tui) {
let parent = self.sidebar_parent();
@@ -267,16 +401,27 @@ impl App {
self.conversation_focus_available(tui)
&& self.sidebar_chooser_available()
&& server.thread_params_mode() != crate::app_server_session::ThreadParamsMode::Cloud
&& server.app_server_platform_family() != Some("windows")
&& (server.uses_remote_workspace() || !cfg!(windows))
&& self.current_displayed_thread_id().is_some()
}
pub(super) fn refresh_transcript_document_links(&self) {
crate::markdown_render::preferences::set_document_links(
self.local_settings.workspace_enabled(&self.config)
&& self.app_server_target.thread_params_mode() != crate::ThreadParamsMode::Cloud,
);
}
pub(super) async fn open_document(
&mut self,
tui: &mut tui::Tui,
server: &mut AppServerSession,
source: ThreadId,
path: AppServerPath,
link: FileLink,
) -> Result<()> {
let location = link.location;
let path = AppServerPath::from_app_server(link.path);
let Some(parent) = self.sidebar_parent() else {
return Ok(());
};
@@ -297,12 +442,17 @@ impl App {
request,
original_path: path,
path: resolved,
location,
});
});
tui.frame_requester().schedule_frame();
Ok(())
}
#[allow(
clippy::too_many_arguments,
reason = "The safe read needs both paths, and the caller supplies navigation and focus."
)]
pub(super) async fn open_resolved_document(
&mut self,
tui: &mut tui::Tui,
@@ -310,6 +460,7 @@ impl App {
source: ThreadId,
original_path: AppServerPath,
path: PathUri,
location: Option<SourceLocation>,
focus: bool,
) -> Result<()> {
let Some(parent) = self.sidebar_parent() else {
@@ -327,6 +478,9 @@ impl App {
return Ok(());
}
if !failed {
if let Some(doc) = self.sidebar_mut().documents.get_mut(&id) {
doc.go_to(location);
}
return self
.activate_sidebar_tab(tui, server, SidebarTab::Document(id))
.await;
@@ -342,6 +496,7 @@ impl App {
path: path.clone(),
backend: backend_id,
link: None,
location,
state: State::Loading(Instant::now()),
},
);
@@ -387,7 +542,7 @@ impl App {
&& mouse.kind == MouseEventKind::Moved
{
if let Some(Document {
state: State::Ready { view, cells },
state: State::Ready { view, cells, .. },
..
}) = pane.documents.get_mut(&id)
&& view.handle_mouse(*mouse, cells).is_some()
@@ -411,12 +566,21 @@ impl App {
if key.kind != KeyEventKind::Press && (escape || key.code == KeyCode::Enter) {
return true;
}
if let State::Ready { view, cells } = &mut doc.state {
if let State::Ready {
view,
cells,
target,
..
} = &mut doc.state
{
if escape && view.has_active_interaction() && !view.is_select_mode() {
view.cancel_search();
view.end_selection(cells);
None
} else if escape && doc.link.take().is_some() {
} else if escape
&& (doc.link.take().is_some()
|| (!view.has_active_interaction() && target.take().is_some()))
{
None
} else if !view.is_search_editing()
&& (self.keymap.app.find_transcript.is_pressed(*key)
@@ -446,7 +610,7 @@ impl App {
} else if crate::key_hint::plain(KeyCode::Enter).is_press(*key)
&& let Some(index) = doc.link.take()
{
view.document_link(cells, index).map(ViewAction::OpenLink)
view.document_link(cells, index).map(ViewAction::from)
} else {
doc.link = None;
if view.has_active_interaction() {
@@ -493,7 +657,7 @@ impl App {
return false;
}
if let Some(Document {
state: State::Ready { view, cells },
state: State::Ready { view, cells, .. },
link,
..
}) = pane.documents.get_mut(&id)
@@ -504,7 +668,14 @@ impl App {
view.copy_on_select_clear_selection =
self.transcript_view.copy_on_select_clear_selection;
view.primary_selection = self.transcript_view.primary_selection;
view.handle_mouse(*mouse, cells)
let mut mouse = *mouse;
if matches!(
mouse.kind,
MouseEventKind::ScrollUp | MouseEventKind::ScrollDown
) {
mouse.column = mouse.column.max(view.remaining_area().x);
}
view.handle_mouse(mouse, cells)
} else {
None
}
@@ -512,25 +683,24 @@ impl App {
_ => return false,
};
match action {
Some(ViewAction::OpenLink(url)) => {
if let Some(url) = crate::terminal_hyperlinks::web_destination(&url) {
self.open_url_in_browser(url);
} else if let Some(doc) = pane.documents.get(&id)
Some(ViewAction::OpenDocument(link)) => {
if let Some(doc) = pane.documents.get(&id)
&& let Some(parent) = doc.path.parent()
{
let result = match LegacyAppPathString::from_string(url)
let result = match LegacyAppPathString::from_string(link.path)
.resolve_against(&parent, /*user_home_dir*/ None)
{
Ok(path) if !path.to_url().has_host() => {
let source = doc.source;
let original_path =
AppServerPath::from_app_server(path.inferred_native_path_string());
let source = doc.source;
self.open_resolved_document(
tui,
server,
source,
original_path,
path,
link.location,
/*focus*/ true,
)
.await
@@ -543,6 +713,11 @@ impl App {
}
}
}
Some(ViewAction::OpenLink(url)) => {
if let Some(url) = crate::terminal_hyperlinks::web_destination(&url) {
self.open_url_in_browser(url);
}
}
Some(action) => {
if let Some((view, cells)) = pane.documents.get_mut(&id).and_then(Document::reader)
&& let Some((count, result)) = view.copy_action(
+131 -26
View File
@@ -54,21 +54,24 @@ async fn document_preview_scenario() -> Result<()> {
size,
Default::default(),
);
let screen = side_frame(&mut app, &mut tui, size)?;
let (column, row) = screen
.lines()
.enumerate()
.find_map(|(row, line)| {
let byte = line.find("guide.md")?;
Some((line[..byte].width() as u16, row as u16))
})
.expect("the local link's path is visible");
let press = MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column,
row,
modifiers: KeyModifiers::NONE,
let link_press = |screen: &str, label: &str| {
let (column, row) = screen
.lines()
.enumerate()
.find_map(|(row, line)| {
let byte = line.find(label)?;
Some((line[..byte].width() as u16, row as u16))
})
.expect("the local link is visible");
MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column,
row,
modifiers: KeyModifiers::NONE,
}
};
let screen = side_frame(&mut app, &mut tui, size)?;
let press = link_press(&screen, "guide.md");
let modified_press = MouseEvent {
modifiers: KeyModifiers::CONTROL,
..press
@@ -85,11 +88,10 @@ async fn document_preview_scenario() -> Result<()> {
app.local_settings.tui.keymap.global.select_transcript =
Some(KeybindingsSpec::One(KeybindingSpec("ctrl-x [".into())));
enable_side_retention(&mut app)?;
crate::markdown_render::preferences::set_document_links(/*enabled*/ true);
let enabled = side_frame(&mut app, &mut tui, size)?;
assert_eq!(
enabled.lines().nth(row as usize),
screen.lines().nth(row as usize)
);
assert!(!enabled.contains("guide.md"));
let press = link_press(&enabled, "Guide");
let release = MouseEvent {
kind: MouseEventKind::Up(MouseButton::Left),
..press
@@ -128,7 +130,10 @@ async fn document_preview_scenario() -> Result<()> {
"Middle.\n\n".repeat(12)
),
)?;
let path = AppServerPath::from_app_server("guide.md");
let path = FileLink {
path: "guide.md".into(),
location: None,
};
app.open_document(&mut tui, &mut server, parent, path.clone())
.await?;
Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?;
@@ -327,7 +332,7 @@ async fn document_preview_scenario() -> Result<()> {
insta::assert_snapshot!(highlighted, @"Next");
for key in [KeyCode::Home, KeyCode::Enter] {
assert!(
app.handle_document_input(&mut tui, &mut server, &TuiEvent::Key(key.into()))
Box::pin(app.handle_document_input(&mut tui, &mut server, &TuiEvent::Key(key.into())))
.await
);
}
@@ -337,8 +342,12 @@ async fn document_preview_scenario() -> Result<()> {
view.jump_to_latest();
side_frame(&mut app, &mut tui, size)?;
assert!(
app.handle_document_input(&mut tui, &mut server, &TuiEvent::Key(KeyCode::Tab.into()))
.await
Box::pin(app.handle_document_input(
&mut tui,
&mut server,
&TuiEvent::Key(KeyCode::Tab.into())
))
.await
);
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Enter.into())))
.await?;
@@ -379,7 +388,10 @@ async fn document_preview_scenario() -> Result<()> {
&mut tui,
&mut server,
parent,
AppServerPath::from_app_server("closed.md"),
FileLink {
path: "closed.md".into(),
location: None,
},
)
.await?;
Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?;
@@ -397,11 +409,98 @@ async fn document_preview_scenario() -> Result<()> {
.await?;
Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(false).await)).await?;
assert_eq!(app.sidebar().unwrap().documents.len(), 1);
std::fs::write(
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 })] {
app.open_document(
&mut tui,
&mut server,
parent,
FileLink {
path: "./main.rs".into(),
location,
},
)
.await?;
Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?;
if location.is_none() {
Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(false).await))
.await?;
let Some(SidebarContent::Document(id)) = app.sidebar().unwrap().visible_content()
else {
panic!("the source tab should be visible");
};
app.sidebar_mut()
.documents
.get_mut(&id)
.unwrap()
.reader()
.unwrap()
.0
.begin_search();
}
}
let source = side_frame(&mut app, &mut tui, Size::new(200, 15))?;
let preview = source
.lines()
.filter_map(|line| line.rsplit_once('│'))
.map(|(_, sidebar)| sidebar.trim())
.filter(|line| !line.is_empty())
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(preview, @"
guide.md × main.rs × +
3 let value = 3; ↑
↑/↓ read · f3 find · Tab link · f8 select · Esc clear highlight
");
let panel = app.conversation_frame.panel_area().unwrap();
let buffer = tui.terminal.previous_buffer();
let target_cell = &buffer[(panel.x + 7, panel.y + 1)];
let adjacent = &buffer[(panel.x + 8, panel.y + 1)];
assert_eq!(target_cell.symbol(), "v");
assert_ne!(
target_cell
.modifier
.contains(ratatui::style::Modifier::REVERSED),
adjacent
.modifier
.contains(ratatui::style::Modifier::REVERSED),
);
assert_eq!(app.sidebar().unwrap().documents.len(), 2);
let Some(SidebarContent::Document(id)) = app.sidebar().unwrap().visible_content() else {
panic!("the source tab should be visible");
};
let (view, cells) = app
.sidebar_mut()
.documents
.get_mut(&id)
.unwrap()
.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 {
panic!("the source tab should be ready");
};
assert!(!view.is_select_mode());
assert!(target.is_some());
assert!(!view.has_active_interaction());
for remaining in [2, 1] {
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into())))
.await?;
assert_eq!(app.sidebar().unwrap().documents.len(), remaining);
}
app.open_document(
&mut tui,
&mut server,
parent,
AppServerPath::from_app_server("notes.md"),
FileLink {
path: "notes.md".into(),
location: None,
},
)
.await?;
app.overlay = Some(crate::pager_overlay::Overlay::Transcript(
@@ -439,7 +538,10 @@ async fn document_preview_scenario() -> Result<()> {
&mut tui,
&mut server,
parent,
AppServerPath::from_app_server(format!("{directory}/shared/guide.md")),
FileLink {
path: format!("{directory}/shared/guide.md"),
location: None,
},
))
.await?;
Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?;
@@ -478,7 +580,10 @@ async fn document_preview_scenario() -> Result<()> {
&mut tui,
&mut server,
parent,
AppServerPath::from_app_server(format!("{directory}/guide.md")),
FileLink {
path: format!("{directory}/guide.md"),
location: None,
},
))
.await?;
Box::pin(app.handle_event(&mut tui, &mut server, next_document_event(true).await)).await?;
+2 -1
View File
@@ -525,7 +525,7 @@ pub(crate) enum AppEvent {
OpenSidebarDocument {
backend_id: crate::backend_id::BackendId,
source: ThreadId,
path: codex_app_server_client::AppServerPath,
link: crate::markdown_render::FileLink,
},
SidebarDocumentResolved {
backend_id: crate::backend_id::BackendId,
@@ -534,6 +534,7 @@ pub(crate) enum AppEvent {
request: uuid::Uuid,
original_path: codex_app_server_client::AppServerPath,
path: std::result::Result<codex_utils_path_uri::PathUri, String>,
location: Option<crate::markdown_render::SourceLocation>,
},
SidebarDocumentLoaded {
backend_id: crate::backend_id::BackendId,
@@ -18,6 +18,7 @@ pub(super) struct MarkdownRenderCacheKey {
pub(super) terminal_fg: Option<(u8, u8, u8)>,
pub(super) terminal_bg: Option<(u8, u8, u8)>,
pub(super) color_level: crate::terminal_palette::StdoutColorLevel,
pub(super) document_links: bool,
}
impl MarkdownRenderCache {
@@ -38,6 +39,7 @@ impl MarkdownRenderCache {
terminal_fg: crate::terminal_palette::default_fg(),
terminal_bg: crate::terminal_palette::default_bg(),
color_level: crate::terminal_palette::stdout_color_level(),
document_links: crate::markdown_render::preferences::document_links_enabled(),
};
let mut cached = self.cached.lock().unwrap_or_else(PoisonError::into_inner);
if let Some((cached_key, lines)) = cached.as_ref()
+4
View File
@@ -2105,6 +2105,10 @@ async fn run_ratatui_app(
let local_settings = crate::local_settings::LocalSettings::for_tui(&config, &tui);
crate::markdown_render::preferences::init(local_settings.tui.rendering);
crate::markdown_render::preferences::set_document_links(
local_settings.workspace_enabled(&config)
&& app_server_target.thread_params_mode() != ThreadParamsMode::Cloud,
);
// Configure syntax highlighting theme from the final config — onboarding
// and resume/fork can both reload config with a different tui_theme, so
// this must happen after the last possible reload.
+2 -2
View File
@@ -140,7 +140,7 @@ pub(crate) fn render_markdown_agent_with_list_spacing(
};
let is_hidden_link_destination = |destination: &str| {
rewritten.trusted_file_links.contains_key(destination)
|| crate::markdown_render::hide_web_link_destination(destination)
|| crate::markdown_render::preferences::hide_transcript_destination(destination)
};
let mut lines = crate::markdown_render::render_with_copy_sources(
&normalized,
@@ -175,7 +175,7 @@ pub(crate) fn render_streaming_markdown_agent_with_links_and_cwd(
&normalized,
width,
cwd,
&crate::markdown_render::hide_web_link_destination,
&crate::markdown_render::preferences::hide_transcript_destination,
list_spacing,
);
if normalized != markdown_source {
+7 -4
View File
@@ -81,6 +81,9 @@ use unicode_segmentation::UnicodeSegmentation;
mod inline_directives;
mod list_spacing;
mod local_links;
pub(crate) use local_links::FileLink;
pub(crate) use local_links::SourceLocation;
pub(crate) use local_links::is_markdown_file;
mod math;
mod mermaid;
pub(crate) mod preferences;
@@ -2411,12 +2414,12 @@ impl<'a, 'policy> Writer<'a, 'policy> {
}
}
fn label_document_path(&self) -> Option<String> {
fn label_document_path(&self) -> Option<FileLink> {
let link = self.link.as_ref().filter(|link| link.style_label)?;
local_links::sidebar_file_link(&link.destination)
}
fn document_label_span(&self, span: Span<'static>, path: String) -> HyperlinkLine {
fn document_label_span(&self, span: Span<'static>, path: FileLink) -> HyperlinkLine {
let width = span_width(&span);
let mut line = HyperlinkLine::new(Line::from(span));
let mut link = TerminalHyperlink::document(0..width, path);
@@ -2427,12 +2430,12 @@ impl<'a, 'policy> Writer<'a, 'policy> {
fn push_link_target(&mut self, span: Span<'static>, destination: &str, source: usize) {
let mut target = HyperlinkLine::default();
if let Some(path) = local_links::sidebar_file_link(destination) {
if let Some(link) = local_links::sidebar_file_link(destination) {
let width = span_width(&span);
target.line.push_span(span);
target
.hyperlinks
.push(TerminalHyperlink::document(0..width, path));
.push(TerminalHyperlink::document(0..width, link));
} else {
target.push_span(span, Some(destination));
}
@@ -27,24 +27,53 @@ static HASH_LOCATION_SUFFIX_RE: LazyLock<Regex> =
Err(error) => panic!("invalid hash location regex: {error}"),
});
pub(crate) fn sidebar_file_link(destination: &str) -> Option<String> {
if destination.len() > 8192 || destination.contains(['#', '?']) {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct SourceLocation {
pub(crate) line: usize,
pub(crate) column: usize,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct FileLink {
pub(crate) path: String,
pub(crate) location: Option<SourceLocation>,
}
pub(crate) fn is_markdown_file(path: &str) -> bool {
path.rsplit_once('.').is_some_and(|(_, ext)| {
ext.eq_ignore_ascii_case("md") || ext.eq_ignore_ascii_case("markdown")
})
}
pub(crate) fn sidebar_file_link(destination: &str) -> Option<FileLink> {
if destination.len() > 8192 || destination.contains('?') {
return None;
}
if destination.starts_with("file://") && Url::parse(destination).ok()?.has_host() {
return None;
}
let (path, location) = parse_local_link_target(destination)?;
let extension = path.rsplit_once('.')?.1;
(location.is_none()
&& (extension.eq_ignore_ascii_case("md") || extension.eq_ignore_ascii_case("markdown"))
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
};
(!path.is_empty()
&& !path.ends_with('/')
&& path.len() <= 4096
&& !path.starts_with('~')
&& !path.starts_with("//")
&& !path.chars().any(char::is_control)
&& (is_absolute_local_link_path(&path) || Url::parse(&path).is_err())
&& (is_local_path_like_link(destination) || Url::parse(destination).is_err()))
.then_some(path)
&& (is_absolute_local_link_path(&path) || Url::parse(&path).is_err()))
.then_some(FileLink { path, location })
}
pub(super) fn is_local_path_like_link(dest_url: &str) -> bool {
@@ -1,5 +1,8 @@
//! Tests for local-link parsing and root-preserving separator normalization.
use super::FileLink;
use super::SourceLocation;
use super::sidebar_file_link;
use super::trim_trailing_local_path_separator;
use pretty_assertions::assert_eq;
@@ -11,3 +14,27 @@ fn trailing_separator_trimming_preserves_local_roots() {
["/", "//", "C:/", "dir", "//server/share", "C:/dir"]
);
}
#[test]
fn sidebar_keeps_line_and_column_for_extensionless_source_links() {
assert_eq!(
sidebar_file_link("./Makefile#L12C3"),
Some(FileLink {
path: "./Makefile".into(),
location: Some(SourceLocation {
line: 12,
column: 3
}),
}),
);
for path in ["Makefile", "build/Makefile"] {
assert_eq!(
sidebar_file_link(path),
Some(FileLink {
path: path.into(),
location: None,
}),
);
}
assert_eq!(sidebar_file_link("https://example.org/Makefile#L12"), None);
}
@@ -41,3 +41,52 @@ pub(crate) fn current() -> TuiRendering {
#[cfg(test)]
#[path = "preferences_tests.rs"]
mod tests;
// Shared by the streaming and replay renderers for this TUI session.
#[cfg(not(test))]
static DOCUMENT_LINKS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
#[cfg(test)]
thread_local! {
static DOCUMENT_LINKS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) fn set_document_links(enabled: bool) {
#[cfg(not(test))]
DOCUMENT_LINKS.store(enabled, std::sync::atomic::Ordering::Relaxed);
#[cfg(test)]
DOCUMENT_LINKS.set(enabled);
}
thread_local! {
static SHOW_LOCAL_PATHS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) fn with_visible_local_paths<T>(render: impl FnOnce() -> T) -> T {
struct Restore<'a>(&'a std::cell::Cell<bool>, bool);
impl Drop for Restore<'_> {
fn drop(&mut self) {
self.0.set(self.1);
}
}
SHOW_LOCAL_PATHS.with(|show| {
let _restore = Restore(show, show.replace(true));
render()
})
}
pub(crate) fn hide_transcript_destination(destination: &str) -> bool {
if document_links_enabled() {
super::hide_reader_link_destination(destination)
} else {
super::hide_web_link_destination(destination)
}
}
pub(crate) fn document_links_enabled() -> bool {
#[cfg(not(test))]
let documents = DOCUMENT_LINKS.load(std::sync::atomic::Ordering::Relaxed);
#[cfg(test)]
let documents = DOCUMENT_LINKS.get();
documents && !SHOW_LOCAL_PATHS.get()
}
@@ -201,6 +201,7 @@ fn empty_reader_local_links_keep_a_visible_destination() {
for markdown in [
"[](empty.md)",
"[](./empty.md)",
"[](src/empty.md#L42)",
"[ ](./empty.md)",
"[\u{200d}](./empty.md)",
] {
+17 -1
View File
@@ -138,7 +138,23 @@ fn incremental_file_citations_preserve_metadata_unicode_and_markdown() {
render.lines
});
assert_debug_snapshot!("incremental_file_citations", rendered_cases);
assert_eq!(
rendered_cases.each_ref().map(|lines| lines
.iter()
.flat_map(|line| &line.hyperlinks)
.map(|link| link.reader_destination(/*documents*/ true))
.collect::<Vec<_>>()),
["Quarterly Report.xlsx", "Résumé *final* ✨.xlsx"].map(|name| vec![Some(
crate::terminal_hyperlinks::ReaderLink::Document(crate::markdown_render::FileLink {
path: cwd.join(name).to_string_lossy().replace('\\', "/"),
location: None,
})
)])
);
assert_debug_snapshot!(
"incremental_file_citations",
rendered_cases.map(visible_lines)
);
}
#[test]
@@ -1,62 +1,32 @@
---
source: tui/src/streaming/render_tests.rs
expression: rendered_cases
expression: rendered_cases.map(visible_lines)
---
[
[
HyperlinkLine {
line: Line::from_iter([
Span::from("# ").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
Span::from("Output").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
]),
hyperlinks: [],
},
HyperlinkLine {
line: Line::default(),
hyperlinks: [],
},
HyperlinkLine {
line: Line::from_iter([
Span::from("• ").fg(Color::Rgb(148, 226, 213)),
Span::from("Quarterly Report.xlsx").fg(Color::Rgb(166, 227, 161)),
]),
hyperlinks: [],
},
HyperlinkLine {
line: Line::default(),
hyperlinks: [],
},
HyperlinkLine {
line: Line::from("Continue."),
hyperlinks: [],
},
Line::from_iter([
Span::from("# ").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
Span::from("Output").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
]),
Line::default(),
Line::from_iter([
Span::from("• ").fg(Color::Rgb(148, 226, 213)),
Span::from("Quarterly Report.xlsx").fg(Color::Rgb(166, 227, 161)),
]),
Line::default(),
Line::from("Continue."),
],
[
HyperlinkLine {
line: Line::from_iter([
Span::from("# ").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
Span::from("Output").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
]),
hyperlinks: [],
},
HyperlinkLine {
line: Line::default(),
hyperlinks: [],
},
HyperlinkLine {
line: Line::from_iter([
Span::from("• ").fg(Color::Rgb(148, 226, 213)),
Span::from("Résumé *final* ✨.xlsx").fg(Color::Rgb(166, 227, 161)),
]),
hyperlinks: [],
},
HyperlinkLine {
line: Line::default(),
hyperlinks: [],
},
HyperlinkLine {
line: Line::from("Continue."),
hyperlinks: [],
},
Line::from_iter([
Span::from("# ").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
Span::from("Output").fg(Color::Rgb(243, 139, 168)).bold().underlined(),
]),
Line::default(),
Line::from_iter([
Span::from("• ").fg(Color::Rgb(148, 226, 213)),
Span::from("Résumé *final* ✨.xlsx").fg(Color::Rgb(166, 227, 161)),
]),
Line::default(),
Line::from("Continue."),
],
]
+30 -10
View File
@@ -33,6 +33,8 @@ use unicode_segmentation::UnicodeSegmentation;
use url::Url;
use crate::line_truncation::line_width;
use crate::markdown_render::FileLink;
use crate::markdown_render::SourceLocation;
use crate::render::line_utils::line_to_borrowed;
use crate::render::line_utils::line_to_static;
use crate::width::display_width;
@@ -76,7 +78,22 @@ enum DestinationKind {
/// A generated visualization, validated workspace artifact, or locally viewed image.
TrustedFile,
/// A local document target used only by an enabled workspace transcript.
Document,
Document(Option<SourceLocation>),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum ReaderLink {
External(String),
Document(FileLink),
}
impl ReaderLink {
pub(crate) fn into_destination(self) -> String {
match self {
Self::External(url) => url,
Self::Document(link) => link.path,
}
}
}
/// An existing, inert source file proven to remain inside its session workspace.
@@ -185,24 +202,27 @@ impl TerminalHyperlink {
}
}
pub(crate) fn document(columns: Range<usize>, path: String) -> Self {
pub(crate) fn document(columns: Range<usize>, link: FileLink) -> Self {
Self {
columns,
destination: path,
destination_kind: DestinationKind::Document,
destination: link.path,
destination_kind: DestinationKind::Document(link.location),
markdown_source: None,
}
}
pub(crate) fn is_document(&self) -> bool {
self.destination_kind == DestinationKind::Document
matches!(self.destination_kind, DestinationKind::Document(_))
}
pub(crate) fn reader_destination(&self, documents: bool) -> Option<String> {
if documents && self.is_document() {
Some(self.destination.clone())
pub(crate) fn reader_destination(&self, documents: bool) -> Option<ReaderLink> {
if documents && let DestinationKind::Document(location) = self.destination_kind {
Some(ReaderLink::Document(FileLink {
path: self.destination.clone(),
location,
}))
} else {
self.terminal_destination()
self.terminal_destination().map(ReaderLink::External)
}
}
@@ -217,7 +237,7 @@ impl TerminalHyperlink {
pub(crate) fn terminal_destination(&self) -> Option<String> {
match self.destination_kind {
DestinationKind::Document => None,
DestinationKind::Document(_) => None,
DestinationKind::Web => web_destination(&self.destination),
DestinationKind::TrustedFile => trusted_file_destination(&self.destination),
}
+54 -17
View File
@@ -10,6 +10,7 @@ mod bookmark;
mod composer_gap;
mod copy_mode;
mod disclosure;
mod document;
mod follow_control;
mod footer;
mod input;
@@ -31,8 +32,10 @@ use crate::history_cell::HistoryCell;
use crate::history_cell::HistoryRenderMode;
use crate::pager_overlay::TranscriptHistoryState;
use crate::terminal_hyperlinks::HyperlinkLine;
use crate::terminal_hyperlinks::TerminalHyperlink;
use crate::tui::SelectionCopy;
use ratatui::buffer::Buffer;
use ratatui::layout::Position as ScreenPosition;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
use ratatui::text::Line;
@@ -345,24 +348,58 @@ impl TranscriptView {
self.render_search(buf);
}
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;
pub(crate) fn has_document_link_at(&self, pointer: ScreenPosition) -> bool {
self.document_links
&& self
.raw_link_at(pointer)
.is_some_and(|(_, link)| link.is_document())
}
fn raw_link_at(&self, pointer: ScreenPosition) -> Option<(&VisibleRow, &TerminalHyperlink)> {
if !self.area.contains(pointer) {
return None;
}
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());
let row = self.visible.get(usize::from(pointer.y - self.area.y))?;
let link = row.layout.raw_link_at(row.row, pointer.x - self.area.x)?;
Some((row, link))
}
pub(crate) fn paint_document_links(&self, buf: &mut Buffer, pointer: Option<ScreenPosition>) {
let Some((hit_row, hit_link)) = pointer
.filter(|_| self.document_links && !self.has_active_interaction())
.and_then(|pointer| self.raw_link_at(pointer))
.filter(|(_, link)| link.is_document())
else {
return;
};
for (y, row) in (self.area.top()..self.area.bottom()).zip(&self.visible) {
if row.key != hit_row.key {
continue;
}
let Some((inset, links)) = row.layout.row_links(row.row) else {
continue;
};
for link in links.iter().filter(|link| link.is_document()) {
if !(std::ptr::eq(hit_link, link) && hit_row.row == row.row
|| hit_link.markdown_source.is_some()
&& hit_link.markdown_source == link.markdown_source
&& hit_link.destination == link.destination)
{
continue;
}
let columns = (inset + link.columns.start)
..(inset + link.columns.end).min(usize::from(self.area.width));
if !columns.is_empty() {
buf.set_style(
Rect::new(
self.area.x + columns.start as u16,
y,
columns.len() as u16,
1,
),
ratatui::style::Style::default().bold(),
);
}
}
}
}
@@ -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<_>>()
};