From 81a6ecf947ccde35d4abc9a56111acce892470ed Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Tue, 17 Nov 2026 18:43:45 +0800 Subject: [PATCH] =?UTF-8?q?feat(lsp-policy):=20=E5=BC=95=E7=94=A8=E5=B7=A5?= =?UTF-8?q?=E5=85=B7=E7=AA=97=E5=8F=A3=E7=9A=84=E5=88=86=E7=BB=84=E3=80=81?= =?UTF-8?q?=E6=A0=91=E8=A1=8C=E4=B8=8E=E7=94=A8=E6=B3=95=E8=A1=8C=E4=BA=A4?= =?UTF-8?q?=E7=BB=99=20Core?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 lsp.references.query:把查找用法的位置按文件分组(文件按项目视图的自然文件名顺序,用法按行列), 按平台传来的折叠状态和选中键给出可见行、每行预览的用法、前后用法,并把被折叠节点挡住的选中移到该节点。 新增 lsp.references.lines:按搜索结果行的同一规则显示用法所在行(去缩进和换行、远处用法前截断加省略号、 最多 240 字节),高亮用法范围。规则放在 lithe-text 的 line_preview。 workspace.search 在 includeContentRanges 时,内容匹配的 preview 也按 line_preview 生成,并返回 previewRanges,桌面端的查找结果和随处搜索不再各自裁剪行。 两个命令的用例在 rust/fixtures/lsp/references-*-v1.json,契约写进 rust-core-api.md。 Refs 1lck/Lithe-IDEA#2096 --- rust/Cargo.lock | 1 + rust/contracts/rust-core-api.md | 45 +- rust/crates/core/src/protocol/command.rs | 7 + .../crates/core/src/runtime/dispatcher/lsp.rs | 6 + rust/crates/core/src/tests/lsp_policy.rs | 28 + rust/crates/core/src/tests/project.rs | 9 + rust/crates/lsp-policy/Cargo.toml | 3 +- rust/crates/lsp-policy/src/lib.rs | 1 + rust/crates/lsp-policy/src/references.rs | 401 +++++++++++++ rust/crates/project/src/contracts.rs | 6 + rust/crates/project/src/files.rs | 1 + rust/crates/project/src/files/search.rs | 43 +- .../project/src/files/search_everywhere.rs | 1 + rust/crates/text/src/lib.rs | 6 +- rust/crates/text/src/line_preview.rs | 176 ++++++ rust/fixtures/lsp/references-lines-v1.json | 197 +++++++ rust/fixtures/lsp/references-query-v1.json | 552 ++++++++++++++++++ rust/fixtures/search/text-snapshot-v1.json | 7 + 18 files changed, 1479 insertions(+), 11 deletions(-) create mode 100644 rust/crates/lsp-policy/src/references.rs create mode 100644 rust/crates/text/src/line_preview.rs create mode 100644 rust/fixtures/lsp/references-lines-v1.json create mode 100644 rust/fixtures/lsp/references-query-v1.json diff --git a/rust/Cargo.lock b/rust/Cargo.lock index ea91d6ca..e3205eb5 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1155,6 +1155,7 @@ dependencies = [ "lithe-document-uri", "lithe-platform", "lithe-protocol", + "lithe-text", "serde", "serde_json", "url", diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 402d8056..a9845630 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -672,6 +672,8 @@ or removing a command fails until the table changes in the same commit. | `lsp.mergeCompletions` | Choose which candidates survive when several prioritized providers complete at one position | | `lsp.activationPolicy` | Decide whether a language server may start automatically after failures, using a platform monotonic clock | | `lsp.problems.query` | Filter, order, and group Problems tool-window diagnostics and count them by severity | +| `lsp.references.query` | Group Find Usages locations by file and lay out the References tool window's visible rows, selection, and previous/next usages | +| `lsp.references.lines` | Show the lines of References tool-window usages with highlighted usage ranges, as search results show theirs | | `lsp.startServer` | Start one Rust-owned process/session and begin initialization | | `lsp.stopServer` | Gracefully shut down a session, with a bounded force-stop fallback | | `lsp.updateWorkspaceConfiguration` | Replace the plugin configuration a running plugin-owned session answers `workspace/configuration` with, and announce it | @@ -2290,8 +2292,12 @@ Optional `includePathPatterns`, `excludePathPatterns`, and `pathFilterPrefix` filter paths before the page limit. Patterns are case-insensitive glob fragments: `*` excludes separators, `**` crosses them, and `?` matches one non-separator. When `includeContentRanges` is true, content matches also return the original -`sourceLine` and `contentMatchRanges` in UTF-16 units; existing callers keep the -trimmed `preview` and do not pay for those fields. +`sourceLine` and `contentMatchRanges` in UTF-16 units, and `preview` becomes the +result row's line with `previewRanges` (UTF-16 `{ start, length }` inside +`preview`): indentation and line break dropped and, when the first match starts +more than 32 units in, the front cut and replaced by `…`, the same rule +`lsp.references.lines` applies. Existing callers keep the trimmed `preview` +and do not pay for those fields. Observed `workspace.searchEverywhere` calls may emit `{ "type": "searchResults", "operationId": "…", "results": { "matches": […] } }` @@ -2977,6 +2983,41 @@ the Project view's natural file-name order. Severity is the LSP number; missing or out-of-range values are unknown (`0`) and rank last. Cases: `rust/fixtures/lsp/problems-query-v1.json`. +`lsp.references.query` accepts the Find Usages answer as +`{ locations: [{ fileKey, displayPath, line, column }] }` together with the +platform-held tree state: `rootCollapsed`, `collapsed` (the `fileKey`s of +closed file nodes; unknown keys are ignored), and the `selected` row key. It +returns `groups` (one per file in the natural file-name order of +`displayPath`, each with `key` `file:`, `fileKey`, `displayPath`, +`name`, `folder`, and `indices` into the submitted list ordered by line and +column, then submission order) and `rows`, the rows that show from top to +bottom. A row has `key` (`root`, `file:`, or `usage:`), +`kind` (`root`, `file`, `usage`), `depth`, `expanded` (nodes only), `group` +(files and usages), `shows` (the usage the row previews and opens: itself, or +the first usage under a node), and `previous`/`next` (the usages before and +after it in tree order, counting usages under closed nodes; absent at the +ends), so the platform steps through usages without another call. `selected` +and `selectedRow` name the selected row: an unknown or absent key selects the +first usage, and a row a closed node hides moves the selection to that node. +An empty answer returns no rows and no selection. Every location is kept; +none is filtered or merged with another on the same line. The platform keeps +the tree state, focus, and file reading, and queries again after a new +answer or an expand, collapse, or selection change. Cases: +`rust/fixtures/lsp/references-query-v1.json`. + +`lsp.references.lines` accepts `{ texts, usages: [{ text, line, column, +endLine, endColumn }] }`, where `text` indexes the distinct line texts (so a +long line with several usages crosses the boundary once) and positions are +zero-based UTF-16. It returns one `{ text, ranges: [{ start, length }] }` per +usage, in order. The usage is highlighted from `column` to `endColumn` on its +line, or to the end of the line when it runs onto later lines; an empty or +reversed range is not highlighted. The line is shown with the rule of search +result rows (`lithe_text::line_preview`): indentation and line break dropped, +the front cut and replaced by `…` when the usage starts more than 32 units in +(16 units stay before it), and the text bounded to 240 bytes at a character +boundary. A `text` index past `texts` is `invalid_request`. Cases: +`rust/fixtures/lsp/references-lines-v1.json`. + Core ships no built-in language-provider catalog. Every language server comes from a plugin's `languageServers` declaration, which Core validates and plans. diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index c79943f4..1fb18f64 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -647,6 +647,11 @@ pub enum LspCommand { ActivationPolicy, /// Filters, orders, and groups Problems tool-window diagnostics (`lsp.problems.query`). ProblemsQuery, + /// Groups Find Usages locations by file and lays out the References tool + /// window's rows (`lsp.references.query`). + ReferencesQuery, + /// Shows the lines of References tool-window usages (`lsp.references.lines`). + ReferencesLines, /// Starts and initializes a managed language server (`lsp.startServer`). StartServer, /// Gracefully shuts down a managed server (`lsp.stopServer`). @@ -1351,6 +1356,8 @@ impl CoreCommand { "lsp.mergeCompletions" => Some(Self::Lsp(LspCommand::MergeCompletions)), "lsp.activationPolicy" => Some(Self::Lsp(LspCommand::ActivationPolicy)), "lsp.problems.query" => Some(Self::Lsp(LspCommand::ProblemsQuery)), + "lsp.references.query" => Some(Self::Lsp(LspCommand::ReferencesQuery)), + "lsp.references.lines" => Some(Self::Lsp(LspCommand::ReferencesLines)), "lsp.startServer" => Some(Self::Lsp(LspCommand::StartServer)), "lsp.stopServer" => Some(Self::Lsp(LspCommand::StopServer)), "lsp.updateWorkspaceConfiguration" => { diff --git a/rust/crates/core/src/runtime/dispatcher/lsp.rs b/rust/crates/core/src/runtime/dispatcher/lsp.rs index e89ebb65..cfb5f206 100644 --- a/rust/crates/core/src/runtime/dispatcher/lsp.rs +++ b/rust/crates/core/src/runtime/dispatcher/lsp.rs @@ -113,6 +113,12 @@ pub(super) fn dispatch(command: LspCommand, id: Option, payload: Value) LspCommand::ProblemsQuery => { plugin_response(id, payload, lithe_lsp_policy::problems::query_command) } + LspCommand::ReferencesQuery => { + plugin_response(id, payload, lithe_lsp_policy::references::query_command) + } + LspCommand::ReferencesLines => { + plugin_response(id, payload, lithe_lsp_policy::references::lines_command) + } LspCommand::StartServer => { match serde_json::from_value::(payload) .map_err(|error| { diff --git a/rust/crates/core/src/tests/lsp_policy.rs b/rust/crates/core/src/tests/lsp_policy.rs index ff6c1d34..b5a5996c 100644 --- a/rust/crates/core/src/tests/lsp_policy.rs +++ b/rust/crates/core/src/tests/lsp_policy.rs @@ -88,6 +88,22 @@ fn problems_query_matches_shared_fixture() { ); } +#[test] +fn references_query_matches_shared_fixture() { + run_fixture( + "lsp.references.query", + include_str!("../../../../fixtures/lsp/references-query-v1.json"), + ); +} + +#[test] +fn references_lines_matches_shared_fixture() { + run_fixture( + "lsp.references.lines", + include_str!("../../../../fixtures/lsp/references-lines-v1.json"), + ); +} + #[test] fn activation_policy_matches_shared_fixture() { let fixture: Value = serde_json::from_str(include_str!( @@ -128,6 +144,18 @@ fn malformed_requests_fail_with_invalid_request() { "lsp.problems.query", json!({"diagnostics": [], "groupBy": "type"}), ), + ( + "lsp.references.query", + json!({"locations": [{"fileKey": "a"}]}), + ), + ( + "lsp.references.query", + json!({"locations": [], "expanded": []}), + ), + ( + "lsp.references.lines", + json!({"texts": [], "usages": [{"text": 0, "line": 0, "column": 0, "endLine": 0, "endColumn": 1}]}), + ), ("lsp.activationPolicy", json!({"event": "automaticStart"})), ( "lsp.activationPolicy", diff --git a/rust/crates/core/src/tests/project.rs b/rust/crates/core/src/tests/project.rs index 4e43904f..ab01f32c 100644 --- a/rust/crates/core/src/tests/project.rs +++ b/rust/crates/core/src/tests/project.rs @@ -1316,6 +1316,15 @@ fn search_pages_apply_path_filters_before_the_page_limit() { first["data"]["matches"][0]["contentMatchRanges"], case["expected"]["contentMatchRanges"] ); + // The row's line drops the indentation and keeps the match marked in it. + assert_eq!( + first["data"]["matches"][0]["preview"], + case["expected"]["preview"] + ); + assert_eq!( + first["data"]["matches"][0]["previewRanges"], + case["expected"]["previewRanges"] + ); payload["cursor"] = first["data"]["nextCursor"].clone(); assert!(payload["cursor"].is_string()); let second = call(&payload); diff --git a/rust/crates/lsp-policy/Cargo.toml b/rust/crates/lsp-policy/Cargo.toml index 6ca96eab..7e988188 100644 --- a/rust/crates/lsp-policy/Cargo.toml +++ b/rust/crates/lsp-policy/Cargo.toml @@ -3,13 +3,14 @@ name = "lithe-lsp-policy" version = "0.1.0" edition = "2021" license = "Apache-2.0" -description = "Deterministic language-tooling decisions both platform hosts apply: document identity, navigation targets, workspace edit plans, completion merging, activation and problems queries" +description = "Deterministic language-tooling decisions both platform hosts apply: document identity, navigation targets, workspace edit plans, completion merging, activation, and the Problems and References tool-window queries" [dependencies] lithe-core-rules = { path = "../core-rules" } lithe-document-uri = { path = "../document-uri" } lithe-platform = { path = "../platform" } lithe-protocol = { path = "../protocol" } +lithe-text = { path = "../text" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } url = "2.5" diff --git a/rust/crates/lsp-policy/src/lib.rs b/rust/crates/lsp-policy/src/lib.rs index ac85eb3f..bac18645 100644 --- a/rust/crates/lsp-policy/src/lib.rs +++ b/rust/crates/lsp-policy/src/lib.rs @@ -11,5 +11,6 @@ pub mod declaration_or_usages; pub mod document_identity; pub mod navigation_target; pub mod problems; +pub mod references; pub mod workspace_edit_plan; mod workspace_scope; diff --git a/rust/crates/lsp-policy/src/references.rs b/rust/crates/lsp-policy/src/references.rs new file mode 100644 index 00000000..000c1753 --- /dev/null +++ b/rust/crates/lsp-policy/src/references.rs @@ -0,0 +1,401 @@ +//! References tool-window grouping, tree rows, and usage lines +//! (`lsp.references.query`, `lsp.references.lines`). +//! +//! Find Usages answers with a flat list of locations. The References tool +//! window shows them the way IntelliJ IDEA's Find tool window does: a Usages +//! node over one node per file, each over its usages. Platforms keep which +//! nodes are collapsed and which row is selected, and ask Core again after a +//! change; Core returns the groups, the visible rows with the usage each row +//! previews and the usages before and after it, and moves a selection that a +//! collapsed node hides to the nearest row that shows. +//! +//! Files are ordered with the IDEA natural file-name order that the Project +//! view and the Problems tool window use; the usages of a file by line and +//! column. Every submitted location is kept: none is filtered or merged with +//! another on the same line. +//! +//! Platforms read the usages' lines themselves (from an open editor or the +//! disk) and submit them to `lsp.references.lines`, which shows them with the +//! rule search results use ([`lithe_text::line_preview`]). + +use lithe_core_rules::file_names::FileNameKey; +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_text::{line_preview, LinePreview, Utf16Span}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::{BTreeMap, BTreeSet}; + +/// Bytes a usage's line keeps after it was cut in front of the usage. +pub const USAGE_LINE_MAX_BYTES: usize = 240; + +/// The key of the Usages node. +const ROOT_KEY: &str = "root"; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct QueryRequest { + locations: Vec, + /// Hides every file under the Usages node. + #[serde(default)] + root_collapsed: bool, + /// The `fileKey`s of the file nodes the user closed; unknown keys are ignored. + #[serde(default)] + collapsed: Vec, + /// The key of the selected row; absent or unknown selects the first usage. + #[serde(default)] + selected: Option, +} + +/// One location of the answer. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LocationFacts { + /// Opaque file identity chosen by the platform with its native path + /// equality, or the URI of a location that is not a local file. + file_key: String, + /// The path shown to the user, with `/` separators: relative to the + /// workspace for a file in it. It decides the file order. + display_path: String, + /// Zero-based start line. + line: u64, + /// Zero-based UTF-16 start column. + column: u64, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Group { + /// The key of the file's node, `file:`. + key: String, + file_key: String, + display_path: String, + /// The last segment of `displayPath`. + name: String, + /// `displayPath` without its last segment; empty at the workspace root. + folder: String, + /// Indices into the submitted `locations`, in display order. + indices: Vec, +} + +#[derive(Serialize, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +enum RowKind { + Root, + File, + Usage, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Row { + /// `root`, `file:`, or `usage:`; stable while nodes open + /// and close. + key: String, + kind: RowKind, + /// 0 for the Usages node, 1 for a file, 2 for a usage. + depth: u8, + /// Whether a node's children show; absent on a usage. + #[serde(skip_serializing_if = "Option::is_none")] + expanded: Option, + /// The group of a file or usage row. + #[serde(skip_serializing_if = "Option::is_none")] + group: Option, + /// The location the row previews and opens: the usage itself, or the + /// first usage under a node. + shows: usize, + /// The usage before the row in tree order, counting usages under closed + /// nodes; a node sits just before its first usage. Absent at the start. + #[serde(skip_serializing_if = "Option::is_none")] + previous: Option, + /// The usage after the row in the same order; absent at the end. + #[serde(skip_serializing_if = "Option::is_none")] + next: Option, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct QueryResponse { + /// Files in natural path order. + groups: Vec, + /// The rows that show, top to bottom; empty for an empty answer. + rows: Vec, + /// The key of the selected row, always one of `rows`; absent when `rows` is empty. + #[serde(skip_serializing_if = "Option::is_none")] + selected: Option, + /// The position of the selected row in `rows`. + #[serde(skip_serializing_if = "Option::is_none")] + selected_row: Option, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LinesRequest { + /// The distinct line texts, so a long line with several usages crosses + /// the boundary once. + texts: Vec, + usages: Vec, +} + +/// One usage and the line its range starts on. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct UsageLine { + /// Index into `texts` of the usage's start line. + text: usize, + line: u64, + column: u64, + end_line: u64, + end_column: u64, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct LinesResponse { + /// One preview per submitted usage, in the same order. + lines: Vec, +} + +/// Executes `lsp.references.query`. +pub fn query_command(payload: Value) -> Result { + let request: QueryRequest = serde_json::from_value(payload).map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid References query request", + ) + .with_details(error.to_string()) + })?; + Ok(serde_json::to_value(query(&request)).expect("References query response should encode")) +} + +/// Executes `lsp.references.lines`. +pub fn lines_command(payload: Value) -> Result { + let request: LinesRequest = serde_json::from_value(payload).map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid References lines request", + ) + .with_details(error.to_string()) + })?; + let lines = request + .usages + .iter() + .map(|usage| { + let text = request.texts.get(usage.text).ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid References lines request", + ) + .with_details(format!("usage text {} is not in texts", usage.text)) + })?; + Ok(usage_line(text, usage)) + }) + .collect::, CoreError>>()?; + Ok(serde_json::to_value(LinesResponse { lines }) + .expect("References lines response should encode")) +} + +fn query(request: &QueryRequest) -> QueryResponse { + let groups = groups(&request.locations); + if groups.is_empty() { + return QueryResponse { + groups, + rows: Vec::new(), + selected: None, + selected_row: None, + }; + } + let collapsed: BTreeSet<&str> = request.collapsed.iter().map(String::as_str).collect(); + let expanded: Vec = groups + .iter() + .map(|group| !collapsed.contains(group.file_key.as_str())) + .collect(); + + // Usages in tree order, and where each group's usages start in it. + let order: Vec = groups + .iter() + .flat_map(|group| group.indices.iter().copied()) + .collect(); + let mut starts = Vec::with_capacity(groups.len()); + let mut position_of = vec![0; request.locations.len()]; + let mut slot_of = vec![0; request.locations.len()]; + let mut count = 0; + for (slot, group) in groups.iter().enumerate() { + starts.push(count); + for index in &group.indices { + position_of[*index] = count; + slot_of[*index] = slot; + count += 1; + } + } + let previous = |at: usize| at.checked_sub(1).map(|at| order[at]); + let next = |at: usize| order.get(at).copied(); + + let mut rows = vec![Row { + key: ROOT_KEY.into(), + kind: RowKind::Root, + depth: 0, + expanded: Some(!request.root_collapsed), + group: None, + shows: order[0], + previous: None, + next: next(0), + }]; + if !request.root_collapsed { + for (slot, group) in groups.iter().enumerate() { + let start = starts[slot]; + rows.push(Row { + key: group.key.clone(), + kind: RowKind::File, + depth: 1, + expanded: Some(expanded[slot]), + group: Some(slot), + shows: group.indices[0], + previous: previous(start), + next: next(start), + }); + if !expanded[slot] { + continue; + } + for index in &group.indices { + let at = position_of[*index]; + rows.push(Row { + key: usage_key(*index), + kind: RowKind::Usage, + depth: 2, + expanded: None, + group: Some(slot), + shows: *index, + previous: previous(at), + next: next(at + 1), + }); + } + } + } + + // A hidden selection moves to the nearest node that shows: a usage's file, + // or the Usages node when it is closed. + let wanted = request + .selected + .as_deref() + .and_then(|key| parse_key(key, &groups, request.locations.len())) + .unwrap_or(Selection::Usage(order[0])); + let selection = match wanted { + Selection::Usage(index) => { + let slot = slot_of[index]; + if request.root_collapsed { + ROOT_KEY.to_string() + } else if !expanded[slot] { + groups[slot].key.clone() + } else { + usage_key(index) + } + } + Selection::File(slot) if !request.root_collapsed => groups[slot].key.clone(), + Selection::File(_) | Selection::Root => ROOT_KEY.to_string(), + }; + let selected_row = rows.iter().position(|row| row.key == selection); + QueryResponse { + groups, + rows, + selected: Some(selection), + selected_row, + } +} + +/// The locations grouped by file, files in natural path order and usages by +/// position, with the submission order as the final tie-breaker. +fn groups(locations: &[LocationFacts]) -> Vec { + let mut slots = BTreeMap::<&str, usize>::new(); + let mut groups: Vec<(&LocationFacts, Vec)> = Vec::new(); + for (index, location) in locations.iter().enumerate() { + let slot = *slots.entry(location.file_key.as_str()).or_insert_with(|| { + groups.push((location, Vec::new())); + groups.len() - 1 + }); + groups[slot].1.push(index); + } + // Each file's display key is converted to UTF-16 once, not per comparison. + let keys: Vec = groups + .iter() + .map(|(first, _)| FileNameKey::new(&first.display_path)) + .collect(); + let mut sorted: Vec = (0..groups.len()).collect(); + sorted.sort_by(|left, right| { + let (left_first, right_first) = (groups[*left].0, groups[*right].0); + keys[*left] + .cmp(&keys[*right]) + .then_with(|| left_first.display_path.cmp(&right_first.display_path)) + .then_with(|| left_first.file_key.cmp(&right_first.file_key)) + }); + sorted + .into_iter() + .map(|slot| { + let (first, indices) = &groups[slot]; + let mut indices = indices.clone(); + indices.sort_by_key(|index| (locations[*index].line, locations[*index].column, *index)); + let (folder, name) = match first.display_path.rfind('/') { + Some(at) => (&first.display_path[..at], &first.display_path[at + 1..]), + None => ("", first.display_path.as_str()), + }; + Group { + key: format!("file:{}", first.file_key), + file_key: first.file_key.clone(), + display_path: first.display_path.clone(), + name: name.into(), + folder: folder.into(), + indices, + } + }) + .collect() +} + +enum Selection { + Root, + File(usize), + Usage(usize), +} + +/// The row a submitted key names, or `None` when it names nothing in this answer. +fn parse_key(key: &str, groups: &[Group], locations: usize) -> Option { + if key == ROOT_KEY { + return Some(Selection::Root); + } + if let Some(index) = key.strip_prefix("usage:") { + return index + .parse::() + .ok() + .filter(|index| *index < locations) + .map(Selection::Usage); + } + groups + .iter() + .position(|group| group.key == key) + .map(Selection::File) +} + +fn usage_key(index: usize) -> String { + format!("usage:{index}") +} + +/// The preview of a usage's line: the usage is highlighted from its start to +/// its end, or to the end of the line when it runs onto later lines. +fn usage_line(text: &str, usage: &UsageLine) -> LinePreview { + let width = text.trim_end_matches(['\r', '\n']).encode_utf16().count() as u64; + let start = usage.column.min(width); + let end = if usage.end_line == usage.line { + usage.end_column.min(width) + } else if usage.end_line > usage.line { + width + } else { + start + }; + let highlights = if end > start { + vec![Utf16Span { + start: start as usize, + length: (end - start) as usize, + }] + } else { + Vec::new() + }; + line_preview(text, &highlights, Some(USAGE_LINE_MAX_BYTES)) +} diff --git a/rust/crates/project/src/contracts.rs b/rust/crates/project/src/contracts.rs index d8399a55..e0006a69 100644 --- a/rust/crates/project/src/contracts.rs +++ b/rust/crates/project/src/contracts.rs @@ -67,6 +67,7 @@ pub struct SearchMatch { /// One-based line of a content match; absent for file and symbol matches. pub line: Option, /// Text shown for the match: the trimmed line, the path, or the symbol name. + /// With `sourceLine`, a content match's line as a result row shows it. pub preview: String, /// Symbol name of a symbol match. #[serde(skip_serializing_if = "Option::is_none")] @@ -80,6 +81,11 @@ pub struct SearchMatch { /// Content match ranges in UTF-16 units of `sourceLine`. #[serde(skip_serializing_if = "Vec::is_empty")] pub content_match_ranges: Vec, + /// Content match ranges in UTF-16 units of `preview`, present with + /// `sourceLine`: the preview is then the line as a result row shows it + /// ([`lithe_text::line_preview`]). + #[serde(skip_serializing_if = "Vec::is_empty")] + pub preview_ranges: Vec, /// Name relevance computed before category truncation; absent for content search. #[serde(skip_serializing_if = "Option::is_none")] pub matching_degree: Option, diff --git a/rust/crates/project/src/files.rs b/rust/crates/project/src/files.rs index 0ced6c86..4f7f3c58 100644 --- a/rust/crates/project/src/files.rs +++ b/rust/crates/project/src/files.rs @@ -114,6 +114,7 @@ mod event_filter_tests { name_match_ranges: vec![], source_line: None, content_match_ranges: Vec::new(), + preview_ranges: Vec::new(), matching_degree: Some(degree), is_ignored: None, }; diff --git a/rust/crates/project/src/files/search.rs b/rust/crates/project/src/files/search.rs index 556ecb22..6b1ac6f4 100644 --- a/rust/crates/project/src/files/search.rs +++ b/rust/crates/project/src/files/search.rs @@ -1,8 +1,10 @@ //! Text search, with and without the search index. use super::*; +use crate::contracts::SearchNameRange; use lithe_platform::paths::relative_path_contains; use lithe_platform::Platform; +use lithe_text::{line_preview, Utf16Span}; /// Applies workspace matching to provider snapshots in one bounded request. pub fn search_text_batch(request: SearchTextBatchRequest) -> Result { @@ -144,6 +146,7 @@ pub(crate) fn search_with_index( name_match_ranges: Vec::new(), source_line: None, content_match_ranges: Vec::new(), + preview_ranges: Vec::new(), matching_degree: None, is_ignored: None, }); @@ -179,19 +182,22 @@ pub(crate) fn search_with_index( for (index, line) in text.split('\n').enumerate() { lithe_protocol::cancellation::check()?; if matcher.matches(line) { + let (preview, content_match_ranges, preview_ranges) = + if request.include_content_ranges { + content_preview(line, matcher.content_ranges(line)) + } else { + (line.trim().to_string(), Vec::new(), Vec::new()) + }; let result = SearchMatch { kind: "content".to_string(), path: path.clone(), line: Some(index + 1), - preview: line.trim().to_string(), + preview, symbol_name: None, name_match_ranges: Vec::new(), source_line: request.include_content_ranges.then(|| line.to_string()), - content_match_ranges: if request.include_content_ranges { - matcher.content_ranges(line) - } else { - Vec::new() - }, + content_match_ranges, + preview_ranges, matching_degree: None, is_ignored: None, }; @@ -210,6 +216,31 @@ pub(crate) fn search_with_index( Ok(SearchResponse { matches }) } +/// The preview of a content match's line and its matches in it, as every +/// result row shows a line ([`line_preview`]), next to the matches in the line. +fn content_preview( + line: &str, + ranges: Vec, +) -> (String, Vec, Vec) { + let highlights: Vec = ranges + .iter() + .map(|range| Utf16Span { + start: range.start, + length: range.length, + }) + .collect(); + let shown = line_preview(line, &highlights, None); + let preview_ranges = shown + .ranges + .iter() + .map(|span| SearchNameRange { + start: span.start, + length: span.length, + }) + .collect(); + (shown.text, ranges, preview_ranges) +} + /// Builds or reuses the search index and reports its current size. pub fn warm_search_index( request: SearchIndexRequest, diff --git a/rust/crates/project/src/files/search_everywhere.rs b/rust/crates/project/src/files/search_everywhere.rs index 169822c4..51aa9133 100644 --- a/rust/crates/project/src/files/search_everywhere.rs +++ b/rust/crates/project/src/files/search_everywhere.rs @@ -114,6 +114,7 @@ pub(crate) fn search_everywhere_with_page( name_match_ranges: Vec::new(), source_line: None, content_match_ranges: Vec::new(), + preview_ranges: Vec::new(), matching_degree: None, is_ignored: None, }; diff --git a/rust/crates/text/src/lib.rs b/rust/crates/text/src/lib.rs index caa66a44..dae0a560 100644 --- a/rust/crates/text/src/lib.rs +++ b/rust/crates/text/src/lib.rs @@ -1,17 +1,19 @@ //! Text primitives shared by the editor and LSP layers: zero-based positions //! and ranges in UTF-16 code units, edit validation and planning, line -//! indexing, and the in-process completions, hover, navigation and snippets -//! that stay available without a language server. +//! indexing, result-row line previews, and the in-process completions, hover, +//! navigation and snippets that stay available without a language server. //! //! The `lsp.*` and `editor.*` JSON commands that use them are dispatched by //! `lithe-core`. mod edits; +mod line_preview; mod position; mod snippets; mod symbols; pub use edits::*; +pub use line_preview::*; pub use position::*; pub use snippets::*; pub use symbols::*; diff --git a/rust/crates/text/src/line_preview.rs b/rust/crates/text/src/line_preview.rs new file mode 100644 index 00000000..7b8b4724 --- /dev/null +++ b/rust/crates/text/src/line_preview.rs @@ -0,0 +1,176 @@ +//! How a result row shows a source line with highlighted fragments: the Find +//! in Files and Search Everywhere content matches and the References tool +//! window's usages all apply this one rule. +//! +//! The row drops the line's indentation and line break. When the first +//! highlight lies far to the right, the front of the line is replaced by an +//! ellipsis so the highlight is not lost past the row's end. Highlights are +//! UTF-16 code units, the unit the platforms measure text in. + +use serde::{Deserialize, Serialize}; + +/// UTF-16 units of a line kept in front of its first highlight; a highlight +/// further right makes the preview cut the line, keeping half of this lead. +pub const LINE_PREVIEW_LEAD: usize = 32; + +/// The ellipsis that replaces the cut front of a line. It is one UTF-16 unit. +const ELLIPSIS: &str = "…"; + +/// One half-open highlighted fragment of a line, in UTF-16 code units. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Utf16Span { + /// First highlighted UTF-16 code unit. + pub start: usize, + /// Highlighted length in UTF-16 code units. + pub length: usize, +} + +/// A line as a result row shows it, with its highlights moved into the shown +/// text. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LinePreview { + /// The shown text. + pub text: String, + /// The highlights inside `text`, ordered by start, each non-empty. + pub ranges: Vec, +} + +/// Returns the preview of `line` with `highlights` given in UTF-16 units of +/// `line`. +/// +/// Leading spaces and tabs and the trailing line break are dropped, with the +/// highlights in the indentation. When the first highlight starts more than +/// [`LINE_PREVIEW_LEAD`] units into what is left, the text in front of it is +/// cut at a character boundary and replaced by an ellipsis, keeping half the +/// lead before the highlight; highlights in the cut part are dropped. +/// `max_bytes` then bounds the text at a character boundary. Highlights that +/// run past the shown text are shortened to it, and empty ones are dropped. +pub fn line_preview(line: &str, highlights: &[Utf16Span], max_bytes: Option) -> LinePreview { + let indented = line.trim_start_matches([' ', '\t']); + // Spaces and tabs are one UTF-16 unit each. + let removed = line.len() - indented.len(); + let body = indented.trim_end_matches(['\r', '\n']); + let mut ranges: Vec = highlights + .iter() + .filter(|span| span.length > 0 && span.start >= removed) + .map(|span| Utf16Span { + start: span.start - removed, + length: span.length, + }) + .collect(); + ranges.sort_by_key(|span| (span.start, span.length)); + + let (prefix, offset) = match ranges.first() { + Some(first) if first.start > LINE_PREVIEW_LEAD => { + let cut = first.start - LINE_PREVIEW_LEAD / 2; + // Walk to the first character boundary at or past unit `cut`, so a + // surrogate pair is never split. + let (mut units, mut offset) = (0, body.len()); + for (index, character) in body.char_indices() { + if units >= cut { + offset = index; + break; + } + units += character.len_utf16(); + } + ranges.retain(|span| span.start >= units); + for span in &mut ranges { + span.start = span.start - units + ELLIPSIS.encode_utf16().count(); + } + (ELLIPSIS, offset) + } + _ => ("", 0), + }; + + let rest = &body[offset..]; + let end = match max_bytes { + Some(max) if prefix.len() + rest.len() > max => { + floor_char_boundary(rest, max.saturating_sub(prefix.len())) + } + _ => rest.len(), + }; + let mut text = String::with_capacity(prefix.len() + end); + text.push_str(prefix); + text.push_str(&rest[..end]); + + let shown = text.encode_utf16().count(); + ranges.retain(|span| span.start < shown); + for span in &mut ranges { + span.length = span.length.min(shown - span.start); + } + LinePreview { text, ranges } +} + +/// The largest character boundary of `text` at or before byte `index`. +fn floor_char_boundary(text: &str, index: usize) -> usize { + let mut index = index.min(text.len()); + while !text.is_char_boundary(index) { + index -= 1; + } + index +} + +#[cfg(test)] +mod tests { + use super::*; + + fn span(start: usize, length: usize) -> Utf16Span { + Utf16Span { start, length } + } + + #[test] + fn drops_the_indentation_and_the_line_break_with_the_highlights_in_them() { + let preview = line_preview("\t let x = 1;\r\n", &[span(0, 1), span(7, 1)], None); + assert_eq!(preview.text, "let x = 1;"); + assert_eq!(preview.ranges, vec![span(4, 1)]); + } + + #[test] + fn keeps_a_near_highlight_and_cuts_in_front_of_a_far_one() { + let near = format!("{}hit", "a".repeat(LINE_PREVIEW_LEAD)); + assert_eq!( + line_preview(&near, &[span(LINE_PREVIEW_LEAD, 3)], None), + LinePreview { + text: near.clone(), + ranges: vec![span(LINE_PREVIEW_LEAD, 3)] + } + ); + + let far = format!("{}hit tail", "a".repeat(40)); + let preview = line_preview(&far, &[span(44, 4), span(40, 3)], None); + // Sixteen units stay in front of the first highlight, after the ellipsis. + assert_eq!(preview.text, format!("…{}hit tail", "a".repeat(16))); + assert_eq!(preview.ranges, vec![span(17, 3), span(21, 4)]); + } + + #[test] + fn never_splits_a_surrogate_pair_when_cutting() { + // 23 single units, then one pair, so the cut at unit 24 falls inside the pair. + let line = format!("{}😀{}hit", "a".repeat(23), "b".repeat(15)); + let preview = line_preview(&line, &[span(40, 3)], None); + assert_eq!(preview.text, format!("…{}hit", "b".repeat(15))); + assert_eq!(preview.ranges, vec![span(16, 3)]); + } + + #[test] + fn bounds_the_text_at_a_character_boundary_and_shortens_the_highlights() { + let preview = line_preview("中文中文中文", &[span(1, 5)], Some(7)); + // Seven bytes end inside the third character, which is dropped. + assert_eq!(preview.text, "中文"); + assert_eq!(preview.ranges, vec![span(1, 1)]); + + let far = format!("{}hit", "a".repeat(40)); + let preview = line_preview(&far, &[span(40, 3)], Some(10)); + assert_eq!(preview.text, format!("…{}", "a".repeat(7))); + assert!(preview.ranges.is_empty()); + } + + #[test] + fn drops_empty_highlights_and_those_past_the_text() { + let preview = line_preview("abc\r", &[span(1, 0), span(2, 9), span(5, 1)], None); + assert_eq!(preview.text, "abc"); + assert_eq!(preview.ranges, vec![span(2, 1)]); + } +} diff --git a/rust/fixtures/lsp/references-lines-v1.json b/rust/fixtures/lsp/references-lines-v1.json new file mode 100644 index 00000000..493530e1 --- /dev/null +++ b/rust/fixtures/lsp/references-lines-v1.json @@ -0,0 +1,197 @@ +{ + "description": "lsp.references.lines shows the lines of References tool-window usages as search results show theirs: without indentation or line break, cut in front of a far usage, at most 240 bytes. Columns and ranges are UTF-16 code units; one preview per usage, in order.", + "cases": [ + { + "name": "the indentation goes and the usage is highlighted in what is left", + "request": { + "texts": [ + "\tabsSelf uint8 = 1 << 0", + "func (b *Box) Absolute() *Box {\r" + ], + "usages": [ + { + "text": 0, + "line": 4, + "column": 1, + "endLine": 4, + "endColumn": 8 + }, + { + "text": 1, + "line": 2, + "column": 14, + "endLine": 2, + "endColumn": 22 + } + ] + }, + "response": { + "lines": [ + { + "text": "absSelf uint8 = 1 << 0", + "ranges": [ + { + "start": 0, + "length": 7 + } + ] + }, + { + "text": "func (b *Box) Absolute() *Box {", + "ranges": [ + { + "start": 14, + "length": 8 + } + ] + } + ] + } + }, + { + "name": "a usage running onto later lines is marked to the end of its first line; CJK text and surrogate pairs count in UTF-16", + "request": { + "texts": [ + "\treturn call(a,\r", + " 中文😀 name := value" + ], + "usages": [ + { + "text": 0, + "line": 3, + "column": 8, + "endLine": 5, + "endColumn": 2 + }, + { + "text": 1, + "line": 0, + "column": 7, + "endLine": 0, + "endColumn": 11 + } + ] + }, + "response": { + "lines": [ + { + "text": "return call(a,", + "ranges": [ + { + "start": 7, + "length": 7 + } + ] + }, + { + "text": "中文😀 name := value", + "ranges": [ + { + "start": 5, + "length": 4 + } + ] + } + ] + } + }, + { + "name": "a far usage cuts the line in front of it and the line is bounded", + "request": { + "texts": [ + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxtargetyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" + ], + "usages": [ + { + "text": 0, + "line": 0, + "column": 100, + "endLine": 0, + "endColumn": 106 + } + ] + }, + "response": { + "lines": [ + { + "text": "…xxxxxxxxxxxxxxxxtargetyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", + "ranges": [ + { + "start": 17, + "length": 6 + } + ] + } + ] + } + }, + { + "name": "usages on one line share its text; an empty or reversed range is not highlighted", + "request": { + "texts": [ + "a = a + a" + ], + "usages": [ + { + "text": 0, + "line": 0, + "column": 0, + "endLine": 0, + "endColumn": 1 + }, + { + "text": 0, + "line": 0, + "column": 8, + "endLine": 0, + "endColumn": 9 + }, + { + "text": 0, + "line": 0, + "column": 4, + "endLine": 0, + "endColumn": 4 + }, + { + "text": 0, + "line": 2, + "column": 4, + "endLine": 1, + "endColumn": 9 + } + ] + }, + "response": { + "lines": [ + { + "text": "a = a + a", + "ranges": [ + { + "start": 0, + "length": 1 + } + ] + }, + { + "text": "a = a + a", + "ranges": [ + { + "start": 8, + "length": 1 + } + ] + }, + { + "text": "a = a + a", + "ranges": [] + }, + { + "text": "a = a + a", + "ranges": [] + } + ] + } + } + ] +} diff --git a/rust/fixtures/lsp/references-query-v1.json b/rust/fixtures/lsp/references-query-v1.json new file mode 100644 index 00000000..9be7638d --- /dev/null +++ b/rust/fixtures/lsp/references-query-v1.json @@ -0,0 +1,552 @@ +{ + "description": "lsp.references.query groups Find Usages locations by file and lays out the References tool window's rows. Files follow the natural file-name order, usages their position; every location is kept. Indices point into the submitted locations.", + "cases": [ + { + "name": "interleaved files are grouped in natural path order with usages by position", + "request": { + "locations": [ + { + "fileKey": "/w/ui/layout.go", + "displayPath": "ui/layout.go", + "line": 8, + "column": 12 + }, + { + "fileKey": "/w/ui/absolute.go", + "displayPath": "ui/absolute.go", + "line": 10, + "column": 14 + }, + { + "fileKey": "/w/ui/layout.go", + "displayPath": "ui/layout.go", + "line": 3, + "column": 12 + }, + { + "fileKey": "/w/ui/absolute.go", + "displayPath": "ui/absolute.go", + "line": 4, + "column": 1 + }, + { + "fileKey": "/w/File10.go", + "displayPath": "File10.go", + "line": 0, + "column": 0 + }, + { + "fileKey": "/w/File2.go", + "displayPath": "File2.go", + "line": 0, + "column": 0 + } + ] + }, + "response": { + "groups": [ + { + "key": "file:/w/File2.go", + "fileKey": "/w/File2.go", + "displayPath": "File2.go", + "name": "File2.go", + "folder": "", + "indices": [ + 5 + ] + }, + { + "key": "file:/w/File10.go", + "fileKey": "/w/File10.go", + "displayPath": "File10.go", + "name": "File10.go", + "folder": "", + "indices": [ + 4 + ] + }, + { + "key": "file:/w/ui/absolute.go", + "fileKey": "/w/ui/absolute.go", + "displayPath": "ui/absolute.go", + "name": "absolute.go", + "folder": "ui", + "indices": [ + 3, + 1 + ] + }, + { + "key": "file:/w/ui/layout.go", + "fileKey": "/w/ui/layout.go", + "displayPath": "ui/layout.go", + "name": "layout.go", + "folder": "ui", + "indices": [ + 2, + 0 + ] + } + ], + "rows": [ + { + "key": "root", + "kind": "root", + "depth": 0, + "expanded": true, + "shows": 5, + "next": 5 + }, + { + "key": "file:/w/File2.go", + "kind": "file", + "depth": 1, + "expanded": true, + "group": 0, + "shows": 5, + "next": 5 + }, + { + "key": "usage:5", + "kind": "usage", + "depth": 2, + "group": 0, + "shows": 5, + "next": 4 + }, + { + "key": "file:/w/File10.go", + "kind": "file", + "depth": 1, + "expanded": true, + "group": 1, + "shows": 4, + "previous": 5, + "next": 4 + }, + { + "key": "usage:4", + "kind": "usage", + "depth": 2, + "group": 1, + "shows": 4, + "previous": 5, + "next": 3 + }, + { + "key": "file:/w/ui/absolute.go", + "kind": "file", + "depth": 1, + "expanded": true, + "group": 2, + "shows": 3, + "previous": 4, + "next": 3 + }, + { + "key": "usage:3", + "kind": "usage", + "depth": 2, + "group": 2, + "shows": 3, + "previous": 4, + "next": 1 + }, + { + "key": "usage:1", + "kind": "usage", + "depth": 2, + "group": 2, + "shows": 1, + "previous": 3, + "next": 2 + }, + { + "key": "file:/w/ui/layout.go", + "kind": "file", + "depth": 1, + "expanded": true, + "group": 3, + "shows": 2, + "previous": 1, + "next": 2 + }, + { + "key": "usage:2", + "kind": "usage", + "depth": 2, + "group": 3, + "shows": 2, + "previous": 1, + "next": 0 + }, + { + "key": "usage:0", + "kind": "usage", + "depth": 2, + "group": 3, + "shows": 0, + "previous": 2 + } + ], + "selected": "usage:5", + "selectedRow": 2 + } + }, + { + "name": "a closed file hides its usages and takes their selection; equal names in two folders stay apart; equal positions keep the submission order", + "request": { + "locations": [ + { + "fileKey": "/w/b/util.go", + "displayPath": "b/util.go", + "line": 1, + "column": 0 + }, + { + "fileKey": "/w/a/util.go", + "displayPath": "a/util.go", + "line": 2, + "column": 0 + }, + { + "fileKey": "/w/a/util.go", + "displayPath": "a/util.go", + "line": 2, + "column": 0 + } + ], + "collapsed": [ + "/w/a/util.go", + "/w/gone.go" + ], + "selected": "usage:2" + }, + "response": { + "groups": [ + { + "key": "file:/w/a/util.go", + "fileKey": "/w/a/util.go", + "displayPath": "a/util.go", + "name": "util.go", + "folder": "a", + "indices": [ + 1, + 2 + ] + }, + { + "key": "file:/w/b/util.go", + "fileKey": "/w/b/util.go", + "displayPath": "b/util.go", + "name": "util.go", + "folder": "b", + "indices": [ + 0 + ] + } + ], + "rows": [ + { + "key": "root", + "kind": "root", + "depth": 0, + "expanded": true, + "shows": 1, + "next": 1 + }, + { + "key": "file:/w/a/util.go", + "kind": "file", + "depth": 1, + "expanded": false, + "group": 0, + "shows": 1, + "next": 1 + }, + { + "key": "file:/w/b/util.go", + "kind": "file", + "depth": 1, + "expanded": true, + "group": 1, + "shows": 0, + "previous": 2, + "next": 0 + }, + { + "key": "usage:0", + "kind": "usage", + "depth": 2, + "group": 1, + "shows": 0, + "previous": 2 + } + ], + "selected": "file:/w/a/util.go", + "selectedRow": 1 + } + }, + { + "name": "a closed Usages node shows alone and takes the selection of a file", + "request": { + "locations": [ + { + "fileKey": "/w/src/main.go", + "displayPath": "src/main.go", + "line": 7, + "column": 2 + }, + { + "fileKey": "/w/src/main.go", + "displayPath": "src/main.go", + "line": 3, + "column": 9 + } + ], + "rootCollapsed": true, + "selected": "file:/w/src/main.go" + }, + "response": { + "groups": [ + { + "key": "file:/w/src/main.go", + "fileKey": "/w/src/main.go", + "displayPath": "src/main.go", + "name": "main.go", + "folder": "src", + "indices": [ + 1, + 0 + ] + } + ], + "rows": [ + { + "key": "root", + "kind": "root", + "depth": 0, + "expanded": false, + "shows": 1, + "next": 1 + } + ], + "selected": "root", + "selectedRow": 0 + } + }, + { + "name": "a selected file node that shows stays selected", + "request": { + "locations": [ + { + "fileKey": "/w/main.go", + "displayPath": "main.go", + "line": 1, + "column": 1 + }, + { + "fileKey": "/w/lib.go", + "displayPath": "lib.go", + "line": 4, + "column": 0 + } + ], + "selected": "file:/w/main.go" + }, + "response": { + "groups": [ + { + "key": "file:/w/lib.go", + "fileKey": "/w/lib.go", + "displayPath": "lib.go", + "name": "lib.go", + "folder": "", + "indices": [ + 1 + ] + }, + { + "key": "file:/w/main.go", + "fileKey": "/w/main.go", + "displayPath": "main.go", + "name": "main.go", + "folder": "", + "indices": [ + 0 + ] + } + ], + "rows": [ + { + "key": "root", + "kind": "root", + "depth": 0, + "expanded": true, + "shows": 1, + "next": 1 + }, + { + "key": "file:/w/lib.go", + "kind": "file", + "depth": 1, + "expanded": true, + "group": 0, + "shows": 1, + "next": 1 + }, + { + "key": "usage:1", + "kind": "usage", + "depth": 2, + "group": 0, + "shows": 1, + "next": 0 + }, + { + "key": "file:/w/main.go", + "kind": "file", + "depth": 1, + "expanded": true, + "group": 1, + "shows": 0, + "previous": 1, + "next": 0 + }, + { + "key": "usage:0", + "kind": "usage", + "depth": 2, + "group": 1, + "shows": 0, + "previous": 1 + } + ], + "selected": "file:/w/main.go", + "selectedRow": 3 + } + }, + { + "name": "a usage key past the answer selects the first usage", + "request": { + "locations": [ + { + "fileKey": "/w/main.go", + "displayPath": "main.go", + "line": 1, + "column": 1 + } + ], + "selected": "usage:7" + }, + "response": { + "groups": [ + { + "key": "file:/w/main.go", + "fileKey": "/w/main.go", + "displayPath": "main.go", + "name": "main.go", + "folder": "", + "indices": [ + 0 + ] + } + ], + "rows": [ + { + "key": "root", + "kind": "root", + "depth": 0, + "expanded": true, + "shows": 0, + "next": 0 + }, + { + "key": "file:/w/main.go", + "kind": "file", + "depth": 1, + "expanded": true, + "group": 0, + "shows": 0, + "next": 0 + }, + { + "key": "usage:0", + "kind": "usage", + "depth": 2, + "group": 0, + "shows": 0 + } + ], + "selected": "usage:0", + "selectedRow": 2 + } + }, + { + "name": "a location that is not a local file is grouped under its URI", + "request": { + "locations": [ + { + "fileKey": "jar:file:///lib/rt.jar!/java/lang/String.class", + "displayPath": "jar:file:///lib/rt.jar!/java/lang/String.class", + "line": 10, + "column": 4 + } + ] + }, + "response": { + "groups": [ + { + "key": "file:jar:file:///lib/rt.jar!/java/lang/String.class", + "fileKey": "jar:file:///lib/rt.jar!/java/lang/String.class", + "displayPath": "jar:file:///lib/rt.jar!/java/lang/String.class", + "name": "String.class", + "folder": "jar:file:///lib/rt.jar!/java/lang", + "indices": [ + 0 + ] + } + ], + "rows": [ + { + "key": "root", + "kind": "root", + "depth": 0, + "expanded": true, + "shows": 0, + "next": 0 + }, + { + "key": "file:jar:file:///lib/rt.jar!/java/lang/String.class", + "kind": "file", + "depth": 1, + "expanded": true, + "group": 0, + "shows": 0, + "next": 0 + }, + { + "key": "usage:0", + "kind": "usage", + "depth": 2, + "group": 0, + "shows": 0 + } + ], + "selected": "usage:0", + "selectedRow": 2 + } + }, + { + "name": "an empty answer has no rows and no selection", + "request": { + "locations": [], + "selected": "root" + }, + "response": { + "groups": [], + "rows": [] + } + } + ] +} diff --git a/rust/fixtures/search/text-snapshot-v1.json b/rust/fixtures/search/text-snapshot-v1.json index 9b7775e6..921878fb 100644 --- a/rust/fixtures/search/text-snapshot-v1.json +++ b/rust/fixtures/search/text-snapshot-v1.json @@ -98,6 +98,13 @@ "start": 4, "length": 6 } + ], + "preview": "😀needle", + "previewRanges": [ + { + "start": 2, + "length": 6 + } ] } }