Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -568,7 +568,7 @@ or removing a command fails until the table changes in the same commit.
| `workspace.configureIndexing` | Install a process-local, canonical-root indexing policy before workspace consumers run; returns a monotonic revision, effective directory reasons and Git failure state; see `rust/fixtures/workspace/indexing-policy-v1.json` |
| `workspace.refreshIndexing` | Refresh external Git decisions for a live `root`, `ownerId`, `revision` lease without changing preferences or release tokens; returns lazy `IndexingStatus` |
| `workspace.filterChanges` | Filter an array of workspace-relative paths, or `{ paths, hiddenFilePatterns }` whose `!` entries turn default exclusions off, against Core's default hidden folders and patterns, including the folders enabled plugins declare; preserve order, spelling, and the empty root path. Native event loss bypasses filtering. Hosts relativize to the most specific explicit watch root and retain explicitly watched files |
| `workspace.listDirectories` | Return one visible level of children for each requested workspace-relative directory (`""` is the root); missing, hidden, symlinked, or nested-worktree paths are omitted, and each listing reports the nested worktrees it left out. Child directories have `children: []` only when a shallow probe proves them visibly empty; otherwise children remain omitted (unloaded), with no recursive tree allocation. Children list directories first, then names in IDEA's natural file-name order (digit runs compare by value, case-insensitive, `-` next to `_`; fixture `rust/fixtures/workspace/file-name-order-v1.json`) |
| `workspace.listDirectories` | Return one visible level of children for each requested workspace-relative directory (`""` is the root); missing, hidden, external/cyclic symlink, or nested-worktree paths are omitted; workspace-internal aliases are browsable and each listing reports `linked: true` when reached through an alias, and each listing reports the nested worktrees it left out. Child directories have `children: []` only when a shallow probe proves them visibly empty; otherwise children remain omitted (unloaded), with no recursive tree allocation. Children list directories first, then names in IDEA's natural file-name order (digit runs compare by value, case-insensitive, `-` next to `_`; fixture `rust/fixtures/workspace/file-name-order-v1.json`) |
| `workspace.orderEntries` | Order natively enumerated directory siblings |
| `workspace.projectTree.rows` | Say which loaded project tree nodes show as rows, keep the selection on a row that shows, and find the row the top of the view was on, without reading the disk (from `lithe-project-tree`) |
| `workspace.rowSelection.reduce` | Apply one plain, Cmd/Ctrl or Shift click, or the end of a batch, to the multi-selection of rows of workspace paths and return what a batch acts on (from `lithe-row-selection`) |
Expand Down Expand Up @@ -2332,7 +2332,41 @@ Without `projectPage`, its original capped literal-search response is unchanged.
Project pages use path/line continuation inside matching, including across pages
within one file; options and immutable `textOverrides` bind the cursor. There is
no 200-result total ceiling. Each page observes current files; edits before a
cursor require a fresh query.
cursor require a fresh query. Like Search Everywhere text queries, project pages
reuse ready content postings or search the names-only inventory directly; they
never synchronously build a full content index before returning the first page.

`workspace.search` with `countOnly: true` scans the same query, scope, decoding,
visibility and unsaved snapshots independently of the loaded page. It returns
`{ files, lines, occurrences, fileOccurrences }`: files with at least one content
match, matching lines, and every non-overlapping occurrence (including zero-width
regex matches). `countPaths` selects at most 200 loaded paths for per-file totals;
the map contains only selected matching paths, while the three totals cover the
entire query. No previews are retained or returned. The host publishes its first
page before starting this cancellable scan, labels counting/failure distinctly,
and discards totals when the query, snapshots or watched files change.

`workspace.search` with `languageSources` discovers relevant language providers
without opening documents. Each source has opaque `languageId`, optional
`fileExtensions` (with or without a dot) and `fileNames` (including project
markers). Core matches case-insensitively against the workspace name inventory
and returns sorted unique `{ languages }`. Sources are limited to 1024, each ID
to 256 bytes, each source to 1024 selectors and each selector to 1024 bytes.
The host reads enabled manifests, starts only relevant servers when symbol
search is requested, and queries their standard `workspace/symbol` capability
as readiness arrives. Core does not duplicate a language parser or semantic index.

Search, Search Everywhere and replacement accept query-local
`includeGenerated` and `followSymlinks`. Generated output declarations can be
included without overriding explicitly hidden names/globs or manual indexing
exclusions. Internal links retain lexical result paths; canonical targets must
stay inside the workspace and respect target exclusions and delegated roots.
Canonical ancestor checks stop cycles. External roots must be opened as workspace
roots rather than traversed implicitly. Link-aware indexes are rebuilt on native
file events and invalidated on saves, so a physical target change cannot leave
an alias stale. Replacement previews deduplicate canonical files to avoid writing
one file twice. Directory listings expose internal aliases and `linked`; hosts
refresh expanded linked listings when recursive physical-target events arrive.

