From 71c9d22df7ff4819316422e57e8f2543b0b83476 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 19 Nov 2026 18:39:32 +0800 Subject: [PATCH] fix(search): read files the editor opens and match CRLF lines without \r Content search and its index now read files the way the desktop editor opens them, so matches are no longer missed (1lck/Lithe-IDEA#2198): - Decode with the editor's automatic detection (BOM-marked UTF-8 or UTF-16, UTF-8, then GBK or GB18030) instead of strict UTF-8. - Read files up to 16 MiB, the editor's open limit, instead of 2 MiB. - Skip binary files by a NUL byte outside UTF-16 before decoding. - Drop a CRLF line's \r before matching, so `$`, whole words, sourceLine and ranges are the same on CRLF and LF files, in workspace.search and workspace.searchTextBatch. Replacement previews still read only strict UTF-8 files up to 2 MiB, because hosts write replacementText back as UTF-8; they now match CRLF lines without \r too and keep it in replacementText. --- rust/contracts/rust-core-api.md | 11 ++ rust/crates/core/src/tests/project.rs | 178 +++++++++++++++++++++++ rust/crates/project/src/encoding.rs | 46 ++++++ rust/crates/project/src/files.rs | 6 + rust/crates/project/src/files/matcher.rs | 27 ++++ rust/crates/project/src/files/replace.rs | 9 +- rust/crates/project/src/files/search.rs | 4 +- 7 files changed, 276 insertions(+), 5 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index cde65f01..af6bd508 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -2309,6 +2309,17 @@ need separate buckets may also provide `maxFileResults` and `maxContentResults`; each category is capped independently and the total cap still applies. +Content search and its index read every file the desktop editor opens as text: +files up to 16 MiB, decoded with `file.read`'s automatic detection (BOM-marked +UTF-8 or UTF-16, UTF-8, then GBK or GB18030). Files containing a NUL byte outside +UTF-16, or other control characters after decoding, are binary and skipped. +Lines are split on `\n` and a CRLF line's `\r` is not part of its text, so `$`, +whole words, `sourceLine` and the ranges are the same on CRLF and LF files. +`workspace.replacePreview` reads only strict UTF-8 files up to 2 MiB, because +hosts write `replacementText` back as UTF-8; it keeps each CRLF line's `\r` in +`replacementText`. A file search finds in another encoding, or above 2 MiB, is +therefore absent from the preview. + Search index enumeration skips inaccessible or vanished descendant directories, logging workspace-relative diagnostic paths without discarding unrelated results. Workspace-root failures, cancellation, deadlines, and other errors still propagate. diff --git a/rust/crates/core/src/tests/project.rs b/rust/crates/core/src/tests/project.rs index ab01f32c..416940f4 100644 --- a/rust/crates/core/src/tests/project.rs +++ b/rust/crates/core/src/tests/project.rs @@ -2506,3 +2506,181 @@ fn shared_workspace_change_fixture() { assert_eq!(response["ok"], true, "{response}"); assert_eq!(response["data"], fixture["expected"]); } + +/// Runs one Core command and returns its JSON response. +fn run_project_command(command: &str, payload: Value) -> Value { + serde_json::from_str(&execute_json( + &serde_json::json!({"id": command, "command": command, "payload": payload}).to_string(), + )) + .expect("command response should be JSON") +} + +/// The path and untrimmed line of every content match in a `workspace.search` response. +fn content_matches(response: &Value) -> Vec<(String, String)> { + assert_eq!(response["ok"], true, "{response}"); + response["data"]["matches"] + .as_array() + .expect("matches should be an array") + .iter() + .filter(|value| value["kind"] == "content") + .map(|value| { + ( + value["path"] + .as_str() + .expect("path should be text") + .to_string(), + value["sourceLine"] + .as_str() + .expect("content matches should carry their line") + .to_string(), + ) + }) + .collect() +} + +#[test] +fn search_reads_every_encoding_and_size_the_editor_opens() { + // The editor detects BOM-marked UTF-8 and UTF-16, UTF-8, then GBK or GB18030, and + // opens files up to 16 MiB; search must find text in every file it can open. + let root = temporary_root("search-encodings"); + let _cleanup = super::support::Cleanup(root.clone()); + fs::create_dir_all(&root).expect("fixture root should be creatable"); + // "\u{4E2D}\u{6587} gbkToken417" in GBK: U+4E2D is D6 D0 and U+6587 is CE C4. + let mut gbk = vec![0xD6, 0xD0, 0xCE, 0xC4, b' ']; + gbk.extend_from_slice(b"gbkToken417\n"); + fs::write(root.join("gbk.txt"), gbk).expect("GBK fixture should be writable"); + let mut utf16_le = vec![0xFF, 0xFE]; + utf16_le.extend( + "utf16LeToken417\n" + .encode_utf16() + .flat_map(u16::to_le_bytes), + ); + fs::write(root.join("utf16-le.txt"), utf16_le).expect("UTF-16 LE fixture should be writable"); + let mut utf16_be = vec![0xFE, 0xFF]; + utf16_be.extend( + "utf16BeToken417\n" + .encode_utf16() + .flat_map(u16::to_be_bytes), + ); + fs::write(root.join("utf16-be.txt"), utf16_be).expect("UTF-16 BE fixture should be writable"); + fs::write(root.join("plain.txt"), "plainToken417\n").expect("plain fixture should be writable"); + // 2.4 MB, above the 2 MiB that both search and the index used to stop at. + let large = "filler line of text\n".repeat(120_000) + "largeToken417\n"; + fs::write(root.join("large.log"), large).expect("large fixture should be writable"); + // Above the editor's 16 MiB limit, so search never reads it. + let huge = "filler line of text\n".repeat(840_000) + "hugeToken417\n"; + assert!(huge.len() > 16 * 1024 * 1024); + fs::write(root.join("huge.log"), huge).expect("huge fixture should be writable"); + // A NUL byte marks binary content even when the rest is ASCII. + fs::write(root.join("data.bin"), b"binaryToken417\0\x01\x02\n") + .expect("binary fixture should be writable"); + + let search = |query: &str, regular_expression: bool| { + content_matches(&run_project_command( + "workspace.search", + serde_json::json!({ + "root": root, + "query": query, + "caseSensitive": true, + "regularExpression": regular_expression, + "maxResults": 50, + "maxFileResults": 0, + "includeContentRanges": true + }), + )) + }; + let found = |path: &str, line: &str| vec![(path.to_string(), line.to_string())]; + assert_eq!( + search("gbkToken417", false), + found("gbk.txt", "中文 gbkToken417") + ); + // A query without an ASCII trigram reads every file rather than the index. + assert_eq!(search("中文", false), found("gbk.txt", "中文 gbkToken417")); + assert_eq!( + search("utf16LeToken417", false), + found("utf16-le.txt", "utf16LeToken417") + ); + assert_eq!( + search("utf16BeToken417", false), + found("utf16-be.txt", "utf16BeToken417") + ); + assert_eq!( + search("largeToken417", false), + found("large.log", "largeToken417") + ); + assert_eq!( + search("large[T]oken417", true), + found("large.log", "largeToken417") + ); + assert_eq!(search("hugeToken417", false), Vec::new()); + 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. + let replacement = run_project_command( + "workspace.replacePreview", + serde_json::json!({"root": root, "query": "Token417", "replacement": "Mark", + "caseSensitive": true}), + ); + assert_eq!(replacement["ok"], true, "{replacement}"); + let replaced = replacement["data"]["files"] + .as_array() + .expect("replacement files should be an array") + .iter() + .map(|file| file["path"].as_str().expect("path should be text")) + .collect::>(); + 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}"); + } +} + +#[test] +fn search_and_replacement_match_line_ends_on_crlf_lines() { + // `$` must match before the carriage return of a CRLF line, and replacement must keep it. + let root = temporary_root("search-crlf"); + let _cleanup = super::support::Cleanup(root.clone()); + fs::create_dir_all(&root).expect("fixture root should be creatable"); + let text = "crlfToken417\r\nnext\r\n"; + fs::write(root.join("crlf.txt"), text).expect("CRLF fixture should be writable"); + + let response = run_project_command( + "workspace.search", + serde_json::json!({"root": root, "query": "crlfToken417$", "caseSensitive": true, + "regularExpression": true, "maxResults": 20, "maxFileResults": 0, + "includeContentRanges": true}), + ); + assert_eq!( + content_matches(&response), + vec![("crlf.txt".to_string(), "crlfToken417".to_string())] + ); + let found = &response["data"]["matches"][0]; + assert_eq!(found["line"], 1); + assert_eq!( + found["contentMatchRanges"], + serde_json::json!([{"start": 0, "length": 12}]) + ); + + let replacement = run_project_command( + "workspace.replacePreview", + serde_json::json!({"root": root, "query": "Token417$", "replacement": "Mark", + "caseSensitive": true, "regularExpression": true}), + ); + assert_eq!(replacement["ok"], true, "{replacement}"); + let file = &replacement["data"]["files"][0]; + assert_eq!(file["path"], "crlf.txt", "{replacement}"); + assert_eq!(file["matches"][0]["before"], "crlfToken417"); + assert_eq!(file["matches"][0]["after"], "crlfMark"); + assert_eq!(file["replacementText"], "crlfMark\r\nnext\r\n"); + + let batch = run_project_command( + "workspace.searchTextBatch", + serde_json::json!({"query": "crlfToken417$", "regularExpression": true, + "contextLines": 1, "files": [{"path": "wsl://fixture/crlf", "text": text}]}), + ); + assert_eq!(batch["ok"], true, "{batch}"); + let found = &batch["data"]["files"][0]["matches"][0]; + assert_eq!(found["line"], 1, "{batch}"); + assert_eq!(found["lineText"], "crlfToken417"); + assert_eq!(found["contextAfter"], serde_json::json!(["next"])); +} diff --git a/rust/crates/project/src/encoding.rs b/rust/crates/project/src/encoding.rs index 467ba58d..ffaeab1d 100644 --- a/rust/crates/project/src/encoding.rs +++ b/rust/crates/project/src/encoding.rs @@ -270,6 +270,26 @@ pub(crate) fn decode( }) } +/// The text of `bytes` as [`decode`] detects and decodes it without a +/// requested encoding. Bytes that are already UTF-8 without a byte order mark +/// become the text without a copy, which is the common case for search. +pub(crate) fn decode_detected_text(bytes: Vec) -> Result { + if bytes.starts_with(&UTF8_BOM) || starts_with_utf16_bom(&bytes) { + return decode(&bytes, None).map(|decoded| decoded.text); + } + match String::from_utf8(bytes) { + Ok(text) => Ok(text), + Err(error) => decode(error.as_bytes(), None).map(|decoded| decoded.text), + } +} + +/// Whether detection reads `bytes` as UTF-16, the only detected encoding +/// whose text bytes can be zero. +pub(crate) fn starts_with_utf16_bom(bytes: &[u8]) -> bool { + (bytes.starts_with(&UTF16_LE_BOM) && !bytes.starts_with(&UTF32_LE_BOM)) + || bytes.starts_with(&UTF16_BE_BOM) +} + /// Encodes `text` for writing. /// /// `bom` overrides the encoding's own BOM choice for the Unicode encodings; @@ -415,6 +435,32 @@ mod tests { fn utf32_le_bom_is_not_decoded_as_utf16() { let bytes = [0xFF, 0xFE, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00]; assert_ne!(detect(&bytes).ok(), Some(DocumentEncoding::Utf16LeBom)); + assert!(!starts_with_utf16_bom(&bytes)); + assert!(starts_with_utf16_bom(&[0xFF, 0xFE, 0x41, 0x00])); + assert!(starts_with_utf16_bom(&[0xFE, 0xFF, 0x00, 0x41])); + } + + #[test] + fn detected_text_is_the_text_of_automatic_decoding() { + let samples: [&[u8]; 6] = [ + b"plain", + &[0xEF, 0xBB, 0xBF, b'b', b'o', b'm'], + &[0xFF, 0xFE, b'l', 0x00, b'e', 0x00], + &[0xFE, 0xFF, 0x00, b'b', 0x00, b'e'], + &[0xD6, 0xD0, 0xCE, 0xC4], + &[0x81, 0x30, 0x81, 0x30], + ]; + for bytes in samples { + assert_eq!( + decode_detected_text(bytes.to_vec()).expect("sample should decode"), + decode_auto(bytes).text, + "{bytes:?}" + ); + } + assert!( + decode_detected_text(vec![0xFF, 0xFE, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00]).is_err() + ); + assert!(decode_detected_text(vec![b'a', 0xFF]).is_err()); } #[test] diff --git a/rust/crates/project/src/files.rs b/rust/crates/project/src/files.rs index 4f7f3c58..de95c4e7 100644 --- a/rust/crates/project/src/files.rs +++ b/rust/crates/project/src/files.rs @@ -49,8 +49,14 @@ pub use snapshot::*; pub use text_io::*; pub use visibility::*; +/// Largest file replacement rewrites, and the largest provider snapshot that +/// batch text search accepts. const MAX_FILE_SIZE: u64 = 2 * 1024 * 1024; +/// Largest file whose text search reads and indexes. It is the desktop +/// editor's open limit, so every content match opens at its line. +const MAX_SEARCH_FILE_SIZE: u64 = 16 * 1024 * 1024; + const MAX_OPEN_FILE_SIZE: u64 = 32 * 1024 * 1024; #[cfg(test)] diff --git a/rust/crates/project/src/files/matcher.rs b/rust/crates/project/src/files/matcher.rs index 90f5a7a1..074fd421 100644 --- a/rust/crates/project/src/files/matcher.rs +++ b/rust/crates/project/src/files/matcher.rs @@ -310,7 +310,28 @@ fn original_ranges_for_lowercase_matches( result } +/// The text search and the search index read from a file: plain text up to +/// [`MAX_SEARCH_FILE_SIZE`] in any encoding the editor detects when it opens +/// the file (BOM-marked UTF-8 or UTF-16, UTF-8, then GBK or GB18030). pub(crate) fn read_searchable_text(path: &Path) -> Option { + let metadata = fs::metadata(path).ok()?; + if !metadata.is_file() || metadata.len() > MAX_SEARCH_FILE_SIZE { + return None; + } + let bytes = fs::read(path).ok()?; + // Outside UTF-16 a zero byte decodes to U+0000, which plain text excludes, + // so binary files are rejected before any decoding is attempted. + if !encoding::starts_with_utf16_bom(&bytes) && bytes.contains(&0) { + return None; + } + let text = encoding::decode_detected_text(bytes).ok()?; + is_plain_text(&text).then_some(text) +} + +/// The text replacement may rewrite: strict UTF-8 plain text up to +/// [`MAX_FILE_SIZE`]. Replacement returns the whole new text, which hosts +/// write back as UTF-8, so a file in another encoding is never offered. +pub(crate) fn read_replaceable_text(path: &Path) -> Option { let metadata = fs::metadata(path).ok()?; if !metadata.is_file() || metadata.len() > MAX_FILE_SIZE { return None; @@ -319,6 +340,12 @@ pub(crate) fn read_searchable_text(path: &Path) -> Option { is_plain_text(&text).then_some(text) } +/// `line` without the carriage return that ends a CRLF line, so `$`, word +/// boundaries and match ranges are the same on CRLF and LF files. +pub(crate) fn line_content(line: &str) -> &str { + line.strip_suffix('\r').unwrap_or(line) +} + /// Whether `text` has no NUL or other control characters besides tab, line feed, vertical tab, form feed and carriage return. pub fn is_plain_text(text: &str) -> bool { text.chars().all(|character| { diff --git a/rust/crates/project/src/files/replace.rs b/rust/crates/project/src/files/replace.rs index e453dab1..aefdb190 100644 --- a/rust/crates/project/src/files/replace.rs +++ b/rust/crates/project/src/files/replace.rs @@ -108,15 +108,18 @@ pub fn replace_preview( .text_overrides .get(&relative) .cloned() - .or_else(|| read_searchable_text(&file)); + .or_else(|| read_replaceable_text(&file)); let Some(text) = text else { continue }; let mut matches = Vec::new(); let mut replaced_lines = Vec::new(); - for (index, line) in text.split('\n').enumerate() { + for (index, raw_line) in text.split('\n').enumerate() { lithe_protocol::cancellation::check()?; + // Match without a CRLF line's carriage return, as search does, and put it back. + let line = line_content(raw_line); + let line_end = &raw_line[line.len()..]; let (after, occurrence_count) = matcher.replace_with_options(line, &request.replacement, request.preserve_case); - replaced_lines.push(after.clone()); + replaced_lines.push(format!("{after}{line_end}")); if occurrence_count > 0 { matches.push(crate::contracts::ReplacementMatch { line: index + 1, diff --git a/rust/crates/project/src/files/search.rs b/rust/crates/project/src/files/search.rs index 6b1ac6f4..0614fbba 100644 --- a/rust/crates/project/src/files/search.rs +++ b/rust/crates/project/src/files/search.rs @@ -42,7 +42,7 @@ pub fn search_text_batch(request: SearchTextBatchRequest) -> Result = file.text.split('\n').collect(); + let lines: Vec<_> = file.text.split('\n').map(line_content).collect(); let mut matches = Vec::new(); for (index, line) in lines.iter().enumerate() { if !matcher.matches(line) { @@ -179,7 +179,7 @@ pub(crate) fn search_with_index( let Some(text) = read_searchable_text(&file) else { continue; }; - for (index, line) in text.split('\n').enumerate() { + for (index, line) in text.split('\n').map(line_content).enumerate() { lithe_protocol::cancellation::check()?; if matcher.matches(line) { let (preview, content_match_ranges, preview_ranges) =