From 4f01691ef340192becfe4ee53b0ebd50bd913495 Mon Sep 17 00:00:00 2001 From: Fabio Nunes <52166187+LittleGuava@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:46:36 -0300 Subject: [PATCH] fix(vfs): apply the configured encoding to ASCII files (#4829) A plain-ASCII file reads the same in any ASCII-compatible encoding, so it was always labelled UTF-8 and the first non-ASCII character typed into it was saved as UTF-8 even when the project or global encoding said otherwise. The configured project/global encoding now labels ASCII files too (decoding is unchanged), through one rule (ide_vfs::Fallback / resolve) shared by the editor, closed-file reads, bounded snapshots, search and VCS revisions. The .properties encoding keeps only decoding non-UTF-8 bytes, so an ASCII .properties file stays UTF-8 by default. An .editorconfig charset now applies to existing ASCII files (judged by their bytes, never relabelling UTF-16) on open, external reload and resource reload as well as to empty files. Refs #4557 Co-authored-by: LittleGuava <52166187+LittleGuava@users.noreply.github.com> --- crates/ide-host/src/ops/search.rs | 2 +- crates/ide-host/src/project.rs | 6 +- crates/ide-host/tests/vcs_encoding.rs | 81 ++++++++-- crates/ide-vfs/src/encoding.rs | 72 +++++++-- crates/ide-vfs/src/lib.rs | 61 +++---- crates/ide-vfs/tests/vfs.rs | 88 ++++++++++ crates/ide-workspace/Cargo.toml | 2 +- crates/ide-workspace/src/documents.rs | 60 +++++-- .../src/documents/workspace_edit.rs | 6 +- crates/ide-workspace/src/file_defaults.rs | 24 +-- crates/ide-workspace/tests/documents.rs | 151 ++++++++++++++++++ crates/ide-workspace/tests/workspace_edits.rs | 22 +++ src/editor/core/view/encodingStatus.test.tsx | 9 ++ src/platform/editorSettings.ts | 1 + 14 files changed, 491 insertions(+), 94 deletions(-) diff --git a/crates/ide-host/src/ops/search.rs b/crates/ide-host/src/ops/search.rs index db9d933688..8f17caf10d 100644 --- a/crates/ide-host/src/ops/search.rs +++ b/crates/ide-host/src/ops/search.rs @@ -111,7 +111,7 @@ pub(crate) fn search_project( }; let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text); let defaults = project.documents.file_defaults(); - let fallback = |path: &Path| defaults.fallback_for(path).map(str::to_owned); + let fallback = |path: &Path| defaults.fallback_for(path).map(|f| f.encoding.to_owned()); let mut total = SearchSummary::default(); for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) { let mut remaining = query.clone(); diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index 666010053b..eb37b61326 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -1498,17 +1498,15 @@ impl Project { return encoding_rs::Encoding::for_label(info.encoding.as_bytes()) .ok_or_else(|| ide_core::IdeError::invalid("unknown document encoding")); } - let defaults = self.documents.file_defaults(); - let fallback = defaults.fallback_for(path); // The working file only when it is a regular file: a path that is a directory there // (a committed symlink to a folder, a file replaced by a folder) has only its blob. if path.is_file() { - let loaded = ide_vfs::load_text_with_fallback(path, fallback)?; + let loaded = self.documents.load_file(path)?; return encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()) .ok_or_else(|| ide_core::IdeError::invalid("unknown file encoding")); } let bytes = self.with_log_repo_of(path, |r| r.file_bytes_at(path, rev))?.unwrap_or_default(); - Ok(ide_vfs::detect_encoding(&bytes, fallback)) + Ok(self.documents.detect_encoding(path, &bytes)) } /// Current text of `path`: the open buffer when available, else the file on disk. diff --git a/crates/ide-host/tests/vcs_encoding.rs b/crates/ide-host/tests/vcs_encoding.rs index 70af8119bd..bf90bcb5f5 100644 --- a/crates/ide-host/tests/vcs_encoding.rs +++ b/crates/ide-host/tests/vcs_encoding.rs @@ -1,16 +1,20 @@ mod common; use ide_core::{ChangeSet, TextChange}; -use ide_host::{Host, ops::vcs}; -use std::{path::Path, process::Command, time::Duration}; +use ide_host::{Host, Project, ops::vcs}; +use std::{ + path::{Path, PathBuf}, + process::Command, + sync::Arc, + time::Duration, +}; fn git(root: &Path, args: &[&str]) { let out = Command::new("git").current_dir(root).args(args).output().unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() { +fn repo() -> (tempfile::TempDir, PathBuf, PathBuf) { let temp = tempfile::tempdir().unwrap(); let base = dunce::canonicalize(temp.path()).unwrap(); let root = base.join("project"); @@ -20,6 +24,25 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() { git(&root, &["config", "user.email", "test@example.com"]); git(&root, &["config", "commit.gpgsign", "false"]); git(&root, &["config", "core.autocrlf", "false"]); + (temp, base, root) +} + +async fn open(base: &Path, root: &Path) -> (Host, Arc) { + let host = Host::new(common::host_config(base)); + host.trust.decide(root, true, false).unwrap(); + let project = host.open_project("main", root).unwrap(); + for _ in 0..500 { + if !project.repos().is_empty() { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + (host, project) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() { + let (_temp, base, root) = repo(); let path = root.join("Example.java"); let old = "// 中文注释\nclass Example {\n // 保持不变\n int value = 1;\n}\n"; let original = ide_vfs::encode(old, "gbk", false).unwrap(); @@ -27,15 +50,7 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() { std::fs::write(root.join("Utf8.java"), old).unwrap(); git(&root, &["add", "."]); git(&root, &["commit", "-m", "GBK Java"]); - let host = Host::new(common::host_config(&base)); - host.trust.decide(&root, true, false).unwrap(); - let project = host.open_project("main", &root).unwrap(); - for _ in 0..500 { - if !project.repos().is_empty() { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } + let (host, project) = open(&base, &root).await; let mut defaults = project.documents.file_defaults(); defaults.project_fallback = "gbk".into(); project.documents.set_file_defaults(defaults); @@ -139,3 +154,43 @@ async fn a_directory_symlink_revision_is_its_target() { assert_eq!(vcs::vcs_file_mode(&host, "main", link, Some("HEAD".into())).await.unwrap().as_deref(), Some("120000")); host.close_project("main"); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ascii_properties_keep_utf8_for_vcs_by_default() { + let (_temp, base, root) = repo(); + let path = root.join("messages.properties"); + std::fs::write(&path, b"greeting=Hello\n").unwrap(); + git(&root, &["add", "."]); + git(&root, &["commit", "-m", "properties"]); + let (host, project) = open(&base, &root).await; + + assert_eq!(project.vcs_encoding(&path, None).unwrap().charset, encoding_rs::UTF_8, "working file"); + std::fs::remove_file(&path).unwrap(); + assert_eq!(project.vcs_encoding(&path, Some("HEAD")).unwrap().charset, encoding_rs::UTF_8, "revision"); + host.close_project("main"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn vcs_labels_ascii_files_like_the_editor() { + let (_temp, base, root) = repo(); + std::fs::write(root.join(".editorconfig"), "root = true\n[Utf8.java]\ncharset = utf-8\n").unwrap(); + let latin = root.join("Latin.java"); + let utf8 = root.join("Utf8.java"); + std::fs::write(&latin, b"class Latin {}\n").unwrap(); + std::fs::write(&utf8, b"class Utf8 {}\n").unwrap(); + git(&root, &["add", "."]); + git(&root, &["commit", "-m", "ascii"]); + let (host, project) = open(&base, &root).await; + let mut defaults = project.documents.file_defaults(); + defaults.project_fallback = "iso-8859-15".into(); + project.documents.set_file_defaults(defaults); + + let charset = |path: &Path, rev| project.vcs_encoding(path, rev).unwrap().charset; + assert_eq!(charset(&latin, None), encoding_rs::ISO_8859_15, "working file, project encoding"); + assert_eq!(charset(&utf8, None), encoding_rs::UTF_8, "working file, .editorconfig charset"); + std::fs::remove_file(&latin).unwrap(); + std::fs::remove_file(&utf8).unwrap(); + assert_eq!(charset(&latin, Some("HEAD")), encoding_rs::ISO_8859_15, "revision, project encoding"); + assert_eq!(charset(&utf8, Some("HEAD")), encoding_rs::UTF_8, "revision, .editorconfig charset"); + host.close_project("main"); +} diff --git a/crates/ide-vfs/src/encoding.rs b/crates/ide-vfs/src/encoding.rs index 158579bf46..13f2a35781 100644 --- a/crates/ide-vfs/src/encoding.rs +++ b/crates/ide-vfs/src/encoding.rs @@ -174,6 +174,45 @@ pub(crate) fn decode(bytes: &[u8]) -> (String, &'static Encoding, bool, bool) { (text.into_owned(), enc, false, false) } +/// The configured encoding of a file. It decodes text that is neither valid UTF-8 nor +/// marked by a BOM and, when `ascii` is set, also labels plain ASCII text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Fallback<'a> { + pub encoding: &'a str, + pub ascii: bool, +} + +pub(crate) enum Resolution { + Keep, + /// Plain ASCII reads the same in the configured encoding: only the label changes. + Relabel(&'static Encoding), + Redecode(&'static Encoding), +} + +/// How decoded text meets the configured encoding; see [`Fallback`]. +pub(crate) fn resolve( + text: &str, + detected: &'static Encoding, + has_bom: bool, + binary: bool, + fallback: Option>, +) -> Resolution { + let Some((fallback, ascii)) = + fallback.and_then(|f| Some((Encoding::for_label(f.encoding.trim().as_bytes())?, f.ascii))) + else { + return Resolution::Keep; + }; + if binary || has_bom || fallback == detected || detected == UTF_16LE || detected == UTF_16BE { + Resolution::Keep + } else if detected != UTF_8 { + Resolution::Redecode(fallback) + } else if ascii && fallback.is_ascii_compatible() && text.is_ascii() { + Resolution::Relabel(fallback) + } else { + Resolution::Keep + } +} + /// Bytes of a file inside an archive (size-checked) and the archive's mtime. fn archive_bytes(path: &Path) -> IdeResult, f64)>> { let Some((archive, entry)) = crate::split_archive_path(path) else { return Ok(None) }; @@ -228,7 +267,11 @@ pub(crate) fn load_text(path: &Path) -> IdeResult { } /// Bounded disk snapshots for background consumers that share editor decoding. -pub(crate) fn load_text_bounded(path: &Path, fallback: Option<&str>, max_bytes: usize) -> IdeResult { +pub(crate) fn load_text_bounded( + path: &Path, + fallback: Option>, + max_bytes: usize, +) -> IdeResult { use std::io::Read; let regular = |meta: &fs::Metadata| meta.is_file() && meta.len() <= max_bytes as u64; if !regular(&fs::metadata(path)?) { @@ -246,15 +289,13 @@ pub(crate) fn load_text_bounded(path: &Path, fallback: Option<&str>, max_bytes: } let len = bytes.len() as u64; let (mut text, mut enc, has_bom, binary) = decode(&bytes); - if !binary - && !has_bom - && enc != UTF_8 - && enc != UTF_16LE - && enc != UTF_16BE - && let Some(fallback) = fallback.and_then(|label| Encoding::for_label(label.trim().as_bytes())) - { - text = fallback.decode_without_bom_handling(&bytes).0.into_owned(); - enc = fallback; + match resolve(&text, enc, has_bom, binary, fallback) { + Resolution::Keep => {} + Resolution::Relabel(fallback) => enc = fallback, + Resolution::Redecode(fallback) => { + text = fallback.decode_without_bom_handling(&bytes).0.into_owned(); + enc = fallback; + } } if text.len() > max_bytes { return Err(IdeError::invalid("decoded document is too large")); @@ -702,18 +743,21 @@ mod tests { }; let text = format!("{text}{}", "padding ".repeat(16)); crate::save_text(&path, &text, encoding, bom).unwrap(); - let ordinary = crate::load_text_with_fallback(&path, Some(encoding)).unwrap(); - let bounded = load_text_bounded(&path, Some(encoding), 1024).unwrap(); + let ordinary = crate::load_text_with_fallback(&path, Some(Fallback { encoding, ascii: true })).unwrap(); + let bounded = load_text_bounded(&path, Some(Fallback { encoding, ascii: true }), 1024).unwrap(); assert!(!bounded.binary, "{encoding} BOM={bom}"); assert_eq!(bounded.text, text, "{encoding} BOM={bom}"); assert_eq!( (&bounded.text, &bounded.encoding, bounded.has_bom), (&ordinary.text, &ordinary.encoding, ordinary.has_bom) ); - assert!(load_text_bounded(&path, Some(encoding), 2).is_err()); + assert!(load_text_bounded(&path, Some(Fallback { encoding, ascii: true }), 2).is_err()); } fs::write(&path, [0xe9; 4]).unwrap(); - assert!(load_text_bounded(&path, Some("windows-1252"), 4).is_err(), "decoded UTF-8 expansion is bounded"); + assert!( + load_text_bounded(&path, Some(Fallback { encoding: "windows-1252", ascii: true }), 4).is_err(), + "decoded UTF-8 expansion is bounded" + ); fs::write(&path, b"\x7fELF\0\0").unwrap(); assert!(load_text_bounded(&path, None, 1024).unwrap().binary); } diff --git a/crates/ide-vfs/src/lib.rs b/crates/ide-vfs/src/lib.rs index d4a67d8e15..b0c5976932 100644 --- a/crates/ide-vfs/src/lib.rs +++ b/crates/ide-vfs/src/lib.rs @@ -34,7 +34,7 @@ pub use compare::{ pub use decode_stream::{DecodedReader, decode_stream}; use encoding::SNIFF_LEN; pub use encoding::{ - LARGE_FILE_THRESHOLD, MAX_OPEN_SIZE, READ_ONLY_THRESHOLD, decode_properties_escapes, encode, + Fallback, LARGE_FILE_THRESHOLD, MAX_OPEN_SIZE, READ_ONLY_THRESHOLD, decode_properties_escapes, encode, encode_properties_ascii, save_properties_text, write_atomic, write_atomic_private, write_atomic_strict, }; pub use private::create_private_dir; @@ -218,24 +218,25 @@ pub fn load_text(path: &Path) -> IdeResult { } /// Loads a regular file with editor decoding, bounding both disk and decoded bytes. -pub fn load_text_bounded(path: &Path, fallback: Option<&str>, max_bytes: usize) -> IdeResult { +pub fn load_text_bounded(path: &Path, fallback: Option>, max_bytes: usize) -> IdeResult { encoding::load_text_bounded(path, fallback, max_bytes) } /// Like [`load_text`], but text that is neither valid UTF-8 nor marked by a BOM -/// is decoded as `fallback` (the configured project encoding) instead of guessed. -pub fn load_text_with_fallback(path: &Path, fallback: Option<&str>) -> IdeResult { - let loaded = encoding::load_text(path)?; - match fallback { - Some(enc) - if !loaded.binary - && !loaded.has_bom - && loaded.encoding != "utf-8" - && !loaded.encoding.starts_with("utf-16") => - { - encoding::load_text_as(path, enc).or(Ok(loaded)) +/// is decoded as `fallback` (the configured encoding) instead of guessed, and +/// plain ASCII text is labelled with it when `fallback.ascii` is set. +pub fn load_text_with_fallback(path: &Path, fallback: Option>) -> IdeResult { + let mut loaded = encoding::load_text(path)?; + let detected = encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8); + match encoding::resolve(&loaded.text, detected, loaded.has_bom, loaded.binary, fallback) { + encoding::Resolution::Keep => Ok(loaded), + encoding::Resolution::Relabel(enc) => { + loaded.encoding = encoding::encoding_label(enc); + Ok(loaded) + } + encoding::Resolution::Redecode(enc) => { + encoding::load_text_as(path, &encoding::encoding_label(enc)).or(Ok(loaded)) } - _ => Ok(loaded), } } @@ -371,17 +372,11 @@ impl FsBatch { } /// Detect a revision's encoding with the same rules as files opened in the editor. -pub fn detect_encoding(bytes: &[u8], fallback: Option<&str>) -> &'static encoding_rs::Encoding { - let (_, detected, has_bom, binary) = encoding::decode(bytes); - if !binary - && !has_bom - && detected != encoding_rs::UTF_8 - && detected != encoding_rs::UTF_16LE - && detected != encoding_rs::UTF_16BE - { - fallback.and_then(|label| encoding_rs::Encoding::for_label(label.trim().as_bytes())).unwrap_or(detected) - } else { - detected +pub fn detect_encoding(bytes: &[u8], fallback: Option>) -> &'static encoding_rs::Encoding { + let (text, detected, has_bom, binary) = encoding::decode(bytes); + match encoding::resolve(&text, detected, has_bom, binary, fallback) { + encoding::Resolution::Keep => detected, + encoding::Resolution::Relabel(enc) | encoding::Resolution::Redecode(enc) => enc, } } @@ -393,18 +388,10 @@ pub fn decode_text(bytes: &[u8], fallback: Option<&str>) -> Option { if binary { return None; } - let fallback = fallback.and_then(|label| encoding_rs::Encoding::for_label(label.trim().as_bytes())); - match fallback { - Some(enc) - if !has_bom - && enc != detected - && detected != encoding_rs::UTF_8 - && detected != encoding_rs::UTF_16LE - && detected != encoding_rs::UTF_16BE => - { - Some(enc.decode_without_bom_handling(bytes).0.into_owned()) - } - _ => Some(text), + let fallback = fallback.map(|encoding| Fallback { encoding, ascii: false }); + match encoding::resolve(&text, detected, has_bom, binary, fallback) { + encoding::Resolution::Redecode(enc) => Some(enc.decode_without_bom_handling(bytes).0.into_owned()), + encoding::Resolution::Keep | encoding::Resolution::Relabel(_) => Some(text), } } diff --git a/crates/ide-vfs/tests/vfs.rs b/crates/ide-vfs/tests/vfs.rs index 12a51a52d7..6f9f9a9758 100644 --- a/crates/ide-vfs/tests/vfs.rs +++ b/crates/ide-vfs/tests/vfs.rs @@ -518,3 +518,91 @@ fn rule_changes_notify_the_affected_subtree() { drop(watcher); } } + +fn configured(encoding: &str) -> Option> { + Some(Fallback { encoding, ascii: true }) +} + +#[test] +fn ascii_text_takes_the_configured_encoding() { + let (_tmp, root) = root(); + let path = root.join("A.java"); + fs::write(&path, b"class A {}\n").unwrap(); + let fallback = configured("iso-8859-15"); + + let loaded = load_text_with_fallback(&path, fallback).unwrap(); + assert_eq!((loaded.text.as_str(), loaded.encoding.as_str()), ("class A {}\n", "iso-8859-15")); + let bounded = load_text_bounded(&path, fallback, 1024).unwrap(); + assert_eq!((bounded.text.as_str(), bounded.encoding.as_str()), ("class A {}\n", "iso-8859-15")); + assert_eq!(detect_encoding(b"class A {}\n", fallback), encoding_rs::ISO_8859_15); + assert_eq!(decode_text(b"class A {}\n", Some("iso-8859-15")).as_deref(), Some("class A {}\n")); +} + +fn configured_label(name: &str, bytes: &[u8], configured: Option<&str>) -> String { + let (_tmp, root) = root(); + let path = root.join(name); + fs::write(&path, bytes).unwrap(); + load_text_with_fallback(&path, configured.map(|encoding| Fallback { encoding, ascii: true })).unwrap().encoding +} + +#[test] +fn ascii_stays_utf8_without_a_configured_encoding() { + assert_eq!(configured_label("a.txt", b"abc\n", None), "utf-8"); +} + +#[test] +fn ascii_ignores_a_configured_encoding_that_is_not_ascii_compatible() { + assert_eq!(configured_label("a.txt", b"abc\n", Some("utf-16le")), "utf-8"); +} + +#[test] +fn utf8_with_accents_keeps_utf8() { + assert_eq!(configured_label("a.txt", "ação\n".as_bytes(), Some("iso-8859-15")), "utf-8"); + assert_eq!(detect_encoding("ação".as_bytes(), configured("iso-8859-15")), encoding_rs::UTF_8); +} + +#[test] +fn a_utf8_bom_keeps_utf8() { + assert_eq!(configured_label("a.txt", b"\xef\xbb\xbfabc\n", Some("iso-8859-15")), "utf-8"); +} + +#[test] +fn utf16_keeps_utf16_with_or_without_a_bom() { + assert_eq!(configured_label("a.txt", b"\xff\xfea\x00b\x00", Some("iso-8859-15")), "utf-16le"); + let bomless = b"a\x00b\x00c\x00d\x00"; + assert_eq!(configured_label("b.txt", bomless, Some("iso-8859-15")), "utf-16le"); + assert_eq!(decode_text(bomless, Some("iso-8859-15")).as_deref(), Some("abcd")); +} + +#[test] +fn binary_content_keeps_its_label() { + let elf = b"\x7fELF\x00\x00\x01"; + assert_eq!(configured_label("a.bin", elf, Some("iso-8859-15")), "utf-8"); + assert_eq!(detect_encoding(elf, configured("iso-8859-15")), encoding_rs::UTF_8); +} + +#[test] +fn non_utf8_bytes_are_decoded_with_the_configured_encoding() { + let (_tmp, root) = root(); + let path = root.join("latin.txt"); + fs::write(&path, b"a\xe7\xe3o \xa4\n").unwrap(); + let latin = load_text_with_fallback(&path, configured("iso-8859-15")).unwrap(); + assert_eq!((latin.text.as_str(), latin.encoding.as_str()), ("ação €\n", "iso-8859-15")); +} + +#[test] +fn a_fallback_without_ascii_only_decodes_non_utf8_text() { + let (_tmp, root) = root(); + let decode_only = Some(Fallback { encoding: "iso-8859-1", ascii: false }); + let ascii = root.join("ascii.properties"); + fs::write(&ascii, b"greeting=Hello\n").unwrap(); + let latin = root.join("latin.properties"); + fs::write(&latin, b"greeting=Ol\xe1\n").unwrap(); + + assert_eq!(load_text_with_fallback(&ascii, decode_only).unwrap().encoding, "utf-8"); + assert_eq!(load_text_bounded(&ascii, decode_only, 1024).unwrap().encoding, "utf-8"); + assert_eq!(detect_encoding(b"greeting=Hello\n", decode_only), encoding_rs::UTF_8); + let loaded = load_text_with_fallback(&latin, decode_only).unwrap(); + assert_eq!((loaded.text.as_str(), loaded.encoding.as_str()), ("greeting=Ol\u{e1}\n", "windows-1252")); + assert_eq!(detect_encoding(b"greeting=Ol\xe1\n", decode_only), encoding_rs::WINDOWS_1252); +} diff --git a/crates/ide-workspace/Cargo.toml b/crates/ide-workspace/Cargo.toml index 92e264dc4a..1a1b5d0298 100644 --- a/crates/ide-workspace/Cargo.toml +++ b/crates/ide-workspace/Cargo.toml @@ -23,7 +23,7 @@ tempfile.workspace = true globset.workspace = true uuid.workspace = true zip.workspace = true +encoding_rs.workspace = true [dev-dependencies] tempfile.workspace = true -encoding_rs.workspace = true diff --git a/crates/ide-workspace/src/documents.rs b/crates/ide-workspace/src/documents.rs index 24d2fbe941..b2fbe220ca 100644 --- a/crates/ide-workspace/src/documents.rs +++ b/crates/ide-workspace/src/documents.rs @@ -201,6 +201,22 @@ fn disk_len(path: &Path) -> u64 { std::fs::metadata(path).map(|m| m.len()).unwrap_or(0) } +fn editorconfig_label(editorconfig: Option<&EditorConfigProps>, detected: &str, ascii: bool) -> Option<&'static str> { + let (charset, _) = editorconfig?.encoding()?; + let compatible = encoding_rs::Encoding::for_label(detected.as_bytes()).is_some_and(|e| e.is_ascii_compatible()); + (ascii && compatible && !charset.starts_with("utf-16")).then_some(charset) +} + +fn apply_editorconfig_charset(loaded: &mut ide_vfs::LoadedText, editorconfig: Option<&EditorConfigProps>) { + if loaded.binary { + return; + } + if let Some(charset) = editorconfig_label(editorconfig, &loaded.encoding, !loaded.has_bom && loaded.text.is_ascii()) + { + loaded.encoding = charset.to_owned(); + } +} + fn read_only_error(path: &Path) -> IdeError { IdeError::new(ErrorKind::PermissionDenied, format!("{} is read-only", path.display())) } @@ -304,13 +320,32 @@ impl Documents { /// Closed-file readers use the same decoding as document opening. pub fn load_file(&self, path: &Path) -> IdeResult { - Self::load_with_defaults(path, &self.file_defaults()) + let defaults = self.file_defaults(); + Self::load_with_defaults(path, &defaults, self.editorconfig_for(path, &defaults).as_ref()) + } + + /// Encoding of `bytes`, a revision of `path`, with the same rules as opening the file. + pub fn detect_encoding(&self, path: &Path, bytes: &[u8]) -> &'static encoding_rs::Encoding { + let defaults = self.file_defaults(); + let detected = ide_vfs::detect_encoding(bytes, defaults.fallback_for(&absolute(path))); + let editorconfig = self.editorconfig_for(path, &defaults); + editorconfig_label(editorconfig.as_ref(), detected.name(), bytes.is_ascii()) + .and_then(|label| encoding_rs::Encoding::for_label(label.as_bytes())) + .unwrap_or(detected) + } + + fn editorconfig_for(&self, path: &Path, defaults: &FileDefaults) -> Option { + if !defaults.editorconfig || ide_vfs::is_archive_path(path) { + return None; + } + self.editorconfig.resolve(&absolute(path)) } /// Bounded closed-file snapshots use the same project defaults as open documents. pub fn load_file_bounded(&self, path: &Path, max_bytes: usize) -> IdeResult { let defaults = self.file_defaults(); let mut loaded = ide_vfs::load_text_bounded(path, defaults.fallback_for(&absolute(path)), max_bytes)?; + apply_editorconfig_charset(&mut loaded, self.editorconfig_for(path, &defaults).as_ref()); if !loaded.binary && defaults.native_to_ascii_for(path) { loaded.text = ide_vfs::decode_properties_escapes(&loaded.text); } @@ -321,8 +356,13 @@ impl Documents { Self::load_as(path, encoding, self.native_to_ascii_for(path)) } - fn load_with_defaults(path: &Path, defaults: &FileDefaults) -> IdeResult { + fn load_with_defaults( + path: &Path, + defaults: &FileDefaults, + editorconfig: Option<&EditorConfigProps>, + ) -> IdeResult { let mut loaded = ide_vfs::load_text_with_fallback(path, defaults.fallback_for(&absolute(path)))?; + apply_editorconfig_charset(&mut loaded, editorconfig); if !loaded.binary && defaults.native_to_ascii_for(path) { loaded.text = ide_vfs::decode_properties_escapes(&loaded.text); } @@ -407,7 +447,9 @@ impl Documents { return Ok(info); } let defaults = self.file_defaults(); - let loaded = Self::load_with_defaults(path, &defaults)?; + let editorconfig = self.editorconfig_for(path, &defaults); + let loaded = Self::load_with_defaults(path, &defaults, editorconfig.as_ref())?; + let editorconfig = editorconfig.filter(|_| !loaded.binary); let language = (self.detect_language)(path, loaded.text.lines().next()); let ui_mode = (self.detect_ui_mode)(path, &language); // Archive entries (`!/`) are read-only and kept from language @@ -417,11 +459,6 @@ impl Documents { let writable = !in_archive && meta.as_ref().map(|m| !m.permissions().readonly()).unwrap_or(true); let empty_file = meta.as_ref().is_some_and(|m| m.len() == 0); let observed = !(loaded.binary || loaded.too_large || in_archive); - let editorconfig = if loaded.binary || in_archive || !defaults.editorconfig { - None - } else { - self.editorconfig.resolve(&absolute(path)) - }; let mut doc = Document::new(&loaded.text); let (mut encoding, mut has_bom) = (loaded.encoding, loaded.has_bom); // An empty file has nothing to detect: Code Style / File Encodings defaults apply. @@ -434,8 +471,9 @@ impl Documents { if let Some(le) = ec.end_of_line { doc.set_line_ending(le); } - // An empty file has no detectable encoding: take the configured one. - if empty_file && let Some((enc, bom)) = ec.encoding() { + if let Some((enc, bom)) = ec.encoding() + && empty_file + { (encoding, has_bom) = (enc.to_owned(), bom); } } @@ -1359,7 +1397,7 @@ impl Documents { let loaded = if st.encoding_chosen { Self::load_as(&st.path, &st.encoding, native_to_ascii)? } else { - Self::load_with_defaults(&st.path, &defaults)? + Self::load_with_defaults(&st.path, &defaults, st.editorconfig.as_ref())? }; st.native_to_ascii = native_to_ascii; loaded diff --git a/crates/ide-workspace/src/documents/workspace_edit.rs b/crates/ide-workspace/src/documents/workspace_edit.rs index b3873b0cef..90ef500470 100644 --- a/crates/ide-workspace/src/documents/workspace_edit.rs +++ b/crates/ide-workspace/src/documents/workspace_edit.rs @@ -808,11 +808,13 @@ impl Documents { return Err(stale(path)); } let defaults = self.file_defaults(); + let native_to_ascii = defaults.native_to_ascii_for(path); let loaded = if state.encoding_chosen { - Self::load_as(path, &state.encoding, state.native_to_ascii)? + Self::load_as(path, &state.encoding, native_to_ascii)? } else { - ide_vfs::load_text_with_fallback(path, defaults.fallback_for(path))? + Self::load_with_defaults(path, &defaults, state.editorconfig.as_ref())? }; + state.native_to_ascii = native_to_ascii; self.replace_locked(id, state, &loaded.text)?; state.encoding = loaded.encoding; state.has_bom = loaded.has_bom; diff --git a/crates/ide-workspace/src/file_defaults.rs b/crates/ide-workspace/src/file_defaults.rs index e26484eb02..04a9c8b38c 100644 --- a/crates/ide-workspace/src/file_defaults.rs +++ b/crates/ide-workspace/src/file_defaults.rs @@ -1,6 +1,6 @@ //! Settings › Editor › File Encodings / Code Style defaults applied by the //! document layer: encoding, BOM and line separator of new (empty) files, the -//! fallback decoding of files that are not valid UTF-8, and EditorConfig support. +//! encoding of files that are not valid UTF-8 or are plain ASCII, and EditorConfig support. use ide_core::settings::Settings; use ide_text::LineEnding; @@ -13,7 +13,7 @@ pub struct FileDefaults { /// Write a BOM into new UTF-8 files. pub utf8_bom: bool, pub line_ending: LineEnding, - /// Fallback for project files that are not valid UTF-8. + /// Encoding of project files that are not valid UTF-8 or are plain ASCII. pub project_fallback: String, /// Fallback for files outside `root`. pub global_fallback: String, @@ -54,16 +54,17 @@ impl FileDefaults { } } - /// Encoding to decode `path` with when it is not valid UTF-8 (`None`: detect). - pub fn fallback_for(&self, path: &Path) -> Option<&str> { - let label = if path.extension().is_some_and(|e| e == "properties") { - &self.properties_fallback + /// Encoding for `path` when it is not valid UTF-8 (`None`: detect). The project and + /// global encodings also label plain ASCII; the properties encoding only decodes. + pub fn fallback_for(&self, path: &Path) -> Option> { + let (label, ascii) = if path.extension().is_some_and(|e| e == "properties") { + (&self.properties_fallback, false) } else if self.root.as_ref().is_none_or(|r| path.starts_with(r)) { - &self.project_fallback + (&self.project_fallback, true) } else { - &self.global_fallback + (&self.global_fallback, true) }; - (label != "utf-8").then_some(label.as_str()) + (label != "utf-8").then_some(ide_vfs::Fallback { encoding: label, ascii }) } pub fn native_to_ascii_for(&self, path: &Path) -> bool { @@ -101,9 +102,10 @@ mod tests { let d = FileDefaults::from_settings(&s, Some(Path::new("/p"))); assert!(d.utf8_bom); assert_eq!(d.line_ending, LineEnding::CrLf); - assert_eq!(d.fallback_for(Path::new("/p/a.txt")), Some("gbk")); + let fallback = |encoding, ascii| Some(ide_vfs::Fallback { encoding, ascii }); + assert_eq!(d.fallback_for(Path::new("/p/a.txt")), fallback("gbk", true)); assert_eq!(d.fallback_for(Path::new("/elsewhere/a.txt")), None); - assert_eq!(d.fallback_for(Path::new("/p/a.properties")), Some("iso-8859-1")); + assert_eq!(d.fallback_for(Path::new("/p/a.properties")), fallback("iso-8859-1", false)); assert!(d.new_file_bytes().is_empty(), "BOM only for UTF-8 new files"); } } diff --git a/crates/ide-workspace/tests/documents.rs b/crates/ide-workspace/tests/documents.rs index 9b177cf45f..fa1edb3b41 100644 --- a/crates/ide-workspace/tests/documents.rs +++ b/crates/ide-workspace/tests/documents.rs @@ -1296,3 +1296,154 @@ fn language_of_a_closed_file_reads_the_hashbang() { docs.apply_edits(doc.id, &[TextEdit { range: all, new_text: "#!/usr/bin/env python3".into() }]).unwrap(); assert_eq!(language(None), "python", "the open buffer's first line"); } + +fn latin_project(f: &Fixture) { + let mut defaults = f.docs.file_defaults(); + defaults.project_fallback = "iso-8859-15".into(); + f.docs.set_file_defaults(defaults); +} + +#[test] +fn ascii_file_in_a_latin_project_saves_new_characters_in_the_project_encoding() { + let f = fixture(); + latin_project(&f); + let path = f.root.join("A.java"); + fs::write(&path, b"class A {}\n").unwrap(); + + let doc = f.docs.open(&path).unwrap(); + assert_eq!(doc.encoding, "iso-8859-15"); + f.docs.edit(doc.id, doc.version, change(0, 0, "// ação €\n")).unwrap(); + f.docs.save(doc.id).unwrap(); + + assert_eq!(fs::read(&path).unwrap(), b"// a\xe7\xe3o \xa4\nclass A {}\n"); +} + +#[test] +fn ascii_file_stays_utf8_when_the_project_encoding_is_utf8() { + let f = fixture(); + let path = f.root.join("A.java"); + fs::write(&path, b"class A {}\n").unwrap(); + + let doc = f.docs.open(&path).unwrap(); + assert_eq!(doc.encoding, "utf-8"); + f.docs.edit(doc.id, doc.version, change(0, 0, "// ç\n")).unwrap(); + f.docs.save(doc.id).unwrap(); + + assert_eq!(fs::read(&path).unwrap(), "// ç\nclass A {}\n".as_bytes()); +} + +#[test] +fn utf8_text_with_accents_keeps_utf8_in_a_latin_project() { + let f = fixture(); + latin_project(&f); + let path = f.root.join("A.java"); + fs::write(&path, "// ação\n").unwrap(); + + assert_eq!(f.docs.open(&path).unwrap().encoding, "utf-8"); +} + +#[test] +fn typing_a_character_latin9_lacks_into_an_ascii_file_fails_the_save() { + let f = fixture(); + latin_project(&f); + let path = f.root.join("A.java"); + fs::write(&path, b"class A {}\n").unwrap(); + let doc = f.docs.open(&path).unwrap(); + f.docs.edit(doc.id, doc.version, change(0, 0, "// 漢\n")).unwrap(); + + let before = f.events.lock().len(); + let err = f.docs.save(doc.id).expect_err("ISO-8859-15 cannot encode the edit"); + + assert_eq!(err.kind, ErrorKind::InvalidInput, "{err}"); + assert_failed_save_preserves_edit(&f, doc.id, "// 漢\nclass A {}\n", before); + assert_eq!(fs::read(&path).unwrap(), b"class A {}\n"); +} + +#[test] +fn editorconfig_utf8_charset_wins_over_a_latin_project_for_ascii_files() { + let f = fixture(); + latin_project(&f); + fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap(); + let path = f.root.join("A.java"); + fs::write(&path, b"class A {}\n").unwrap(); + + let doc = f.docs.open(&path).unwrap(); + assert_eq!(doc.encoding, "utf-8"); + f.docs.edit(doc.id, doc.version, change(0, 0, "// é\n")).unwrap(); + f.docs.save(doc.id).unwrap(); + + assert_eq!(fs::read(&path).unwrap(), "// é\nclass A {}\n".as_bytes()); +} + +#[test] +fn ascii_properties_file_stays_utf8_by_default() { + let f = fixture(); + let path = f.root.join("messages.properties"); + fs::write(&path, b"greeting=Hello\n").unwrap(); + + let doc = f.docs.open(&path).unwrap(); + assert_eq!(doc.encoding, "utf-8", "the properties encoding only decodes bytes that are not UTF-8"); + f.docs.edit(doc.id, doc.version, change(9, 14, "Olá")).unwrap(); + f.docs.save(doc.id).unwrap(); + + assert_eq!(fs::read(&path).unwrap(), "greeting=Olá\n".as_bytes()); +} + +#[test] +fn latin_properties_file_still_decodes_with_the_properties_encoding() { + let f = fixture(); + let path = f.root.join("messages.properties"); + fs::write(&path, b"greeting=Ol\xe1\n").unwrap(); + + let doc = f.docs.open(&path).unwrap(); + assert_eq!(doc.encoding, "windows-1252"); + assert_eq!(f.docs.text_of(&path).as_deref(), Some("greeting=Olá\n")); +} + +#[test] +fn editorconfig_charset_leaves_a_bomless_utf16_file_alone() { + let f = fixture(); + fs::write(f.root.join(".editorconfig"), "root = true\n[*.txt]\ncharset = latin1\n").unwrap(); + let path = f.root.join("a.txt"); + fs::write(&path, b"a\x00b\x00c\x00d\x00").unwrap(); + + let doc = f.docs.open(&path).unwrap(); + assert_eq!(doc.encoding, "utf-16le"); + f.docs.edit(doc.id, doc.version, change(4, 4, "e")).unwrap(); + f.docs.save(doc.id).unwrap(); + + assert_eq!(fs::read(&path).unwrap(), b"a\x00b\x00c\x00d\x00e\x00"); +} + +#[test] +fn an_external_change_keeps_the_editorconfig_charset_of_an_ascii_file() { + let f = fixture(); + latin_project(&f); + fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap(); + let path = f.root.join("A.java"); + fs::write(&path, b"class A {}\n").unwrap(); + let doc = f.docs.open(&path).unwrap(); + assert_eq!(doc.encoding, "utf-8"); + + std::thread::sleep(std::time::Duration::from_millis(20)); + fs::write(&path, b"class B {}\n").unwrap(); + f.docs.on_disk_changed(std::slice::from_ref(&path)); + + let reloaded = f.docs.snapshot(doc.id).unwrap(); + assert_eq!((reloaded.text.as_str(), reloaded.encoding.as_str()), ("class B {}\n", "utf-8")); +} + +#[test] +fn editorconfig_charset_applies_to_a_native_to_ascii_properties_file() { + let f = fixture(); + let mut defaults = f.docs.file_defaults(); + defaults.native_to_ascii = true; + f.docs.set_file_defaults(defaults); + fs::write(f.root.join(".editorconfig"), "root = true\n[*.properties]\ncharset = latin1\n").unwrap(); + let path = f.root.join("messages.properties"); + fs::write(&path, b"greeting=Ol\\u00e1\n").unwrap(); + + let doc = f.docs.open(&path).unwrap(); + assert_eq!(doc.encoding, "windows-1252", "the escapes are ASCII bytes"); + assert_eq!(f.docs.text_of(&path).as_deref(), Some("greeting=Olá\n")); +} diff --git a/crates/ide-workspace/tests/workspace_edits.rs b/crates/ide-workspace/tests/workspace_edits.rs index be3e33ea1b..1450b04d43 100644 --- a/crates/ide-workspace/tests/workspace_edits.rs +++ b/crates/ide-workspace/tests/workspace_edits.rs @@ -679,3 +679,25 @@ fn replacing_a_directory_symlink_does_not_resolve_later_child_paths_through_its_ assert_eq!(std::fs::read_to_string(link.join("file.txt")).unwrap(), "new file\n"); } } + +#[test] +fn an_overwritten_open_file_keeps_the_editorconfig_charset() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap(); + let path = tmp.path().join("A.java"); + std::fs::write(&path, "class A {}\n").unwrap(); + let docs = documents(); + let mut defaults = docs.file_defaults(); + defaults.project_fallback = "iso-8859-15".into(); + docs.set_file_defaults(defaults); + let doc = docs.open(&path).unwrap(); + assert_eq!(doc.encoding, "utf-8"); + + docs.apply_workspace_edit(&WorkspaceEdit { + files: vec![FileEdit::Create { path: path.clone().into(), overwrite: true }], + ..Default::default() + }) + .unwrap(); + + assert_eq!(docs.snapshot(doc.id).unwrap().encoding, "utf-8"); +} diff --git a/src/editor/core/view/encodingStatus.test.tsx b/src/editor/core/view/encodingStatus.test.tsx index 2725802461..393962c4b7 100644 --- a/src/editor/core/view/encodingStatus.test.tsx +++ b/src/editor/core/view/encodingStatus.test.tsx @@ -133,3 +133,12 @@ it("converts the current text when Convert is chosen", async () => { await waitFor(() => expect(setMeta).toHaveBeenCalledWith({ encoding: "gbk", hasBom: false, dirty: true })); view.unmount(); }); + +it("offers ISO-8859-15, the Latin-9 encoding of legacy Western European projects", async () => { + setEncoding.mockResolvedValue({ encoding: "iso-8859-15", hasBom: false }); + const view = openPicker(meta({ path: "/p/Main.java", readOnly: false })); + choose("ISO-8859-15"); + fireEvent.click(button("Convert")); + expect(setEncoding).toHaveBeenCalledWith(1, "iso-8859-15", false); + view.unmount(); +}); diff --git a/src/platform/editorSettings.ts b/src/platform/editorSettings.ts index 9c90ae8dfc..f0a6b6ffbf 100644 --- a/src/platform/editorSettings.ts +++ b/src/platform/editorSettings.ts @@ -368,5 +368,6 @@ export const ENCODING_CHOICES: ReadonlyArray = [ ["euc-kr", "EUC-KR"], ["windows-1252", "windows-1252"], ["iso-8859-1", "ISO-8859-1"], + ["iso-8859-15", "ISO-8859-15"], ["koi8-r", "KOI8-R"], ];