Search and replacement accept `scopeExpression`: comma-separated relative paths,
include globs and `!`-prefixed exclude globs. `scopePaths` remains supported.
Expand Down
23 changes: 16 additions & 7 deletions rust/crates/core/src/tests/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2381,13 +2381,15 @@ fn file_encoding_options_are_optional_and_validated() {
serde_json::json!({"root": root, "path": "a.txt", "encoding": "ebcdic"}),
);
assert_eq!(unknown["error"]["code"], "invalid_request");
// Invalid bytes fail automatic detection but are repaired on an explicit reopen.
fs::write(root.join("bad.txt"), [0x41, 0xFF, 0xFE, 0x42, 0x81]).unwrap();
// Legacy bytes use the lossless Windows-1252 fallback; explicit UTF-8 repairs them.
fs::write(root.join("bad.txt"), b"caf\xE9").unwrap();
let auto = call(
"file.read",
serde_json::json!({"root": root, "path": "bad.txt"}),
);
assert_eq!(auto["error"]["code"], "parse_failed");
assert_eq!(auto["data"]["encoding"], "windows-1252", "{auto}");
assert_eq!(auto["data"]["text"], "café", "{auto}");
assert_eq!(auto["data"]["lossy"], false, "{auto}");
let lossy = call(
"file.read",
serde_json::json!({"root": root, "path": "bad.txt", "encoding": "utf-8"}),
Expand Down Expand Up @@ -2616,7 +2618,7 @@ fn search_reads_every_encoding_and_size_the_editor_opens() {
assert_eq!(search("binaryToken417", false), Vec::new());
assert_eq!(search("binary[T]oken417", true), Vec::new());

// Replacement writes UTF-8 back, so it must not offer the files that are not UTF-8.
// Replacement preserves the source encoding, so every searchable encoding is offered.
let replacement = run_project_command(
"workspace.replacePreview",
serde_json::json!({"root": root, "query": "Token417", "replacement": "Mark",
Expand All @@ -2629,10 +2631,17 @@ fn search_reads_every_encoding_and_size_the_editor_opens() {
.iter()
.map(|file| file["path"].as_str().expect("path should be text"))
.collect::<Vec<_>>();
assert!(replaced.contains(&"plain.txt"), "{replacement}");
for path in ["gbk.txt", "utf16-le.txt", "utf16-be.txt", "data.bin"] {
assert!(!replaced.contains(&path), "{path}: {replacement}");
for path in [
"plain.txt",
"gbk.txt",
"utf16-le.txt",
"utf16-be.txt",
"large.log",
] {
assert!(replaced.contains(&path), "{path}: {replacement}");
}
assert!(!replaced.contains(&"data.bin"), "{replacement}");
assert!(!replaced.contains(&"huge.log"), "{replacement}");
}

#[test]
Expand Down
2 changes: 2 additions & 0 deletions rust/crates/project/src/contracts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ pub struct DirectoryListingResponse {
#[serde(rename_all = "camelCase")]
/// One directory's children, each without its own children.
pub struct DirectoryListing {
/// This listing is reached through a workspace-internal alias and needs refresh on target events.
pub linked: bool,
/// Normalized workspace-relative path; empty for the root.
pub path: String,
/// Directories first, then case-insensitive names, as in snapshots.
Expand Down
34 changes: 34 additions & 0 deletions rust/crates/project/src/files/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,40 @@ pub(crate) struct Matcher {
}

impl Matcher {
/// Counts occurrences without constructing replacement text.
pub(crate) fn occurrence_count(&self, text: &str) -> usize {
if let Some(regex) = &self.regex {
regex.find_iter(text).count()
} else {
let haystack = if self.case_sensitive {
std::borrow::Cow::Borrowed(text)
} else {
std::borrow::Cow::Owned(text.to_lowercase())
};
let needle = if self.case_sensitive {
std::borrow::Cow::Borrowed(self.plain_query.as_str())
} else {
std::borrow::Cow::Owned(self.plain_query.to_lowercase())
};
if needle.is_empty() {
return 0;
}
haystack
.match_indices(needle.as_ref())
.filter(|(start, matched)| {
!self.whole_words
|| (!haystack[..*start]
.chars()
.next_back()
.is_some_and(is_word_character)
&& !haystack[*start + matched.len()..]
.chars()
.next()
.is_some_and(is_word_character))
})
.count()
}
}
/// Projects original byte ranges into the editor's UTF-16 coordinate space.
pub(crate) fn content_ranges(&self, text: &str) -> Vec<crate::contracts::SearchNameRange> {
let ranges = if let Some(regex) = &self.regex {
Expand Down
19 changes: 19 additions & 0 deletions rust/crates/project/src/files/paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,25 @@ pub(crate) fn safe_relative_path(root: &Path, value: &str) -> Result<PathBuf, Co
Ok(canonical)
}

/// Shares unsaved snapshots with internal aliases without copying their contents.
pub(crate) fn canonical_text_overrides<'a>(
root: &Path,
overrides: impl IntoIterator<Item = (&'a String, &'a String)>,
follow_links: bool,
) -> HashMap<PathBuf, &'a str> {
let mut result = HashMap::new();
if follow_links {
let mut paths: Vec<_> = overrides.into_iter().collect();
paths.sort_by_key(|(path, _)| *path);
for (path, text) in paths {
if let Ok(canonical) = safe_relative_path(root, path) {
result.entry(canonical).or_insert(text.as_str());
}
}
}
result
}

pub(crate) fn writable_relative_path(root: &Path, value: &str) -> Result<PathBuf, CoreError> {
let path = root.join(relative_request_path(value)?.as_ref());
if let Some(parent) = path.parent() {
Expand Down
29 changes: 24 additions & 5 deletions rust/crates/project/src/files/replace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,13 @@ pub fn replace_preview(
request.hidden_file_patterns.clone(),
)
.with_workspace_roots(&root, &request.workspace_roots)
.with_search_options(request.max_file_bytes, request.include_ignored)?;
let shared_index = search_index::get_or_build(&root, &rules)?;
.with_search_options(request.max_file_bytes, request.include_ignored)?
.with_search_visibility(
request.include_generated,
request.follow_symlinks,
&request.hidden_directory_names,
);
let shared_index = search_index::get_for_text(&root, &rules)?;
let index = shared_index
.read()
.map_err(|_| CoreError::new(ErrorCode::Unknown, "Search index lock was poisoned"))?;
Expand All @@ -78,7 +83,12 @@ pub fn replace_preview(
request.whole_words,
request.regular_expression,
)?;
let candidate_ids = index.candidate_ids(&query, request.regular_expression);
let aliases = canonical_text_overrides(&root, &request.text_overrides, request.follow_symlinks);
let candidate_ids = if aliases.is_empty() {
index.candidate_ids(&query, request.regular_expression)
} else {
index.all_file_ids()
};
let candidate_set = candidate_ids.iter().copied().collect::<HashSet<_>>();
let mut paths = if request.paths.is_empty() {
candidate_ids
Expand Down Expand Up @@ -108,6 +118,7 @@ pub fn replace_preview(
drop(index);
let masks = parse_file_mask(&request.file_mask);
let mut files = Vec::new();
let mut canonical_files = HashSet::new();
for path in paths {
lithe_protocol::cancellation::check()?;
let relative = safe_relative_path_string(&path)?;
Expand All @@ -120,6 +131,9 @@ pub fn replace_preview(
let Ok(file) = safe_relative_path(&root, &relative) else {
continue;
};
if !canonical_files.insert(file.clone()) {
continue;
}
if rules.is_delegated(&file)
|| indexing_policy
.as_ref()
Expand All @@ -130,8 +144,13 @@ pub fn replace_preview(
{
continue;
}
let (text, source_identity) = if let Some(text) = request.text_overrides.get(&relative) {
(text.clone(), None)
let snapshot = request
.text_overrides
.get(&relative)
.map(String::as_str)
.or_else(|| aliases.get(&file).copied());
let (text, source_identity) = if let Some(text) = snapshot {
(text.to_owned(), None)
} else {
let Some(bytes) = read_searchable_bytes(&file, rules.max_file_bytes) else {
continue;
Expand Down
12 changes: 12 additions & 0 deletions rust/crates/project/src/files/requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ pub struct DirectoryListingRequest {
#[serde(rename_all = "camelCase")]
/// Bounded file, content, and symbol search options.
pub struct SearchRequest {
/// Includes plugin-declared generated folders for this query, retaining manual exclusions.
#[serde(default)]
pub include_generated: bool,
/// Follows only links whose canonical targets stay inside the workspace.
#[serde(default)]
pub follow_symlinks: bool,
/// Comma-separated project paths and include/exclude globs; parsed only by Core.
#[serde(default)]
pub scope_expression: String,
Expand Down Expand Up @@ -190,6 +196,12 @@ pub struct SearchIndexStatusResponse {
#[serde(rename_all = "camelCase")]
/// Search and replacement options used to produce a non-mutating preview.
pub struct ReplacementPreviewRequest {
/// Uses the same request-local generated-folder visibility as search.
#[serde(default)]
pub include_generated: bool,
/// Follows only workspace-internal links; previews deduplicate canonical files.
#[serde(default)]
pub follow_symlinks: bool,
/// Same request-local path and glob expression used by content search.
#[serde(default)]
pub scope_expression: String,
Expand Down
Loading
Loading