Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

file_finder: Support line range queries with path:start-end syntax (#53958)

Xiaobo Liu6aaea4d10afd
diff --git a/Cargo.lock b/Cargo.lock
index ea316675240..e1c74513434 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6341,6 +6341,7 @@ dependencies = [
"fuzzy",
"fuzzy_nucleo",
"gpui",
+ "language",
"menu",
"open_path_prompt",
"picker",
diff --git a/crates/file_finder/Cargo.toml b/crates/file_finder/Cargo.toml
index f7f09956c15..b66d77da25a 100644
--- a/crates/file_finder/Cargo.toml
+++ b/crates/file_finder/Cargo.toml
@@ -23,6 +23,7 @@ futures.workspace = true
fuzzy.workspace = true
fuzzy_nucleo.workspace = true
gpui.workspace = true
+language.workspace = true
menu.workspace = true
open_path_prompt.workspace = true
picker.workspace = true
@@ -49,4 +50,4 @@ theme = { workspace = true, features = ["test-support"] }
workspace = { workspace = true, features = ["test-support"] }
zlog.workspace = true
remote_connection = { workspace = true, features = ["test-support"] }
-theme_settings = { workspace = true, features = ["test-support"] }
\ No newline at end of file
+theme_settings = { workspace = true, features = ["test-support"] }
diff --git a/crates/file_finder/src/file_finder.rs b/crates/file_finder/src/file_finder.rs
index c15524b17bf..50f0a99abdc 100644
--- a/crates/file_finder/src/file_finder.rs
+++ b/crates/file_finder/src/file_finder.rs
@@ -16,6 +16,7 @@ use gpui::{
KeyContext, Modifiers, ModifiersChangedEvent, ParentElement, Render,
StatefulInteractiveElement, Styled, Task, TaskExt, WeakEntity, Window, actions, rems,
};
+use language::{BufferSnapshot, Point};
use open_path_prompt::{
OpenPathPrompt,
file_finder_settings::{FileFinderSettings, FileFinderWidth},
@@ -29,7 +30,7 @@ use settings::Settings;
use std::{
borrow::Cow,
cmp,
- ops::Range,
+ ops::{Range, RangeInclusive},
path::{Component, Path, PathBuf},
sync::{
Arc,
@@ -806,6 +807,7 @@ struct FileSearchQuery {
raw_query: String,
file_query_end: Option<usize>,
path_position: PathWithPosition,
+ line_range: Option<RangeInclusive<u32>>,
}
impl FileSearchQuery {
@@ -815,6 +817,92 @@ impl FileSearchQuery {
None => &self.raw_query,
}
}
+
+ fn selection_range(&self, buffer_snapshot: &BufferSnapshot) -> Option<Range<Point>> {
+ if let Some(line_range) = self.line_range.clone() {
+ return Some(buffer_range_for_line_range(buffer_snapshot, line_range));
+ }
+
+ let row = self.path_position.row.map(|row| row.saturating_sub(1))?;
+ let col = self.path_position.column.unwrap_or(0).saturating_sub(1);
+ let point = buffer_snapshot.point_from_external_input(row, col);
+ Some(point..point)
+ }
+}
+
+fn parse_file_search_query(raw_query: &str) -> FileSearchQuery {
+ let raw_query = raw_query.trim().trim_end_matches(':').to_owned();
+
+ if let Some((path_query, start_line, end_line)) = parse_line_range_query(&raw_query) {
+ let path_query = path_query.to_owned();
+ return FileSearchQuery {
+ raw_query,
+ file_query_end: Some(path_query.len()),
+ path_position: PathWithPosition {
+ path: PathBuf::from(&path_query),
+ row: Some(start_line),
+ column: None,
+ },
+ line_range: end_line.map(|end| start_line..=end),
+ };
+ }
+
+ let path_position = PathWithPosition::parse_str(&raw_query);
+ let path_str = path_position.path.to_str();
+ let path_trimmed = path_str.unwrap_or(&raw_query).trim_end_matches(':');
+ let file_query_end = if path_trimmed == raw_query {
+ None
+ } else {
+ path_str.map(str::len)
+ };
+
+ FileSearchQuery {
+ raw_query,
+ file_query_end,
+ path_position,
+ line_range: None,
+ }
+}
+
+fn parse_line_range_query(raw_query: &str) -> Option<(&str, u32, Option<u32>)> {
+ let (path_query, line_range) = raw_query.rsplit_once(':')?;
+ if path_query.is_empty() {
+ return None;
+ }
+
+ let (start_line, end_line) = line_range.split_once('-')?;
+ let start_line = start_line.parse::<u32>().ok()?;
+ if start_line == 0 {
+ return None;
+ }
+
+ let end_line = end_line
+ .parse::<u32>()
+ .ok()
+ .filter(|&end| end != 0 && end >= start_line);
+
+ Some((path_query, start_line, end_line))
+}
+
+fn buffer_range_for_line_range(
+ buffer_snapshot: &BufferSnapshot,
+ line_range: RangeInclusive<u32>,
+) -> Range<Point> {
+ let max_point = buffer_snapshot.max_point();
+ let start_line = line_range.start().saturating_sub(1);
+ let start_point = if start_line > max_point.row {
+ max_point
+ } else {
+ Point::new(start_line, 0)
+ };
+ let end_line = *line_range.end();
+ let end_point = if end_line > max_point.row {
+ max_point
+ } else {
+ Point::new(end_line, 0)
+ };
+
+ start_point..end_point
}
impl FileFinderDelegate {
@@ -1488,23 +1576,8 @@ impl PickerDelegate for FileFinderDelegate {
cx.notify();
Task::ready(())
} else {
- let path_position = PathWithPosition::parse_str(raw_query);
- let raw_query = raw_query.trim().trim_end_matches(':').to_owned();
- let path = path_position.path.clone();
- let path_str = path_position.path.to_str();
- let path_trimmed = path_str.unwrap_or(&raw_query).trim_end_matches(':');
- let file_query_end = if path_trimmed == raw_query {
- None
- } else {
- // Safe to unwrap as we won't get here when the unwrap in if fails
- Some(path_str.unwrap().len())
- };
-
- let query = FileSearchQuery {
- raw_query,
- file_query_end,
- path_position,
- };
+ let query = parse_file_search_query(raw_query);
+ let path = query.path_position.path.clone();
cx.spawn_in(window, async move |this, cx| {
let _ = maybe!(async move {
@@ -1647,17 +1720,7 @@ impl PickerDelegate for FileFinderDelegate {
}
});
- let row = self
- .latest_search_query
- .as_ref()
- .and_then(|query| query.path_position.row)
- .map(|row| row.saturating_sub(1));
- let col = self
- .latest_search_query
- .as_ref()
- .and_then(|query| query.path_position.column)
- .unwrap_or(0)
- .saturating_sub(1);
+ let selection_query = self.latest_search_query.clone();
let finder = self.file_finder.clone();
let workspace = self.workspace.clone();
@@ -1665,9 +1728,7 @@ impl PickerDelegate for FileFinderDelegate {
let item = open_task
.await
.notify_workspace_async_err(workspace, &mut cx)?;
- if let Some(row) = row
- && let Some(active_editor) = item.downcast::<Editor>()
- {
+ if let Some(active_editor) = item.downcast::<Editor>() {
active_editor
.downgrade()
.update_in(cx, |editor, window, cx| {
@@ -1675,8 +1736,15 @@ impl PickerDelegate for FileFinderDelegate {
return;
};
let buffer_snapshot = buffer.read(cx).snapshot();
- let point = buffer_snapshot.point_from_external_input(row, col);
- editor.go_to_singleton_buffer_point(point, window, cx);
+ let Some(selection_query) = selection_query.as_ref() else {
+ return;
+ };
+ let Some(selection_range) =
+ selection_query.selection_range(&buffer_snapshot)
+ else {
+ return;
+ };
+ editor.go_to_singleton_buffer_range(selection_range, window, cx);
})
.log_err();
}
diff --git a/crates/file_finder/src/file_finder_tests.rs b/crates/file_finder/src/file_finder_tests.rs
index 7a17202a5e4..a9d67dd31aa 100644
--- a/crates/file_finder/src/file_finder_tests.rs
+++ b/crates/file_finder/src/file_finder_tests.rs
@@ -681,6 +681,200 @@ async fn test_row_column_numbers_query_outside_file(cx: &mut TestAppContext) {
});
}
+#[test]
+fn test_line_range_query_parsing() {
+ let query = parse_file_search_query("fs/smb/server/connection.c:428-440");
+
+ assert_eq!(query.raw_query, "fs/smb/server/connection.c:428-440");
+ assert_eq!(
+ query.file_query_end,
+ Some("fs/smb/server/connection.c".len())
+ );
+ assert_eq!(query.path_query(), "fs/smb/server/connection.c");
+ assert_eq!(query.path_position.row, Some(428));
+ assert_eq!(query.path_position.column, None);
+ assert_eq!(query.line_range, Some(428..=440));
+}
+
+#[test]
+fn test_parse_search_query() {
+ // Test trailing colon stripping.
+ let query = parse_file_search_query("content.rs:2:");
+ assert_eq!(query.raw_query, "content.rs:2");
+ assert_eq!(query.path_query(), "content.rs");
+ assert_eq!(query.path_position.row, Some(2));
+ assert_eq!(query.path_position.column, None);
+ assert_eq!(query.line_range, None);
+
+ // Test multiple trailing colons are also stripped.
+ let query = parse_file_search_query("content.rs:2:::");
+ assert_eq!(query.raw_query, "content.rs:2");
+ assert_eq!(query.path_query(), "content.rs");
+ assert_eq!(query.path_position.row, Some(2));
+ assert_eq!(query.path_position.column, None);
+ assert_eq!(query.line_range, None);
+
+ // Test trailing colon after an incomplete range is stripped.
+ let query = parse_file_search_query("content.rs:2-:");
+ assert_eq!(query.raw_query, "content.rs:2-");
+ assert_eq!(query.path_query(), "content.rs");
+ assert_eq!(query.path_position.row, Some(2));
+ assert_eq!(query.path_position.column, None);
+ assert_eq!(query.line_range, None);
+
+ // Test trailing colon after a complete range is stripped, range is preserved.
+ let query = parse_file_search_query("content.rs:2-4:");
+ assert_eq!(query.raw_query, "content.rs:2-4");
+ assert_eq!(query.path_query(), "content.rs");
+ assert_eq!(query.path_position.row, Some(2));
+ assert_eq!(query.path_position.column, None);
+ assert_eq!(query.line_range, Some(2..=4));
+
+ // Test multiple trailing colons after a complete range are all stripped.
+ let query = parse_file_search_query("content.rs:2-4:::");
+ assert_eq!(query.raw_query, "content.rs:2-4");
+ assert_eq!(query.path_query(), "content.rs");
+ assert_eq!(query.path_position.row, Some(2));
+ assert_eq!(query.path_position.column, None);
+ assert_eq!(query.line_range, Some(2..=4));
+
+ // Test invalid end should fall back to using the start as a single row.
+ let query = parse_file_search_query("content.rs:5-x");
+ assert_eq!(query.raw_query, "content.rs:5-x");
+ assert_eq!(query.path_query(), "content.rs");
+ assert_eq!(query.path_position.row, Some(5));
+ assert_eq!(query.path_position.column, None);
+ assert_eq!(query.line_range, None);
+
+ // Test reversed range (end < start) should fall back to using the start as a single row.
+ let query = parse_file_search_query("content.rs:10-5");
+ assert_eq!(query.raw_query, "content.rs:10-5");
+ assert_eq!(query.path_query(), "content.rs");
+ assert_eq!(query.path_position.row, Some(10));
+ assert_eq!(query.path_position.column, None);
+ assert_eq!(query.line_range, None);
+}
+
+#[gpui::test]
+async fn test_line_range_query_selects_lines(cx: &mut TestAppContext) {
+ let app_state = init_test(cx);
+
+ let first_file_contents = "line 1\nline 2\nline 3\nline 4\nline 5";
+ app_state
+ .fs
+ .as_fake()
+ .insert_tree(
+ path!("/src"),
+ json!({
+ "test": {
+ "first.rs": first_file_contents,
+ }
+ }),
+ )
+ .await;
+
+ let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;
+
+ let (picker, workspace, cx) = build_find_picker(project, cx);
+
+ let query = "test/first.rs:2-4";
+ picker
+ .update_in(cx, |finder, window, cx| {
+ finder
+ .delegate
+ .update_matches(query.to_string(), window, cx)
+ })
+ .await;
+ picker.update(cx, |finder, _| {
+ assert_eq!(finder.delegate.matches.len(), 2);
+ assert_match_at_position(finder, 0, "first.rs");
+ assert_match_at_position(finder, 1, "first.rs:2-4");
+
+ let latest_search_query = finder
+ .delegate
+ .latest_search_query
+ .as_ref()
+ .expect("Finder should have a query after the update_matches call");
+ assert_eq!(latest_search_query.raw_query, query);
+ assert_eq!(
+ latest_search_query.file_query_end,
+ Some("test/first.rs".len())
+ );
+ assert_eq!(latest_search_query.path_position.row, Some(2));
+ assert_eq!(latest_search_query.path_position.column, None);
+ assert_eq!(latest_search_query.line_range, Some(2..=4));
+ });
+
+ cx.dispatch_action(Confirm);
+
+ let editor = cx.update(|_, cx| workspace.read(cx).active_item_as::<Editor>(cx).unwrap());
+ cx.executor().advance_clock(Duration::from_secs(2));
+
+ editor.update(cx, |editor, cx| {
+ let all_selections = editor.selections.all_adjusted(&editor.display_snapshot(cx));
+ assert_eq!(
+ all_selections.len(),
+ 1,
+ "Expected to have 1 selection after file finder confirm, but got: {all_selections:?}"
+ );
+ let selection = all_selections.into_iter().next().unwrap();
+ assert_eq!(selection.start.row, 1);
+ assert_eq!(selection.start.column, 0);
+ assert_eq!(selection.end.row, 4);
+ assert_eq!(selection.end.column, 0);
+ });
+}
+
+#[gpui::test]
+async fn test_line_range_query_outside_file_clamps_to_eof(cx: &mut TestAppContext) {
+ let app_state = init_test(cx);
+
+ let first_file_contents = "line 1\nline 2";
+ app_state
+ .fs
+ .as_fake()
+ .insert_tree(
+ path!("/src"),
+ json!({
+ "test": {
+ "first.rs": first_file_contents,
+ }
+ }),
+ )
+ .await;
+
+ let project = Project::test(app_state.fs.clone(), [path!("/src").as_ref()], cx).await;
+
+ let (picker, workspace, cx) = build_find_picker(project, cx);
+
+ let query = "test/first.rs:200-300";
+ picker
+ .update_in(cx, |finder, window, cx| {
+ finder
+ .delegate
+ .update_matches(query.to_string(), window, cx)
+ })
+ .await;
+
+ cx.dispatch_action(Confirm);
+
+ let editor = cx.update(|_, cx| workspace.read(cx).active_item_as::<Editor>(cx).unwrap());
+ cx.executor().advance_clock(Duration::from_secs(2));
+
+ editor.update(cx, |editor, cx| {
+ let all_selections = editor.selections.all_adjusted(&editor.display_snapshot(cx));
+ assert_eq!(
+ all_selections.len(),
+ 1,
+ "Expected to have 1 selection after file finder confirm, but got: {all_selections:?}"
+ );
+ let selection = all_selections.into_iter().next().unwrap();
+ assert_eq!(selection.start, selection.end);
+ assert_eq!(selection.start.row, 1);
+ assert_eq!(selection.start.column, "line 2".len() as u32);
+ });
+}
+
#[gpui::test]
async fn test_matching_cancellation(cx: &mut TestAppContext) {
let app_state = init_test(cx);
@@ -3797,17 +3991,7 @@ fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
}
fn test_path_position(test_str: &str) -> FileSearchQuery {
- let path_position = PathWithPosition::parse_str(test_str);
-
- FileSearchQuery {
- raw_query: test_str.to_owned(),
- file_query_end: if path_position.path.to_str().unwrap() == test_str {
- None
- } else {
- Some(path_position.path.to_str().unwrap().len())
- },
- path_position,
- }
+ parse_file_search_query(test_str)
}
fn build_find_picker(