Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

feat(editor): support transparent native-to-ascii conversion (#537)

l0ng-ai27ed0515e8f9
diff --git a/crates/ide-core/src/editor_settings.rs b/crates/ide-core/src/editor_settings.rs
index 73cc773a4..a478558c6 100644
--- a/crates/ide-core/src/editor_settings.rs
+++ b/crates/ide-core/src/editor_settings.rs
@@ -438,6 +438,8 @@ pub struct EncodingSettings {
pub project: String,
/// Fallback for `.properties` files.
pub properties: String,
+ /// Display properties Unicode escapes as characters and save non-ASCII as escapes.
+ pub native_to_ascii: bool,
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
pub utf8_bom: String,
}
@@ -448,6 +450,7 @@ impl Default for EncodingSettings {
global: "utf-8".into(),
project: "utf-8".into(),
properties: "iso-8859-1".into(),
+ native_to_ascii: false,
utf8_bom: "never".into(),
}
}
diff --git a/crates/ide-host/src/ops/analysis.rs b/crates/ide-host/src/ops/analysis.rs
index 7d693b52e..e40a4edf1 100644
--- a/crates/ide-host/src/ops/analysis.rs
+++ b/crates/ide-host/src/ops/analysis.rs
@@ -39,12 +39,13 @@ fn load(project: &Project, languages: &LanguageRegistry, path: &Path) -> Option<
let snap = project.documents.text_snapshot(doc).ok()?;
return (!snap.large).then_some((snap.language, snap.text));
}
- let loaded = ide_vfs::load_text(path).ok()?;
+ let loaded = project.documents.load_file(path).ok()?;
if loaded.binary || loaded.large || loaded.too_large {
return None;
}
- let language = languages.detect(path, loaded.text.lines().next());
- Some((language, loaded.text))
+ let text = ide_text::normalize_line_endings(&loaded.text).into_owned();
+ let language = languages.detect(path, text.lines().next());
+ Some((language, text))
}
// ---- Inspect Code ----
diff --git a/crates/ide-host/src/ops/doc/commands.rs b/crates/ide-host/src/ops/doc/commands.rs
index aad18b809..aa0f918bb 100644
--- a/crates/ide-host/src/ops/doc/commands.rs
+++ b/crates/ide-host/src/ops/doc/commands.rs
@@ -30,8 +30,15 @@ pub async fn doc_ui_mode(host: &Host, window: &str, path: PathBuf) -> IdeResult<
}
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding label.
-pub fn doc_set_encoding(host: &Host, window: &str, doc: DocId, encoding: String, reload: bool) -> IdeResult<String> {
- host.project(window)?.documents.set_encoding(doc, &encoding, reload)
+pub async fn doc_set_encoding(
+ host: &Host,
+ window: &str,
+ doc: DocId,
+ encoding: String,
+ reload: bool,
+) -> IdeResult<String> {
+ let project = host.project(window)?;
+ host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
}
pub fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_ending: LineEnding) -> IdeResult<()> {
@@ -117,7 +124,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("doc_open_virtual", |c| async move { doc_open_virtual(&c.host, &c.window, c.arg("uri")?).await });
d.add("doc_ui_mode", |c| async move { doc_ui_mode(&c.host, &c.window, c.arg("path")?).await });
d.add("doc_set_encoding", |c| async move {
- doc_set_encoding(&c.host, &c.window, c.arg("doc")?, c.arg("encoding")?, c.arg("reload")?)
+ doc_set_encoding(&c.host, &c.window, c.arg("doc")?, c.arg("encoding")?, c.arg("reload")?).await
});
d.add("doc_set_line_ending", |c| async move {
doc_set_line_ending(&c.host, &c.window, c.arg("doc")?, c.arg("lineEnding")?)
diff --git a/crates/ide-host/src/ops/project.rs b/crates/ide-host/src/ops/project.rs
index b4ee7b745..7055d2e50 100644
--- a/crates/ide-host/src/ops/project.rs
+++ b/crates/ide-host/src/ops/project.rs
@@ -146,6 +146,14 @@ pub fn set_settings(
}
}
let affected = || if project_scope { current.iter().cloned().collect() } else { host.projects() };
+ if key == "editor" || key == "editor.encodings" || key == "editor.encodings.nativeToAscii" {
+ let affected = affected();
+ host.runtime.spawn_blocking(move || {
+ for project in affected {
+ project.documents.reload_properties();
+ }
+ });
+ }
// File type associations re-detect open documents (off the command thread).
if key == "files" || key.starts_with("files.fileType") {
let affected = affected();
diff --git a/crates/ide-host/src/ops/search.rs b/crates/ide-host/src/ops/search.rs
index 40122b0a0..ac2de1168 100644
--- a/crates/ide-host/src/ops/search.rs
+++ b/crates/ide-host/src/ops/search.rs
@@ -75,7 +75,7 @@ pub async fn start(
&query,
Some(&filter),
Some(&literals),
- &|p| documents.text_of(p),
+ &|p| documents.search_text_of(p),
&cancel,
&|mut file| {
if dir != &root {
diff --git a/crates/ide-host/src/ops/syntax.rs b/crates/ide-host/src/ops/syntax.rs
index 027444b97..d4b5033ce 100644
--- a/crates/ide-host/src/ops/syntax.rs
+++ b/crates/ide-host/src/ops/syntax.rs
@@ -124,7 +124,7 @@ pub async fn syntax_identifiers_in_files(
let snap = project.documents.text_snapshot(doc).ok()?;
return (!snap.large).then_some((snap.language, Some((doc, snap.version)), snap.text));
}
- let text = ide_vfs::load_text(path).ok()?.text;
+ let text = project.text_of(path).ok()?;
let first_line = text.lines().next();
Some((languages.detect(path, first_line), None, text))
};
diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs
index 964b130f6..754f15348 100644
--- a/crates/ide-host/src/ops/vcs/commands.rs
+++ b/crates/ide-host/src/ops/vcs/commands.rs
@@ -187,10 +187,13 @@ pub async fn vcs_branch_info(host: &Host, window: &str, repo: Option<PathBuf>) -
}
/// Gutter change markers for a file, computed against its current (unsaved) text.
-pub fn vcs_line_hunks(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<LineHunk>> {
+pub async fn vcs_line_hunks(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<LineHunk>> {
let project = host.project(window)?;
- let text = project.text_of(&path)?;
- project.with_repo_of(&path, |r| r.line_hunks(&path, &text, false, project.vcs_encoding(&path, None)?))
+ blocking(move || {
+ let text = project.text_of(&path)?;
+ project.with_repo_of(&path, |r| r.line_hunks(&path, &text, false, project.vcs_encoding(&path, None)?))
+ })
+ .await
}
pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<String>) -> IdeResult<Option<String>> {
@@ -210,8 +213,8 @@ pub async fn vcs_blame(
) -> IdeResult<Vec<BlameLine>> {
let project = host.project(window)?;
// An explicit text wins (merge view annotates its side panes, not the worktree).
- let text = text.or_else(|| project.documents.text_of(&path));
blocking(move || {
+ let text = text.or_else(|| project.documents.text_of(&path));
project.with_repo_of(&path, |r| {
r.blame(&path, text.as_deref(), revision.as_deref(), project.vcs_encoding(&path, revision.as_deref())?)
})
@@ -510,14 +513,17 @@ pub fn vcs_diff_hunks(_host: &Host, _window: &str, old_text: String, new_text: S
/// Stages only the selected hunks of a file's working-tree changes.
/// Indices refer to `vcs_diff_hunks(index_text, worktree_text)`.
-pub fn vcs_stage_hunks(host: &Host, window: &str, path: PathBuf, hunks: Vec<u32>) -> IdeResult<()> {
+pub async fn vcs_stage_hunks(host: &Host, window: &str, path: PathBuf, hunks: Vec<u32>) -> IdeResult<()> {
let project = host.project(window)?;
- let encoding = project.vcs_encoding(&path, Some(":0"))?;
- let current = ide_vfs::load_text_as(&path, encoding.name())?.text;
- project.with_repo_of(&path, |r| {
- let selected: Vec<usize> = hunks.iter().map(|&h| h as usize).collect();
- r.stage_hunks(&path, &current, &selected, encoding)
+ blocking(move || {
+ let encoding = project.vcs_encoding(&path, Some(":0"))?;
+ let current = project.documents.load_file_as(&path, encoding.charset.name())?.text;
+ project.with_repo_of(&path, |r| {
+ let selected: Vec<usize> = hunks.iter().map(|&h| h as usize).collect();
+ r.stage_hunks(&path, &current, &selected, encoding)
+ })
})
+ .await
}
/// Clones a repository (Get from VCS). Works without an open project.
@@ -874,7 +880,7 @@ pub async fn vcs_write_patch(_host: &Host, _window: &str, path: PathBuf, patch:
pub(crate) fn register(d: &mut Dispatcher) {
d.add("vcs_roots", |c| async move { vcs_roots(&c.host, &c.window) });
d.add("vcs_branch_info", |c| async move { vcs_branch_info(&c.host, &c.window, c.arg("repo")?).await });
- d.add("vcs_line_hunks", |c| async move { vcs_line_hunks(&c.host, &c.window, c.arg("path")?) });
+ d.add("vcs_line_hunks", |c| async move { vcs_line_hunks(&c.host, &c.window, c.arg("path")?).await });
d.add("vcs_file_at", |c| async move { vcs_file_at(&c.host, &c.window, c.arg("path")?, c.arg("rev")?).await });
d.add("vcs_blame", |c| async move {
vcs_blame(&c.host, &c.window, c.arg("path")?, c.arg("text")?, c.arg("revision")?).await
@@ -958,7 +964,10 @@ pub(crate) fn register(d: &mut Dispatcher) {
"vcs_diff_hunks",
|c| async move { Ok(vcs_diff_hunks(&c.host, &c.window, c.arg("oldText")?, c.arg("newText")?)) },
);
- d.add("vcs_stage_hunks", |c| async move { vcs_stage_hunks(&c.host, &c.window, c.arg("path")?, c.arg("hunks")?) });
+ d.add(
+ "vcs_stage_hunks",
+ |c| async move { vcs_stage_hunks(&c.host, &c.window, c.arg("path")?, c.arg("hunks")?).await },
+ );
d.add("vcs_clone", |c| async move {
vcs_clone(&c.host, &c.window, c.arg("request")?, c.arg("url")?, c.arg("dest")?, c.sender("onOutput")?).await
});
diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs
index 8fadce6ae..9683307eb 100644
--- a/crates/ide-host/src/project.rs
+++ b/crates/ide-host/src/project.rs
@@ -689,7 +689,7 @@ impl Project {
limit: q.limit,
};
let filter = |rel: &str| q.languages.contains(&self.languages.detect(&root.join(rel), None));
- match ide_search::files_with_word(&root, &query, Some(&filter), &|p| self.documents.text_of(p), cancel) {
+ match ide_search::files_with_word(&root, &query, Some(&filter), &|p| self.documents.search_text_of(p), cancel) {
Ok(found) => ide_lsp::CandidateFiles { files: found.files, limit_hit: found.limit_hit },
Err(e) => {
tracing::debug!("reference candidates: {}", e.message);
@@ -747,7 +747,17 @@ impl Project {
}
/// Use the open document's selected encoding, or the same detection/settings as opening it.
- pub fn vcs_encoding(&self, path: &Path, rev: Option<&str>) -> IdeResult<&'static encoding_rs::Encoding> {
+ pub fn vcs_encoding(&self, path: &Path, rev: Option<&str>) -> IdeResult<ide_vcs::TextEncoding> {
+ let charset = self.file_encoding(path, rev)?;
+ let encoding = ide_vcs::TextEncoding::from(charset);
+ Ok(if self.documents.native_to_ascii_for(path) {
+ encoding.with_ascii_conversion(ide_vfs::decode_properties_escapes, ide_vfs::encode_properties_ascii)
+ } else {
+ encoding
+ })
+ }
+
+ fn file_encoding(&self, path: &Path, rev: Option<&str>) -> IdeResult<&'static encoding_rs::Encoding> {
if let Some(id) = self.documents.by_path(path) {
let info = self.documents.snapshot(id)?;
return encoding_rs::Encoding::for_label(info.encoding.as_bytes())
@@ -768,7 +778,7 @@ impl Project {
pub fn text_of(&self, path: &Path) -> IdeResult<String> {
match self.documents.text_of(path) {
Some(text) => Ok(text),
- None => Ok(ide_vfs::load_text_with_fallback(path, self.documents.file_defaults().fallback_for(path))?.text),
+ None => Ok(ide_text::normalize_line_endings(&self.documents.load_file(path)?.text).into_owned()),
}
}
}
diff --git a/crates/ide-host/tests/properties.rs b/crates/ide-host/tests/properties.rs
new file mode 100644
index 000000000..a9760fe4c
--- /dev/null
+++ b/crates/ide-host/tests/properties.rs
@@ -0,0 +1,184 @@
+use ide_core::{ChangeSet, NullSink, RequestId, TextChange};
+use ide_host::{
+ Host, HostConfig,
+ ops::{doc, search, vcs},
+};
+use ide_search::{SearchQuery, SearchScope};
+use std::{
+ path::{Path, PathBuf},
+ process::Command,
+ sync::{Arc, Mutex},
+ 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));
+}
+
+fn host(base: &Path) -> Host {
+ Host::new(HostConfig {
+ config_dir: base.join("config"),
+ data_dir: base.join("data"),
+ languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
+ syntax: Arc::default(),
+ sink_for: Box::new(|_| Arc::new(NullSink)),
+ owner: |w| w,
+ runtime: tokio::runtime::Handle::current(),
+ project_environment: false,
+ })
+}
+
+async fn find(host: &Host, paths: Vec<PathBuf>, pattern: &str) -> Vec<ide_search::FileMatches> {
+ let files = Arc::new(Mutex::new(Vec::new()));
+ let found = files.clone();
+ search::start(
+ host,
+ "main",
+ RequestId(519),
+ SearchQuery {
+ pattern: pattern.into(),
+ is_regex: false,
+ case_sensitive: true,
+ whole_word: false,
+ include: Vec::new(),
+ exclude: Vec::new(),
+ scope: SearchScope::Files { paths: paths.into_iter().map(Into::into).collect() },
+ max_matches: 0,
+ context: Default::default(),
+ },
+ Arc::new(move |event| {
+ if let search::SearchEvent::File { file } = event {
+ found.lock().unwrap().push(file);
+ }
+ }),
+ )
+ .await
+ .unwrap();
+ Arc::try_unwrap(files).unwrap().into_inner().unwrap()
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn properties_search_git_and_document_coordinates_agree() {
+ let temp = tempfile::tempdir().unwrap();
+ let base = dunce::canonicalize(temp.path()).unwrap();
+ let root = base.join("project");
+ std::fs::create_dir(&root).unwrap();
+ git(&root, &["init", "-b", "main"]);
+ git(&root, &["config", "user.name", "Test"]);
+ git(&root, &["config", "user.email", "[email protected]"]);
+ git(&root, &["config", "commit.gpgsign", "false"]);
+ git(&root, &["config", "core.autocrlf", "false"]);
+ let path = root.join("messages.properties");
+ let original = "hello=\\u4f60\\u597d\\uD83D\\uDE00target\nsecond=unchanged\nescaped=line\\u000Alogical\n";
+ std::fs::write(&path, original).unwrap();
+ let host = host(&base);
+ 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;
+ }
+ git(&root, &["add", "."]);
+ git(&root, &["commit", "-m", "Properties"]);
+ let mut defaults = project.documents.file_defaults();
+ defaults.native_to_ascii = true;
+ project.documents.set_file_defaults(defaults);
+ let displayed = "hello=你好😀target\nsecond=unchanged\nescaped=line\\u000Alogical\n";
+ assert_eq!(project.text_of(&path).unwrap(), displayed);
+ let closed = find(&host, vec![path.clone()], "target").await;
+ let closed_json = serde_json::to_value(&closed).unwrap();
+ let opened = doc::open(&host, "main", path.clone()).await.unwrap();
+ assert_eq!(opened.text, displayed);
+ assert_eq!(serde_json::to_value(find(&host, vec![path.clone()], "target").await).unwrap(), closed_json);
+ assert_eq!(closed[0].matches[0].ranges, vec![(10, 16)]);
+ assert_eq!(find(&host, vec![path.clone()], "你好").await[0].matches.len(), 1);
+ assert!(find(&host, vec![path.clone()], r"\u4f60").await.is_empty());
+ assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap().is_empty());
+ assert_eq!(vcs::vcs_file_at(&host, "main", path.clone(), None).await.unwrap().as_deref(), Some(displayed));
+ assert!(vcs::vcs_blame(&host, "main", path.clone(), None, None).await.unwrap().iter().all(|l| l.author == "Test"));
+ doc::edit(
+ &host,
+ "main",
+ opened.id,
+ opened.version,
+ ChangeSet { changes: vec![TextChange { from: 10, to: 16, insert: "世界".into() }] },
+ )
+ .unwrap();
+ let hunks = vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap();
+ assert_eq!(hunks.len(), 1);
+ assert_eq!(hunks[0].old_text, "hello=你好😀target\n");
+ doc::save(&host, "main", opened.id).await.unwrap();
+ let saved = std::fs::read(&path).unwrap();
+ assert!(saved.is_ascii());
+ assert!(String::from_utf8(saved.clone()).unwrap().contains(r"\u4F60\u597D\uD83D\uDE00\u4E16\u754C"));
+ vcs::vcs_stage_hunks(&host, "main", path.clone(), vec![0]).await.unwrap();
+ let repo = ide_vcs::Repo::discover(&root).unwrap().unwrap();
+ assert_eq!(repo.file_bytes_at(&path, Some(":0")).unwrap().unwrap(), saved);
+ repo.unstage(std::slice::from_ref(&path)).unwrap();
+ // Line staging must match the decoded base even when Git stores lowercase escapes.
+ let patch = ide_vcs::build_partial_patch("messages.properties", displayed, &project.text_of(&path).unwrap(), &[0]);
+ repo.stage_patch(&patch, &|p| project.vcs_encoding(p, Some(":0"))).unwrap();
+ assert_eq!(repo.file_bytes_at(&path, Some(":0")).unwrap().unwrap(), saved);
+ repo.unstage(std::slice::from_ref(&path)).unwrap();
+ let snap = project.documents.snapshot(opened.id).unwrap();
+ project.documents.replace_all(opened.id, displayed).unwrap();
+ doc::save(&host, "main", opened.id).await.unwrap();
+ assert!(project.documents.snapshot(opened.id).unwrap().version > snap.version);
+ assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap().is_empty());
+ // Partial commits identify hunks in displayed line coordinates as well.
+ let partial_text = displayed.replace("target", "世界").replace("logical", "changed");
+ project.documents.replace_all(opened.id, &partial_text).unwrap();
+ doc::save(&host, "main", opened.id).await.unwrap();
+ let hunks = ide_vcs::diff_hunks(displayed, &partial_text);
+ assert_eq!(hunks.len(), 2);
+ let selected = &hunks[0];
+ let options = ide_vcs::CommitOptions {
+ partial: vec![ide_vcs::PartialCommitFile {
+ path: path.clone().into(),
+ hunks: vec![ide_vcs::HunkRange {
+ start: selected.start,
+ lines: selected.lines,
+ old_start: selected.old_start,
+ old_lines: selected.old_lines,
+ }],
+ }],
+ ..Default::default()
+ };
+ repo.commit_with("Selected properties change", &options, &|p| project.vcs_encoding(p, None)).unwrap();
+ let head = vcs::vcs_file_at(&host, "main", path.clone(), None).await.unwrap().unwrap();
+ assert_eq!(head, displayed.replace("target", "世界"));
+ assert!(repo.file_bytes_at(&path, None).unwrap().unwrap().is_ascii());
+ let closed_path = root.join("closed.properties");
+ std::fs::write(&closed_path, r"value=\u4F60\u597D\uD83D\uDE00target").unwrap();
+ let query = SearchQuery {
+ pattern: "target".into(),
+ is_regex: false,
+ case_sensitive: true,
+ whole_word: false,
+ include: Vec::new(),
+ exclude: Vec::new(),
+ scope: SearchScope::Files { paths: vec![closed_path.clone().into()] },
+ max_matches: 0,
+ context: Default::default(),
+ };
+ search::replace_in_files(
+ &host,
+ "main",
+ RequestId(520),
+ query,
+ "世界".into(),
+ false,
+ vec![ide_search::ReplaceTarget {
+ path: closed_path.clone().into(),
+ only: Some(vec![ide_core::Pos { line: 0, col: 10 }]),
+ }],
+ ide_host::ops::Channel::new(|_| {}),
+ )
+ .await
+ .unwrap();
+ assert_eq!(std::fs::read_to_string(&closed_path).unwrap(), r"value=\u4F60\u597D\uD83D\uDE00\u4E16\u754C");
+ assert!(project.documents.by_path(&closed_path).is_none());
+ host.close_project("main");
+}
diff --git a/crates/ide-host/tests/rpc.rs b/crates/ide-host/tests/rpc.rs
index ade529267..b3d51c759 100644
--- a/crates/ide-host/tests/rpc.rs
+++ b/crates/ide-host/tests/rpc.rs
@@ -257,3 +257,62 @@ async fn local_deployment_runs_on_the_project_host() {
assert!(!target.join("local.txt").exists());
invoke(&peer, "close_project", json!({})).await.unwrap();
}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn properties_conversion_through_remote_dispatch_without_a_remote_host() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().join("properties-project");
+ std::fs::create_dir(&root).unwrap();
+ let path = root.join("messages.properties");
+ std::fs::write(&path, r"value=\u4F60\u597D\uD83D\uDE00!").unwrap();
+ let peer_slot = Arc::new(OnceLock::new());
+ let host = Arc::new(Host::new(HostConfig {
+ config_dir: tmp.path().join("config"),
+ data_dir: tmp.path().join("data"),
+ languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
+ syntax: Arc::default(),
+ sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
+ owner: |w| w,
+ runtime: tokio::runtime::Handle::current(),
+ project_environment: false,
+ }));
+ let (client_io, server_io) = tokio::io::duplex(1 << 20);
+ let (sr, sw) = tokio::io::split(server_io);
+ tokio::spawn(rpc::serve(host, Dispatcher::standard(), peer_slot, sr, sw));
+ let (cr, cw) = tokio::io::split(client_io);
+ let peer = Peer::connect(cr, cw, Arc::new(Client::default()));
+ invoke(&peer, "open_project", json!({"path":root})).await.unwrap();
+ let settings = invoke(&peer, "settings_get", json!({})).await.unwrap();
+ assert_eq!(settings["editor"]["encodings"]["nativeToAscii"], false);
+ let opened = invoke(&peer, "doc_open", json!({"path":path})).await.unwrap();
+ let doc = opened["id"].clone();
+ invoke(&peer, "settings_set", json!({"scope":"project", "key":"editor.encodings.nativeToAscii", "value":"true"}))
+ .await
+ .unwrap();
+ let mut snap = Value::Null;
+ for _ in 0..500 {
+ snap = invoke(&peer, "doc_snapshot", json!({"doc":doc})).await.unwrap();
+ if snap["text"] == "value=你好😀!" {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ assert_eq!(snap["text"], "value=你好😀!");
+ assert_eq!(snap["dirty"], false);
+ invoke(
+ &peer,
+ "doc_edit",
+ json!({"doc":doc, "baseVersion":snap["version"],
+ "changes":{"changes":[{"from":10,"to":11,"insert":"界"}]}}),
+ )
+ .await
+ .unwrap();
+ invoke(&peer, "doc_save", json!({"doc":doc})).await.unwrap();
+ assert_eq!(std::fs::read_to_string(&path).unwrap(), r"value=\u4F60\u597D\uD83D\uDE00\u754C");
+ invoke(&peer, "doc_set_encoding", json!({"doc":doc,"encoding":"utf-8","reload":true})).await.unwrap();
+ let reloaded = invoke(&peer, "doc_snapshot", json!({"doc":doc})).await.unwrap();
+ assert_eq!(reloaded["text"], "value=你好😀界");
+ assert_eq!(reloaded["dirty"], false);
+ invoke(&peer, "close_project", json!({})).await.unwrap();
+ peer.kill();
+}
diff --git a/crates/ide-host/tests/vcs_encoding.rs b/crates/ide-host/tests/vcs_encoding.rs
index 65104008a..7bb1442ab 100644
--- a/crates/ide-host/tests/vcs_encoding.rs
+++ b/crates/ide-host/tests/vcs_encoding.rs
@@ -53,7 +53,7 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
let mut defaults = project.documents.file_defaults();
defaults.project_fallback = "windows-1252".into();
project.documents.set_file_defaults(defaults);
- assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).unwrap().is_empty());
+ assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap().is_empty());
let from = old.find("value = 1").unwrap() + "value = ".len();
let offset = old[..from].encode_utf16().count() as u32;
project
@@ -64,12 +64,12 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
ChangeSet { changes: vec![TextChange { from: offset, to: offset + 1, insert: "2".into() }] },
)
.unwrap();
- let hunks = vcs::vcs_line_hunks(&host, "main", path.clone()).unwrap();
+ let hunks = vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap();
assert_eq!(hunks.len(), 1);
assert_eq!((hunks[0].start, hunks[0].lines), (3, 1));
assert_eq!(hunks[0].old_text, " int value = 1;\n");
project.documents.save(doc.id).unwrap();
- vcs::vcs_stage_hunks(&host, "main", path.clone(), vec![0]).unwrap();
+ vcs::vcs_stage_hunks(&host, "main", path.clone(), vec![0]).await.unwrap();
let repo = ide_vcs::Repo::discover(&root).unwrap().unwrap();
assert_eq!(
repo.file_bytes_at(&path, Some(":0")).unwrap().unwrap(),
@@ -95,7 +95,7 @@ async fn gbk_document_gutter_diff_stage_and_rollback_share_encoding() {
.unwrap();
project.documents.save(doc.id).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), original);
- assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).unwrap().is_empty());
+ assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap().is_empty());
assert!(vcs::vcs_blame(&host, "main", path.clone(), None, None).await.unwrap().iter().all(|l| l.author == "Test"));
// Missing working files still use configured encoding for historical content.
project.documents.close(doc.id);
diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs
index 6059b2e9c..6777005fd 100644
--- a/crates/ide-vcs/src/lib.rs
+++ b/crates/ide-vcs/src/lib.rs
@@ -2,12 +2,12 @@
//! writes (commit, checkout, push/pull, stash, merge) shell out to `git` so
//! hooks, credentials and signing behave exactly as on the command line.
-use encoding_rs::Encoding;
use ide_core::ignored::IgnoredNames;
use ide_core::{CancellationToken, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
+pub use text_encoding::TextEncoding;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -540,7 +540,13 @@ impl Repo {
}
/// Content of `path` at `rev` (default HEAD); `None` if absent there.
/// `rev` may be any revision git understands, or `":"` / `":0"` for the index.
- pub fn file_at(&self, path: &Path, rev: Option<&str>, encoding: &'static Encoding) -> IdeResult<Option<String>> {
+ pub fn file_at(
+ &self,
+ path: &Path,
+ rev: Option<&str>,
+ encoding: impl Into<TextEncoding>,
+ ) -> IdeResult<Option<String>> {
+ let encoding = encoding.into();
let rel = self.rel_path(path)?;
let repo = self.gix()?;
Ok(repo::blob_at(&repo, &rel, rev.unwrap_or("HEAD"))?.map(|b| text_encoding::decode(&b, encoding).into_owned()))
@@ -555,8 +561,9 @@ impl Repo {
path: &Path,
current: &str,
selected: &[usize],
- encoding: &'static Encoding,
+ encoding: impl Into<TextEncoding>,
) -> IdeResult<()> {
+ let encoding = encoding.into();
write::stage_hunks(self, path, current, selected, encoding)
}
/// Hunks of `current_text` against HEAD (or the index when `against_index`).
@@ -570,8 +577,9 @@ impl Repo {
path: &Path,
current_text: &str,
against_index: bool,
- encoding: &'static Encoding,
+ encoding: impl Into<TextEncoding>,
) -> IdeResult<Vec<LineHunk>> {
+ let encoding = encoding.into();
let Ok(rel) = self.rel_path(path) else { return Ok(Vec::new()) };
if rel.is_empty() || rel == ".git" || rel.starts_with(".git/") {
return Ok(Vec::new());
@@ -598,8 +606,9 @@ impl Repo {
path: &Path,
current_text: Option<&str>,
revision: Option<&str>,
- encoding: &'static Encoding,
+ encoding: impl Into<TextEncoding>,
) -> IdeResult<Vec<BlameLine>> {
+ let encoding = encoding.into();
write::blame(self, path, current_text, revision, encoding)
}
/// Commits newest-first in topological order (children before parents).
@@ -631,7 +640,8 @@ impl Repo {
}
/// Unified diff of a file: index↔worktree (`staged == false`, untracked files diff
/// against /dev/null) or HEAD↔index (`staged == true`). Empty when unchanged.
- pub fn diff_text(&self, path: &Path, staged: bool, encoding: &'static Encoding) -> IdeResult<String> {
+ pub fn diff_text(&self, path: &Path, staged: bool, encoding: impl Into<TextEncoding>) -> IdeResult<String> {
+ let encoding = encoding.into();
write::diff_text(self, path, staged, encoding)
}
@@ -650,8 +660,12 @@ impl Repo {
}
/// Applies a unified-diff patch to the index (partial staging of hunks/lines).
/// Zero-context patches (see [`build_partial_patch`]) are accepted.
- pub fn stage_patch(&self, patch: &str, encoding: &dyn Fn(&Path) -> IdeResult<&'static Encoding>) -> IdeResult<()> {
- write::stage_patch(self, patch, encoding)
+ pub fn stage_patch<E: Into<TextEncoding>>(
+ &self,
+ patch: &str,
+ encoding: &dyn Fn(&Path) -> IdeResult<E>,
+ ) -> IdeResult<()> {
+ write::stage_patch(self, patch, &|path| encoding(path).map(Into::into))
}
/// Discards unstaged changes: tracked paths are restored from the index (staged
/// changes are kept), untracked files and directories are deleted.
@@ -662,16 +676,16 @@ impl Repo {
/// `amend` keeps the previous message.
pub fn commit(&self, message: &str, amend: bool, sign_off: bool) -> IdeResult<String> {
let options = CommitOptions { amend, sign_off, author: None, run_hooks: true, partial: Vec::new() };
- write::commit(self, message, &options, &|_| Ok(encoding_rs::UTF_8))
+ write::commit(self, message, &options, &|_| Ok(encoding_rs::UTF_8.into()))
}
/// Commits with the Commit Options popup's choices.
- pub fn commit_with(
+ pub fn commit_with<E: Into<TextEncoding>>(
&self,
message: &str,
options: &CommitOptions,
- encoding: &dyn Fn(&Path) -> IdeResult<&'static Encoding>,
+ encoding: &dyn Fn(&Path) -> IdeResult<E>,
) -> IdeResult<String> {
- write::commit(self, message, options, encoding)
+ write::commit(self, message, options, &|path| encoding(path).map(Into::into))
}
/// Switches to `branch`. With `create`, creates it at HEAD. Without, a remote branch
/// (`origin/x`) gets a local tracking branch and any other revision is checked out
@@ -925,7 +939,8 @@ impl Repo {
}
/// The versions of a conflicted file with the user's work as `ours`, as IDEA's merge
/// dialog shows them (sides swapped during a rebase).
- pub fn merge_versions(&self, path: &Path, encoding: &'static Encoding) -> IdeResult<MergeVersions> {
+ pub fn merge_versions(&self, path: &Path, encoding: impl Into<TextEncoding>) -> IdeResult<MergeVersions> {
+ let encoding = encoding.into();
let (base, ours, theirs) = self.conflict_versions(path, encoding)?;
let sides = self.merge_sides()?;
let (ours, theirs) = if sides.reversed { (theirs, ours) } else { (ours, theirs) };
@@ -939,8 +954,9 @@ impl Repo {
pub fn conflict_versions(
&self,
path: &Path,
- encoding: &'static Encoding,
+ encoding: impl Into<TextEncoding>,
) -> IdeResult<(Option<String>, Option<String>, Option<String>)> {
+ let encoding = encoding.into();
let rel = self.rel_path(path)?;
let repo = self.gix()?;
let stage = |n: u8| -> IdeResult<Option<String>> {
diff --git a/crates/ide-vcs/src/patch.rs b/crates/ide-vcs/src/patch.rs
index 28f3869e8..5f40ae750 100644
--- a/crates/ide-vcs/src/patch.rs
+++ b/crates/ide-vcs/src/patch.rs
@@ -349,7 +349,7 @@ fn lossless_diff(r: &Repo, args: &[&str], env: &[(&str, &OsStr)]) -> IdeResult<S
pub(crate) fn encode_text_patch(
r: &Repo,
patch: &str,
- encoding: &dyn Fn(&std::path::Path) -> IdeResult<&'static encoding_rs::Encoding>,
+ encoding: &dyn Fn(&std::path::Path) -> IdeResult<crate::TextEncoding>,
) -> IdeResult<Vec<u8>> {
let mut out = Vec::new();
let mut header = String::new();
@@ -379,6 +379,52 @@ pub(crate) fn encode_text_patch(
Ok(out)
}
+/// Apply displayed-text line selections in a temporary UTF-8 index, then
+/// serialize the result. Literal escape spelling in the real index must not
+/// prevent a selected patch from matching its decoded base.
+pub(crate) fn stage_converted_patch(
+ r: &Repo,
+ patch: &str,
+ encoding: &dyn Fn(&std::path::Path) -> IdeResult<crate::TextEncoding>,
+) -> IdeResult<()> {
+ use crate::text_encoding::{decode, encode, has_bom};
+ let tmp = TempIndex::new(r);
+ let env = tmp.env();
+ let index = r.git_dir.join("index");
+ if index.exists() {
+ std::fs::copy(index, &tmp.0)?;
+ } else {
+ run_env(r.root(), &["read-tree", "--empty"], None, &env)?;
+ }
+ let mut files = Vec::new();
+ for file in parse_patch(patch) {
+ let path = r.abs_path(&file.path);
+ let enc = encoding(&path)?;
+ let original = r.file_bytes_at(&path, Some(":0"))?;
+ let bom = original.as_ref().is_some_and(|bytes| has_bom(bytes, enc));
+ if let Some(original) = original {
+ crate::write::write_index_blob(r, &file.path, decode(&original, enc).as_bytes(), &env)?;
+ }
+ files.push((file.path, enc, bom));
+ }
+ run_env(
+ r.root(),
+ &["apply", "--cached", "--unidiff-zero", "--whitespace=nowarn", "--recount", "-"],
+ Some(patch.as_bytes()),
+ &env,
+ )?;
+ for (rel, enc, bom) in files {
+ let staged = cli::run_raw_env(r.root(), &["show", &format!(":0:{rel}")], None, &env)?;
+ if staged.code == Some(0) {
+ let text = std::str::from_utf8(&staged.stdout).map_err(|e| IdeError::invalid(e.to_string()))?;
+ crate::write::write_index_blob(r, &rel, &encode(text, enc, bom)?, &[])?;
+ } else {
+ run(r.root(), &["--literal-pathspecs", "update-index", "--force-remove", "--", &rel], None)?;
+ }
+ }
+ Ok(())
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ide-vcs/src/text_encoding.rs b/crates/ide-vcs/src/text_encoding.rs
index 9d23171a4..038256a95 100644
--- a/crates/ide-vcs/src/text_encoding.rs
+++ b/crates/ide-vcs/src/text_encoding.rs
@@ -3,23 +3,77 @@ use encoding_rs::{Encoding, UTF_8, UTF_16BE, UTF_16LE};
use ide_core::{IdeError, IdeResult};
use std::borrow::Cow;
-pub(crate) fn has_bom(bytes: &[u8], encoding: &'static Encoding) -> bool {
- Encoding::for_bom(bytes).is_some_and(|(enc, _)| enc == encoding)
+/// File charset plus an optional reversible ASCII representation (for properties).
+/// The host supplies conversion functions so Git and documents share one codec.
+#[derive(Clone, Copy)]
+pub struct TextEncoding {
+ pub charset: &'static Encoding,
+ ascii_conversion: Option<AsciiConversion>,
}
-pub(crate) fn decode<'a>(bytes: &'a [u8], encoding: &'static Encoding) -> Cow<'a, str> {
+#[derive(Clone, Copy)]
+struct AsciiConversion {
+ decode: fn(&str) -> String,
+ encode: fn(&str) -> String,
+}
+
+impl From<&'static Encoding> for TextEncoding {
+ fn from(charset: &'static Encoding) -> Self {
+ Self { charset, ascii_conversion: None }
+ }
+}
+
+impl TextEncoding {
+ pub(crate) fn display_text(self, text: &str) -> String {
+ match self.ascii_conversion {
+ Some(conversion) => (conversion.decode)(text),
+ None => text.to_owned(),
+ }
+ }
+
+ pub(crate) fn has_ascii_conversion(self) -> bool {
+ self.ascii_conversion.is_some()
+ }
+
+ pub fn with_ascii_conversion(mut self, decode: fn(&str) -> String, encode: fn(&str) -> String) -> Self {
+ self.ascii_conversion = Some(AsciiConversion { decode, encode });
+ self
+ }
+}
+
+pub(crate) fn has_bom(bytes: &[u8], encoding: TextEncoding) -> bool {
+ Encoding::for_bom(bytes).is_some_and(|(enc, _)| enc == encoding.charset)
+}
+
+pub(crate) fn decode_raw<'a>(bytes: &'a [u8], encoding: TextEncoding) -> Cow<'a, str> {
let body = match Encoding::for_bom(bytes) {
- Some((enc, len)) if enc == encoding => &bytes[len..],
+ Some((enc, len)) if enc == encoding.charset => &bytes[len..],
_ => bytes,
};
- encoding.decode_without_bom_handling(body).0
+ if encoding.ascii_conversion.is_some() && body.is_ascii() {
+ Cow::Borrowed(std::str::from_utf8(body).expect("ASCII"))
+ } else {
+ encoding.charset.decode_without_bom_handling(body).0
+ }
}
-pub(crate) fn is_binary(bytes: &[u8], encoding: &'static Encoding) -> bool {
- encoding != UTF_16LE && encoding != UTF_16BE && bytes.contains(&0)
+pub(crate) fn decode<'a>(bytes: &'a [u8], encoding: TextEncoding) -> Cow<'a, str> {
+ let text = decode_raw(bytes, encoding);
+ match encoding.ascii_conversion {
+ Some(conversion) => Cow::Owned((conversion.decode)(&text)),
+ None => text,
+ }
}
-pub(crate) fn encode(text: &str, encoding: &'static Encoding, bom: bool) -> IdeResult<Vec<u8>> {
+pub(crate) fn is_binary(bytes: &[u8], encoding: TextEncoding) -> bool {
+ encoding.charset != UTF_16LE && encoding.charset != UTF_16BE && bytes.contains(&0)
+}
+
+pub(crate) fn encode(text: &str, encoding: TextEncoding, bom: bool) -> IdeResult<Vec<u8>> {
+ if let Some(conversion) = encoding.ascii_conversion {
+ return Ok((conversion.encode)(text).into_bytes());
+ }
+ let encoding = encoding.charset;
let mut out = Vec::new();
if encoding == UTF_16LE || encoding == UTF_16BE {
let le = encoding == UTF_16LE;
diff --git a/crates/ide-vcs/src/write.rs b/crates/ide-vcs/src/write.rs
index 535be279d..0b45d3c8c 100644
--- a/crates/ide-vcs/src/write.rs
+++ b/crates/ide-vcs/src/write.rs
@@ -1,5 +1,6 @@
//! Operations delegated to the git CLI (all writes, plus blame and textual diffs).
+use crate::TextEncoding;
use crate::cli::{self, run};
use crate::repo::{gx, resolve};
use crate::text_encoding::{decode, encode, has_bom, is_binary};
@@ -7,7 +8,6 @@ use crate::{
BlameLine, CheckoutMode, CheckoutOptions, CheckoutOutcome, CommitOptions, DeletedBranch, DivergedLocal,
PushBranchOptions, Repo,
};
-use encoding_rs::Encoding;
use gix::bstr::{BStr, ByteSlice};
use ide_core::{CancellationToken, IdeError, IdeResult};
use std::path::{Path, PathBuf};
@@ -46,7 +46,7 @@ pub(crate) fn blame(
path: &Path,
current_text: Option<&str>,
revision: Option<&str>,
- encoding: &'static Encoding,
+ encoding: TextEncoding,
) -> IdeResult<Vec<BlameLine>> {
let rel = r.rel_path(path)?;
let revision = match revision {
@@ -59,7 +59,11 @@ pub(crate) fn blame(
Err(error) => return Err(error.into()),
};
let text = current_text.map(str::to_owned).unwrap_or_else(|| decode(&disk, encoding).into_owned());
+ if encoding.has_ascii_conversion() {
+ return converted_blame(r, path, &rel, &text, revision, encoding);
+ }
let contents = match current_text {
+ Some(_) if crate::diff::normalize_eol(&text) == crate::diff::normalize_eol(&decode(&disk, encoding)) => disk,
Some(_) => {
let disk_text = decode(&disk, encoding);
let eol = if disk_text.contains("\r\n") {
@@ -102,6 +106,46 @@ pub(crate) fn blame(
Ok(lines)
}
+fn converted_blame(
+ r: &Repo,
+ path: &Path,
+ rel: &str,
+ text: &str,
+ revision: &str,
+ encoding: TextEncoding,
+) -> IdeResult<Vec<BlameLine>> {
+ let current = crate::diff::normalize_eol(text);
+ let mut result = uncommitted_lines(current.split_inclusive('\n').count());
+ let Some(base) = r.file_bytes_at(path, Some(revision))? else { return Ok(result) };
+ let out = run(r.root(), &["--literal-pathspecs", "blame", "--porcelain", revision, "--", rel], None)?;
+ let physical = crate::blame::parse_porcelain(&out.stdout_str());
+ let raw = crate::text_encoding::decode_raw(&base, encoding);
+ let raw = crate::diff::normalize_eol(&raw);
+ let mut logical = Vec::new();
+ for (line, metadata) in raw.split_inclusive('\n').zip(physical) {
+ let displayed = encoding.display_text(line);
+ let displayed = crate::diff::normalize_eol(&displayed);
+ logical.extend(std::iter::repeat_n(metadata, displayed.split_inclusive('\n').count()));
+ }
+ let base = decode(&base, encoding);
+ let hunks = crate::diff::line_hunks(&base, &current);
+ let (mut old, mut new) = (0usize, 0usize);
+ for h in hunks {
+ let unchanged = h.start as usize - new;
+ for i in 0..unchanged {
+ if let Some(metadata) = logical.get(old + i) {
+ result[new + i] = metadata.clone();
+ }
+ }
+ old = (h.old_start + h.old_lines) as usize;
+ new = (h.start + h.lines) as usize;
+ }
+ for (line, metadata) in result[new..].iter_mut().zip(&logical[old.min(logical.len())..]) {
+ *line = metadata.clone();
+ }
+ Ok(result)
+}
+
fn uncommitted_lines(n: usize) -> Vec<BlameLine> {
let now =
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as f64).unwrap_or(0.0);
@@ -115,7 +159,7 @@ fn uncommitted_lines(n: usize) -> Vec<BlameLine> {
.collect()
}
-pub(crate) fn diff_text(r: &Repo, path: &Path, staged: bool, encoding: &'static Encoding) -> IdeResult<String> {
+pub(crate) fn diff_text(r: &Repo, path: &Path, staged: bool, encoding: TextEncoding) -> IdeResult<String> {
let rel = r.rel_path(path)?;
let base =
["-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false", "-c", "diff.external=", "--literal-pathspecs"];
@@ -156,11 +200,7 @@ pub(crate) fn unstage(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> {
}
}
-pub(crate) fn stage_patch(
- r: &Repo,
- patch: &str,
- encoding: &dyn Fn(&Path) -> IdeResult<&'static Encoding>,
-) -> IdeResult<()> {
+pub(crate) fn stage_patch(r: &Repo, patch: &str, encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>) -> IdeResult<()> {
if patch.trim().is_empty() {
return Ok(());
}
@@ -168,6 +208,12 @@ pub(crate) fn stage_patch(
if !patch.ends_with('\n') {
patch.push('\n');
}
+ if crate::patch::parse_patch(&patch)
+ .iter()
+ .any(|file| encoding(&r.abs_path(&file.path)).is_ok_and(TextEncoding::has_ascii_conversion))
+ {
+ return crate::patch::stage_converted_patch(r, &patch, encoding);
+ }
let bytes = crate::patch::encode_text_patch(r, &patch, encoding)?;
run(r.root(), &["apply", "--cached", "--unidiff-zero", "--whitespace=nowarn", "--recount", "-"], Some(&bytes))
.map(|_| ())
@@ -257,7 +303,7 @@ pub(crate) fn commit(
r: &Repo,
message: &str,
options: &CommitOptions,
- encoding: &dyn Fn(&Path) -> IdeResult<&'static Encoding>,
+ encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
) -> IdeResult<String> {
let mut args = vec!["commit", "-q", "--cleanup=whitespace"];
if options.amend {
@@ -311,7 +357,7 @@ fn commit_partial(
commit_args: &[&str],
stdin: Option<&[u8]>,
partial: &[crate::PartialCommitFile],
- encoding: &dyn Fn(&Path) -> IdeResult<&'static Encoding>,
+ encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
) -> IdeResult<()> {
let tmp = TempIndex(r.git_dir.join("openidea-partial-index"));
let index = r.git_dir.join("index");
@@ -852,7 +898,7 @@ fn push_remote(r: &Repo) -> IdeResult<String> {
.ok_or_else(|| IdeError::invalid("no remote configured"))
}
-fn write_index_blob(r: &Repo, rel: &str, bytes: &[u8], env: &[(&str, &std::ffi::OsStr)]) -> IdeResult<()> {
+pub(crate) fn write_index_blob(r: &Repo, rel: &str, bytes: &[u8], env: &[(&str, &std::ffi::OsStr)]) -> IdeResult<()> {
let entry =
cli::run_env(r.root(), &["--literal-pathspecs", "ls-files", "--stage", "--", rel], None, env)?.stdout_str();
let mode = entry.split_whitespace().next().unwrap_or("100644");
@@ -866,7 +912,7 @@ pub(crate) fn stage_hunks(
path: &Path,
current: &str,
selected: &[usize],
- encoding: &'static Encoding,
+ encoding: TextEncoding,
) -> IdeResult<()> {
if selected.is_empty() {
return Ok(());
@@ -887,7 +933,7 @@ pub(crate) fn stage_hunks(
}
// Git headers contain UTF-8 paths; only source lines use the file's encoding.
-fn decode_diff(bytes: &[u8], encoding: &'static Encoding) -> String {
+fn decode_diff(bytes: &[u8], encoding: TextEncoding) -> String {
let mut hunks = false;
let mut text = String::new();
for line in bytes.split_inclusive(|&b| b == b'\n') {
@@ -898,7 +944,7 @@ fn decode_diff(bytes: &[u8], encoding: &'static Encoding) -> String {
hunks = true;
}
if hunks {
- text.push_str(&decode(line, encoding));
+ text.push_str(&crate::text_encoding::decode_raw(line, encoding));
} else {
text.push_str(&String::from_utf8_lossy(line));
}
diff --git a/crates/ide-vfs/src/encoding.rs b/crates/ide-vfs/src/encoding.rs
index 9153abded..05504a1b2 100644
--- a/crates/ide-vfs/src/encoding.rs
+++ b/crates/ide-vfs/src/encoding.rs
@@ -22,6 +22,87 @@ pub(crate) fn encoding_label(enc: &'static Encoding) -> String {
enc.name().to_ascii_lowercase()
}
+fn unicode_escape(text: &str) -> Option<u16> {
+ let digits = text.strip_prefix("\\u")?.as_bytes().get(..4)?;
+ digits.iter().try_fold(0u16, |n, b| Some(n * 16 + (*b as char).to_digit(16)? as u16))
+}
+
+fn unicode_character(text: &str) -> Option<(char, usize)> {
+ let unit = unicode_escape(text)?;
+ if (0xD800..=0xDBFF).contains(&unit) {
+ let low = unicode_escape(&text[6..]).filter(|low| (0xDC00..=0xDFFF).contains(low))?;
+ char::from_u32(0x10000 + ((unit as u32 - 0xD800) << 10) + low as u32 - 0xDC00).map(|c| (c, 12))
+ } else {
+ // A decoded line terminator would save as a real line break and split the property.
+ char::from_u32(unit as u32).filter(|c| !matches!(c, '\n' | '\r')).map(|c| (c, 6))
+ }
+}
+
+/// Decodes eligible Java properties Unicode escapes once. Backslash pairs,
+/// malformed escapes and unpaired surrogates retain their literal spelling.
+pub fn decode_properties_escapes(text: &str) -> String {
+ let mut out = String::with_capacity(text.len());
+ let mut rest = text;
+ while !rest.is_empty() {
+ if rest.starts_with("\\\\") {
+ out.push_str("\\\\");
+ rest = &rest[2..];
+ continue;
+ }
+ if let Some((c, len)) = unicode_character(rest) {
+ out.push(c);
+ rest = &rest[len..];
+ continue;
+ }
+ let c = rest.chars().next().expect("nonempty");
+ out.push(c);
+ rest = &rest[c.len_utf8()..];
+ }
+ out
+}
+
+/// Serializes displayed properties text as ASCII, using uppercase UTF-16 units.
+pub fn encode_properties_ascii(text: &str) -> String {
+ use std::fmt::Write;
+ let mut out = String::with_capacity(text.len());
+ let mut rest = text;
+ while let Some(c) = rest.chars().next() {
+ let current = rest;
+ rest = &rest[c.len_utf8()..];
+ if c == '\\' {
+ if rest.starts_with('\\') {
+ out.push_str("\\\\");
+ rest = &rest[1..];
+ } else if unicode_character(current).is_some() || rest.chars().next().is_some_and(|next| !next.is_ascii()) {
+ // Keep a literal backslash from swallowing a generated escape,
+ // or becoming a Unicode escape on the next load.
+ out.push_str("\\u005C");
+ } else {
+ out.push(c);
+ }
+ } else if c.is_ascii() && c != '\0' {
+ out.push(c);
+ } else {
+ for unit in c.encode_utf16(&mut [0; 2]) {
+ write!(out, "\\u{unit:04X}").expect("write to string");
+ }
+ }
+ }
+ out
+}
+
+/// Preserve an ASCII file's exact escape spelling when edits were undone or
+/// replaced with identical displayed text. Otherwise serialize the new buffer.
+pub fn save_properties_text(path: &Path, text: &str) -> IdeResult<f64> {
+ if let Ok(bytes) = fs::read(path)
+ && bytes.is_ascii()
+ && decode_properties_escapes(std::str::from_utf8(&bytes).expect("ASCII")) == text
+ {
+ return Ok(mtime_ms(&fs::metadata(path)?));
+ }
+ write_atomic(path, encode_properties_ascii(text).as_bytes())
+}
+
/// Detects BOM-less UTF-16 from the distribution of NUL bytes in mostly-ASCII text.
fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> {
if sample.len() < 4 {
@@ -285,6 +366,42 @@ fn write_atomic_impl(path: &Path, bytes: &[u8], allow_in_place: bool) -> IdeResu
mod tests {
use super::*;
+ #[test]
+ fn properties_unicode_escapes() {
+ for (source, displayed) in [
+ (r"test.key1=Hello", "test.key1=Hello"),
+ (r"test.key2=\u4F60\u597D", "test.key2=你好"),
+ (r"test.key3=\u4f60\u597d", "test.key3=你好"),
+ (r"\u0041\uD83D\uDE00!", "A😀!"),
+ (r"\\u0041", r"\\u0041"),
+ (r"\\\u0041", r"\\A"),
+ (r"\\\\u0041", r"\\\\u0041"),
+ (r"\u005Cu0041", r"\u0041"),
+ (r"\u123 \u12xz \uu0041 \uD800 \uDC00", r"\u123 \u12xz \uu0041 \uD800 \uDC00"),
+ (r"\uD800\u0041", r"\uD800A"),
+ (r"\uD800\uD83D\uDE00", "\\uD800😀"),
+ ] {
+ assert_eq!(decode_properties_escapes(source), displayed, "{source}");
+ }
+ assert_eq!(encode_properties_ascii("你好😀"), r"\u4F60\u597D\uD83D\uDE00");
+ for text in ["plain=ASCII\r\n", r"escaped=\\u0041", r"bad=\u12xz", r"bad=\uD800"] {
+ assert_eq!(encode_properties_ascii(text), text);
+ }
+ for text in ["你好😀", "\0", "\\中", "\\\\中", "\\\\\\😀", r"\u0041", r"\\u0041", r"\uD83D\uDE00"] {
+ let ascii = encode_properties_ascii(text);
+ assert!(ascii.is_ascii());
+ assert_eq!(decode_properties_escapes(&ascii), text, "{ascii}");
+ }
+ }
+
+ #[test]
+ fn properties_line_terminator_escapes_survive_an_edit() {
+ let source = r"key=one\u000Atwo\u000Dthree";
+ let displayed = decode_properties_escapes(source);
+ assert_eq!(displayed, source);
+ assert_eq!(encode_properties_ascii(&displayed.replace("three", "3")), r"key=one\u000Atwo\u000D3");
+ }
+
#[test]
fn strict_write_replaces_complete_contents() {
let dir = tempfile::tempdir().unwrap();
diff --git a/crates/ide-vfs/src/lib.rs b/crates/ide-vfs/src/lib.rs
index f1542f3d8..55c28b71b 100644
--- a/crates/ide-vfs/src/lib.rs
+++ b/crates/ide-vfs/src/lib.rs
@@ -22,7 +22,8 @@ pub use archive::{
pub use bytes::{ByteRange, FileProbe, MAX_RANGE_LEN, base64, image_mime, probe, read_data_url, read_range};
use encoding::SNIFF_LEN;
pub use encoding::{
- LARGE_FILE_THRESHOLD, MAX_OPEN_SIZE, READ_ONLY_THRESHOLD, encode, write_atomic, write_atomic_strict,
+ LARGE_FILE_THRESHOLD, MAX_OPEN_SIZE, READ_ONLY_THRESHOLD, decode_properties_escapes, encode,
+ encode_properties_ascii, save_properties_text, write_atomic, write_atomic_strict,
};
pub use rules::ExcludeMatcher;
pub use watch::{WatchMode, Watcher};
diff --git a/crates/ide-workspace/src/documents.rs b/crates/ide-workspace/src/documents.rs
index 0f44819dc..74a185724 100644
--- a/crates/ide-workspace/src/documents.rs
+++ b/crates/ide-workspace/src/documents.rs
@@ -118,6 +118,7 @@ struct DocState {
ui_mode: Option<String>,
encoding: String,
has_bom: bool,
+ native_to_ascii: bool,
read_only: bool,
large: bool,
editorconfig: Option<EditorConfigProps>,
@@ -189,6 +190,72 @@ impl Documents {
*self.defaults.write() = defaults;
}
+ /// Re-decode only clean properties buffers after the conversion setting changes.
+ /// Runs on the host's blocking pool; dirty documents retain their current codec.
+ pub fn reload_properties(&self) {
+ for id in self.open_documents() {
+ let result = self.with_doc(id, |st| {
+ let enabled = self.file_defaults().native_to_ascii_for(&st.path);
+ if st.dirty || st.uri.is_some() || st.binary || enabled == st.native_to_ascii {
+ return Ok(());
+ }
+ let loaded = Self::load_as(&st.path, &st.encoding, enabled)?;
+ self.replace_locked(id, st, &loaded.text)?;
+ st.native_to_ascii = enabled;
+ st.disk_mtime = loaded.mtime_ms;
+ st.disk_len = disk_len(&st.path);
+ Ok(())
+ });
+ if let Err(e) = result {
+ tracing::warn!("reload properties {id}: {e}");
+ }
+ }
+ }
+
+ pub fn native_to_ascii_for(&self, path: &Path) -> bool {
+ if let Some(id) = self.by_path(path)
+ && let Ok(enabled) = self.with_doc(id, |st| Ok(st.native_to_ascii))
+ {
+ return enabled;
+ }
+ self.file_defaults().native_to_ascii_for(path)
+ }
+
+ fn load_as(path: &Path, encoding: &str, native_to_ascii: bool) -> IdeResult<ide_vfs::LoadedText> {
+ let mut loaded = if native_to_ascii {
+ let detected = ide_vfs::load_text(path)?;
+ // Converted files are ASCII even when the selected source charset is UTF-16.
+ if detected.text.is_ascii() && !detected.binary && detected.encoding == "utf-8" {
+ detected
+ } else {
+ ide_vfs::load_text_as(path, encoding)?
+ }
+ } else {
+ ide_vfs::load_text_as(path, encoding)?
+ };
+ if native_to_ascii {
+ loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
+ }
+ Ok(loaded)
+ }
+
+ /// Closed-file readers use the same decoding as document opening.
+ pub fn load_file(&self, path: &Path) -> IdeResult<ide_vfs::LoadedText> {
+ Self::load_with_defaults(path, &self.file_defaults())
+ }
+
+ pub fn load_file_as(&self, path: &Path, encoding: &str) -> IdeResult<ide_vfs::LoadedText> {
+ Self::load_as(path, encoding, self.native_to_ascii_for(path))
+ }
+
+ fn load_with_defaults(path: &Path, defaults: &FileDefaults) -> IdeResult<ide_vfs::LoadedText> {
+ let mut loaded = ide_vfs::load_text_with_fallback(path, defaults.fallback_for(&absolute(path)))?;
+ if !loaded.binary && defaults.native_to_ascii_for(path) {
+ loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
+ }
+ Ok(loaded)
+ }
+
pub fn file_defaults(&self) -> FileDefaults {
self.defaults.read().clone()
}
@@ -263,7 +330,7 @@ impl Documents {
return Ok(info);
}
let defaults = self.file_defaults();
- let loaded = ide_vfs::load_text_with_fallback(path, defaults.fallback_for(&absolute(path)))?;
+ let loaded = Self::load_with_defaults(path, &defaults)?;
let language = (self.detect_language)(path, loaded.text.lines().next());
let ui_mode = (self.detect_ui_mode)(path, &language);
// Archive entries (`<jar>!/<entry>`) are read-only and kept from language
@@ -305,6 +372,7 @@ impl Documents {
ui_mode,
encoding,
has_bom,
+ native_to_ascii: !loaded.binary && defaults.native_to_ascii_for(path),
read_only: !observed || !writable,
large: loaded.large,
editorconfig,
@@ -362,6 +430,7 @@ impl Documents {
ui_mode: None,
encoding: "utf-8".into(),
has_bom: false,
+ native_to_ascii: false,
read_only: true,
large,
editorconfig: None,
@@ -524,7 +593,12 @@ impl Documents {
if !st.dirty || st.uri.is_some() {
return Ok(());
}
- let mtime = ide_vfs::save_text(&st.path, &st.doc.text_for_save(), &st.encoding, st.has_bom)?;
+ let text = st.doc.text_for_save();
+ let mtime = if st.native_to_ascii {
+ ide_vfs::save_properties_text(&st.path, &text)?
+ } else {
+ ide_vfs::save_text(&st.path, &text, &st.encoding, st.has_bom)?
+ };
st.disk_mtime = mtime;
st.disk_len = disk_len(&st.path);
self.set_dirty(doc, st, false);
@@ -582,6 +656,18 @@ impl Documents {
self.with_doc(id, |st| Ok(st.doc.text())).ok()
}
+ /// Search overlays include closed properties files when their disk spelling
+ /// differs from the text that opening the document would display.
+ pub fn search_text_of(&self, path: &Path) -> Option<String> {
+ self.text_of(path).or_else(|| {
+ if !self.native_to_ascii_for(path) {
+ return None;
+ }
+ let loaded = self.load_file(path).ok()?;
+ (!loaded.binary && !loaded.too_large).then(|| ide_text::normalize_line_endings(&loaded.text).into_owned())
+ })
+ }
+
/// Toggle Read-only Attribute: sets the file's writable bit and, when the
/// file is open, whether its document accepts edits. Returns the resulting
/// read-only state.
@@ -672,14 +758,18 @@ impl Documents {
if st.uri.is_some() {
return Err(read_only_error(&st.path));
}
+ ide_vfs::encode("", encoding, false)?;
if reload {
if st.dirty {
return Err(IdeError::invalid("save or revert the unsaved changes before reloading"));
}
- let loaded = ide_vfs::load_text_as(&st.path, encoding)?;
+ let enabled = self.file_defaults().native_to_ascii_for(&st.path);
+ let loaded = Self::load_as(&st.path, encoding, enabled)?;
+ st.native_to_ascii = enabled;
st.encoding = loaded.encoding.clone();
st.has_bom = loaded.has_bom;
st.disk_mtime = loaded.mtime_ms;
+ st.disk_len = disk_len(&st.path);
self.replace_locked(doc, st, &loaded.text)?;
// Reloading is not an edit: the buffer matches the file again.
self.set_dirty(doc, st, false);
@@ -691,7 +781,9 @@ impl Documents {
let utf16 = encoding.starts_with("utf-16");
let has_bom = utf16 || (st.has_bom && encoding == "utf-8");
// Fails (with the offending character) when the text is not representable.
- ide_vfs::encode(&st.doc.text_for_save(), encoding, has_bom)?;
+ if !st.native_to_ascii {
+ ide_vfs::encode(&st.doc.text_for_save(), encoding, has_bom)?;
+ }
st.encoding = encoding.to_owned();
st.has_bom = has_bom;
self.set_dirty(doc, st, true);
@@ -726,7 +818,9 @@ impl Documents {
});
return Ok(());
}
- let loaded = ide_vfs::load_text(&st.path)?;
+ let defaults = self.file_defaults();
+ let loaded = Self::load_with_defaults(&st.path, &defaults)?;
+ st.native_to_ascii = defaults.native_to_ascii_for(&st.path);
st.disk_mtime = loaded.mtime_ms;
st.disk_len = disk_len(&st.path);
if loaded.binary || st.binary {
diff --git a/crates/ide-workspace/src/file_defaults.rs b/crates/ide-workspace/src/file_defaults.rs
index f378109cc..e26484eb0 100644
--- a/crates/ide-workspace/src/file_defaults.rs
+++ b/crates/ide-workspace/src/file_defaults.rs
@@ -18,6 +18,7 @@ pub struct FileDefaults {
/// Fallback for files outside `root`.
pub global_fallback: String,
pub properties_fallback: String,
+ pub native_to_ascii: bool,
pub editorconfig: bool,
pub root: Option<PathBuf>,
}
@@ -47,6 +48,7 @@ impl FileDefaults {
project_fallback: normalize(&enc.project),
global_fallback: normalize(&enc.global),
properties_fallback: normalize(&enc.properties),
+ native_to_ascii: enc.native_to_ascii,
editorconfig: style.editorconfig,
root: root.map(Path::to_path_buf),
}
@@ -64,6 +66,10 @@ impl FileDefaults {
(label != "utf-8").then_some(label.as_str())
}
+ pub fn native_to_ascii_for(&self, path: &Path) -> bool {
+ self.native_to_ascii && path.extension().is_some_and(|e| e == "properties")
+ }
+
/// Bytes of a new empty file: a BOM when UTF-8 files are created with one.
pub fn new_file_bytes(&self) -> Vec<u8> {
if self.encoding == "utf-8" && self.utf8_bom {
diff --git a/crates/ide-workspace/tests/documents.rs b/crates/ide-workspace/tests/documents.rs
index 681f9be57..48e9e85a5 100644
--- a/crates/ide-workspace/tests/documents.rs
+++ b/crates/ide-workspace/tests/documents.rs
@@ -599,3 +599,100 @@ fn archive_entries_open_read_only_without_observers() {
assert!(f.rec.log.lock().is_empty(), "language servers / history never see archive entries");
f.docs.close(info.id);
}
+
+#[test]
+fn properties_conversion_uses_displayed_utf16_and_survives_reload() {
+ let f = fixture();
+ let path = f.root.join("messages.properties");
+ let original = "greeting=\\u4f60\\u597d\\uD83D\\uDE00!\r\nliteral=\\\\u0041\r\nbad=\\u12xz\r\n";
+ fs::write(&path, original).unwrap();
+ let mut defaults = f.docs.file_defaults();
+ defaults.native_to_ascii = true;
+ f.docs.set_file_defaults(defaults);
+ let doc = f.docs.open(&path).unwrap();
+ assert_eq!(doc.text, "greeting=你好😀!\nliteral=\\\\u0041\nbad=\\u12xz\n");
+ assert!(!doc.dirty);
+ assert_eq!(f.docs.text_snapshot(doc.id).unwrap().text, doc.text);
+ f.docs.save(doc.id).unwrap();
+ assert_eq!(fs::read(&path).unwrap(), original.as_bytes());
+ // Two BMP characters + one surrogate pair put ! at UTF-16 offset 13.
+ f.docs.edit(doc.id, doc.version, change(13, 14, "界")).unwrap();
+ f.docs.save(doc.id).unwrap();
+ let expected = "greeting=\\u4F60\\u597D\\uD83D\\uDE00\\u754C\r\nliteral=\\\\u0041\r\nbad=\\u12xz\r\n";
+ assert_eq!(fs::read(&path).unwrap(), expected.as_bytes());
+ assert!(f.rec.log.lock().iter().any(|line| line.contains("greeting=你好😀界")));
+ let saved = f.docs.snapshot(doc.id).unwrap();
+ f.docs.set_encoding(doc.id, "iso-8859-1", true).unwrap();
+ assert_eq!(f.docs.snapshot(doc.id).unwrap().version, saved.version);
+ // Force a watcher event even though the serialized contents are identical.
+ fs::File::options().write(true).open(&path).unwrap().set_modified(std::time::SystemTime::UNIX_EPOCH).unwrap();
+ f.docs.on_disk_changed(std::slice::from_ref(&path));
+ let reloaded = f.docs.snapshot(doc.id).unwrap();
+ assert_eq!(reloaded.text, saved.text);
+ assert_eq!(reloaded.version, saved.version);
+ assert!(!reloaded.dirty);
+ fs::write(&path, "greeting=\\u4E16\\u754C\r\n").unwrap();
+ f.docs.on_disk_changed(std::slice::from_ref(&path));
+ assert_eq!(f.docs.snapshot(doc.id).unwrap().text, "greeting=世界\n");
+ assert!(!f.docs.is_dirty(doc.id).unwrap());
+}
+
+#[test]
+fn properties_toggle_reloads_only_clean_properties_and_pins_dirty_codec() {
+ let f = fixture();
+ let paths = ["clean.properties", "dirty.properties", "other.txt"].map(|name| f.root.join(name));
+ for path in &paths {
+ fs::write(path, r"value=\u4F60").unwrap();
+ }
+ let [clean, dirty, other] = paths.each_ref().map(|p| f.docs.open(p).unwrap());
+ f.docs.edit(dirty.id, dirty.version, change(12, 12, "!")).unwrap();
+ let mut defaults = f.docs.file_defaults();
+ defaults.native_to_ascii = true;
+ f.docs.set_file_defaults(defaults.clone());
+ f.docs.reload_properties();
+ assert_eq!(f.docs.snapshot(clean.id).unwrap().text, "value=你");
+ assert!(!f.docs.is_dirty(clean.id).unwrap());
+ assert_eq!(f.docs.snapshot(dirty.id).unwrap().text, r"value=\u4F60!");
+ assert!(!f.docs.native_to_ascii_for(&paths[1]));
+ assert_eq!(f.docs.snapshot(other.id).unwrap().text, r"value=\u4F60");
+ f.docs.save(dirty.id).unwrap();
+ assert_eq!(fs::read_to_string(&paths[1]).unwrap(), r"value=\u4F60!");
+ f.docs.reload_properties();
+ assert_eq!(f.docs.snapshot(dirty.id).unwrap().text, "value=你!");
+ f.docs.edit(dirty.id, f.docs.snapshot(dirty.id).unwrap().version, change(7, 8, "好")).unwrap();
+ defaults.native_to_ascii = false;
+ f.docs.set_file_defaults(defaults);
+ f.docs.reload_properties();
+ assert_eq!(f.docs.snapshot(clean.id).unwrap().text, r"value=\u4F60");
+ assert!(f.docs.native_to_ascii_for(&paths[1]));
+ f.docs.save(dirty.id).unwrap();
+ assert_eq!(fs::read_to_string(&paths[1]).unwrap(), r"value=\u4F60\u597D");
+}
+
+#[test]
+fn properties_ascii_noop_and_charset_conversion() {
+ let f = fixture();
+ let mut defaults = f.docs.file_defaults();
+ defaults.native_to_ascii = true;
+ f.docs.set_file_defaults(defaults);
+ for (i, source) in ["a=b\r\n# comment\r\n", r"a=\u0041", r"a=\\u0041", r"a=\uD800"].iter().enumerate() {
+ let path = f.root.join(format!("{i}.properties"));
+ fs::write(&path, source).unwrap();
+ let doc = f.docs.open(&path).unwrap();
+ f.docs.edit(doc.id, doc.version, change(0, 0, "x")).unwrap();
+ f.docs.edit(doc.id, doc.version + 1, change(0, 1, "")).unwrap();
+ f.docs.save(doc.id).unwrap();
+ f.docs.set_encoding(doc.id, "utf-8", true).unwrap();
+ f.docs.save(doc.id).unwrap();
+ assert_eq!(fs::read_to_string(path).unwrap(), *source);
+ }
+ let path = f.root.join("utf16.properties");
+ fs::write(&path, ide_vfs::encode("a=你好😀", "utf-16le", true).unwrap()).unwrap();
+ let doc = f.docs.open(&path).unwrap();
+ f.docs.replace_all(doc.id, "a=世界😀").unwrap();
+ f.docs.save(doc.id).unwrap();
+ assert!(fs::read(&path).unwrap().is_ascii());
+ f.docs.set_encoding(doc.id, "utf-16le", true).unwrap();
+ assert_eq!(f.docs.snapshot(doc.id).unwrap().text, "a=世界😀");
+ assert!(!f.docs.is_dirty(doc.id).unwrap());
+}
diff --git a/src-tauri/src/commands/doc.rs b/src-tauri/src/commands/doc.rs
index ddbd3b05f..b19a32a36 100644
--- a/src-tauri/src/commands/doc.rs
+++ b/src-tauri/src/commands/doc.rs
@@ -74,14 +74,14 @@ pub async fn doc_ui_mode(window: Window, state: State<'_, AppState>, path: PathB
/// "Reload with Encoding" (`reload`) or "Convert to Encoding"; returns the new encoding label.
#[tauri::command]
#[specta::specta]
-pub fn doc_set_encoding(
+pub async fn doc_set_encoding(
window: Window,
state: State<'_, AppState>,
doc: DocId,
encoding: String,
reload: bool,
) -> IdeResult<String> {
- ide_host::ops::doc::doc_set_encoding(&state.host, window.label(), doc, encoding, reload)
+ ide_host::ops::doc::doc_set_encoding(&state.host, window.label(), doc, encoding, reload).await
}
#[tauri::command]
diff --git a/src-tauri/src/commands/vcs.rs b/src-tauri/src/commands/vcs.rs
index efe148c05..1c90bf70b 100644
--- a/src-tauri/src/commands/vcs.rs
+++ b/src-tauri/src/commands/vcs.rs
@@ -35,8 +35,8 @@ pub async fn vcs_branch_info(
/// Gutter change markers for a file, computed against its current (unsaved) text.
#[tauri::command]
#[specta::specta]
-pub fn vcs_line_hunks(window: Window, state: State<'_, AppState>, path: PathBuf) -> IdeResult<Vec<LineHunk>> {
- ide_host::ops::vcs::vcs_line_hunks(&state.host, window.label(), path)
+pub async fn vcs_line_hunks(window: Window, state: State<'_, AppState>, path: PathBuf) -> IdeResult<Vec<LineHunk>> {
+ ide_host::ops::vcs::vcs_line_hunks(&state.host, window.label(), path).await
}
#[tauri::command]
@@ -338,8 +338,13 @@ pub fn vcs_diff_hunks(state: State<'_, AppState>, old_text: String, new_text: St
/// Indices refer to `vcs_diff_hunks(index_text, worktree_text)`.
#[tauri::command]
#[specta::specta]
-pub fn vcs_stage_hunks(window: Window, state: State<'_, AppState>, path: PathBuf, hunks: Vec<u32>) -> IdeResult<()> {
- ide_host::ops::vcs::vcs_stage_hunks(&state.host, window.label(), path, hunks)
+pub async fn vcs_stage_hunks(
+ window: Window,
+ state: State<'_, AppState>,
+ path: PathBuf,
+ hunks: Vec<u32>,
+) -> IdeResult<()> {
+ ide_host::ops::vcs::vcs_stage_hunks(&state.host, window.label(), path, hunks).await
}
/// Clones a repository (Get from VCS). Works without an open project.
diff --git a/src/bindings.ts b/src/bindings.ts
index ad7223a83..113eff5dd 100644
--- a/src/bindings.ts
+++ b/src/bindings.ts
@@ -2873,6 +2873,8 @@ export type EncodingSettings = {
project?: string,
/** Fallback for `.properties` files. */
properties?: string,
+ /** Display properties Unicode escapes as characters and save non-ASCII as escapes. */
+ nativeToAscii?: boolean,
/** Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows). */
utf8Bom?: string,
};
diff --git a/src/features/settings/__tests__/dialog.test.tsx b/src/features/settings/__tests__/dialog.test.tsx
index 0ab46c953..bf60202ce 100644
--- a/src/features/settings/__tests__/dialog.test.tsx
+++ b/src/features/settings/__tests__/dialog.test.tsx
@@ -65,6 +65,24 @@ async function openDialog(page?: string) {
}
describe("Settings dialog", () => {
+ it("stages properties conversion through its action and applies the checkbox", async () => {
+ const dialog = await openDialog("editor.fileEncodings");
+ const checkbox = within(dialog).getByRole("checkbox", { name: "Transparent native-to-ascii conversion" });
+ expect(checkbox).not.toBeChecked();
+ await act(async () => fireEvent.click(checkbox));
+ expect(checkbox).toBeChecked();
+ expect(settingsSet).not.toHaveBeenCalled();
+ await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Apply" })));
+ expect(settingsSet).toHaveBeenCalledWith("global", "editor.encodings.nativeToAscii", "true");
+ });
+
+ it("toggles properties conversion through its stable action", async () => {
+ await executeAction("editor.encodings.toggleNativeToAscii");
+ expect(settingsSet).toHaveBeenCalledWith("global", "editor.encodings.nativeToAscii", "true");
+ await executeAction("editor.encodings.toggleNativeToAscii");
+ expect(settingsSet).toHaveBeenLastCalledWith("global", "editor.encodings.nativeToAscii", "false");
+ });
+
it("finds Gradle JVM and applies project Gradle settings", async () => {
useProject.setState({ project: { root: "/project" } as never });
const dialog = await openDialog("build.gradle");
diff --git a/src/features/settings/index.ts b/src/features/settings/index.ts
index 3be8e8f04..8391dad44 100644
--- a/src/features/settings/index.ts
+++ b/src/features/settings/index.ts
@@ -36,6 +36,7 @@ import { installActionProxies, installSettingsHost } from "./window/bridge";
import { AssignShortcutOverlay, showAssignShortcut } from "./keymap/AssignShortcut";
import { settingsSearchEntries } from "./searchIndex";
import { activatePythonStatus } from "./languages/PythonStatus";
+import { nativeToAsciiAction } from "./nativeToAscii";
import { isImeKey } from "@/platform/ime";
export { settingsWindowParent } from "./window/bridge";
@@ -49,6 +50,7 @@ const NEW_PROJECTS_PAGE = "languages.java";
function settingsActions(open: (page?: string, newProjects?: boolean) => void): Action[] {
return [
+ nativeToAsciiAction(),
{
id: "file.settings",
title: "Settings…",
diff --git a/src/features/settings/nativeToAscii.ts b/src/features/settings/nativeToAscii.ts
new file mode 100644
index 000000000..dd978efa6
--- /dev/null
+++ b/src/features/settings/nativeToAscii.ts
@@ -0,0 +1,32 @@
+import type { Action } from "@/platform/actions";
+import { call, commands } from "@/platform/ipc";
+import { loadSettings, useProject } from "@/platform/project";
+import { stage, type Scope } from "./model/staging";
+
+export const NATIVE_TO_ASCII_ACTION = "editor.encodings.toggleNativeToAscii";
+const KEY = "editor.encodings.nativeToAscii";
+
+export function nativeToAsciiAction(): Action {
+ return {
+ id: NATIVE_TO_ASCII_ACTION,
+ title: "Transparent native-to-ascii conversion",
+ category: "Editor",
+ keywords: ["properties", "encoding", "Unicode"],
+ run: async ({ arg }) => {
+ const staged = arg as { pageId?: string; scope?: Scope; value?: boolean } | undefined;
+ if (staged?.pageId && staged.scope && typeof staged.value === "boolean") {
+ stage(staged.pageId, staged.scope, KEY, staged.value);
+ return;
+ }
+ const { settings, project } = useProject.getState();
+ await call(
+ commands.settingsSet(
+ project ? "project" : "global",
+ KEY,
+ JSON.stringify(!settings?.editor?.encodings?.nativeToAscii),
+ ),
+ );
+ await loadSettings();
+ },
+ };
+}
diff --git a/src/features/settings/pages/editor/codeStyle.tsx b/src/features/settings/pages/editor/codeStyle.tsx
index 548b74a9a..3138f68e1 100644
--- a/src/features/settings/pages/editor/codeStyle.tsx
+++ b/src/features/settings/pages/editor/codeStyle.tsx
@@ -11,6 +11,7 @@ import { useId, useState } from "react";
import { Button, Checkbox, Input, type SelectOption, T } from "@/ui";
import { commands, isTauri, type LanguageInfo_Serialize as LanguageInfo } from "@/platform/ipc";
import { ENCODING_CHOICES, lineCommentDefaults, type LanguageCodeStyle } from "@/platform/editorSettings";
+import { NATIVE_TO_ASCII_ACTION } from "../../nativeToAscii";
import { NumberInput, Row } from "../../components/Form";
import { useSetting } from "../../components/context";
import type { PageSpec } from "../spec";
@@ -272,7 +273,7 @@ const ENCODINGS_PAGE = editorPage({
title: "File Encodings",
order: 27,
projectScope: true,
- keywords: ["encoding", "charset", "utf-8", "bom"],
+ keywords: ["encoding", "charset", "utf-8", "bom", "native-to-ascii", "properties"],
sections: [
{
items: [
@@ -301,6 +302,12 @@ const ENCODINGS_PAGE = editorPage({
label: "Default encoding for properties files",
options: ENCODINGS,
},
+ {
+ t: "check",
+ key: "editor.encodings.nativeToAscii",
+ action: NATIVE_TO_ASCII_ACTION,
+ label: "Transparent native-to-ascii conversion",
+ },
],
},
{
diff --git a/src/features/settings/pages/editor/kit.tsx b/src/features/settings/pages/editor/kit.tsx
index 0d09798c9..74edf3683 100644
--- a/src/features/settings/pages/editor/kit.tsx
+++ b/src/features/settings/pages/editor/kit.tsx
@@ -8,9 +8,10 @@
import { createContext, useContext, useId, type ComponentType, type ReactNode } from "react";
import clsx from "clsx";
import { Checkbox, Input, type SelectOption } from "@/ui";
+import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { NumberInput, Row, SearchLabel, Section, Select } from "../../components/Form";
-import { useLabelMatch, useSetting } from "../../components/context";
+import { useLabelMatch, usePageContext, useSetting } from "../../components/context";
import type { PageSpec } from "../spec";
import styles from "./Editor.module.css";
@@ -22,6 +23,7 @@ export type Item =
| {
t: "check";
key: string;
+ action?: string;
label: string;
hint?: ReactNode;
/** Checked when the stored boolean is false (e.g. "Disable …"). */
@@ -60,6 +62,7 @@ const Disabled = createContext(false);
function CheckItem({ item }: { item: Extract<Item, { t: "check" }> }) {
const parentDisabled = useContext(Disabled);
+ const context = usePageContext();
const [raw, set] = useSetting<boolean>(item.key);
const checked = item.invert ? !raw : !!raw;
const matched = useLabelMatch(item.label);
@@ -70,7 +73,11 @@ function CheckItem({ item }: { item: Extract<Item, { t: "check" }> }) {
<Checkbox
checked={checked}
disabled={parentDisabled}
- onChange={(v) => set(item.invert ? !v : v)}
+ onChange={(v) => {
+ const value = item.invert ? !v : v;
+ if (item.action) void executeAction(item.action, { ...context, value });
+ else set(value);
+ }}
label={<SearchLabel text={item.label} />}
/>
{item.inline && <InlineControl inline={item.inline} label={item.label} disabled={off} />}
diff --git a/src/platform/editorSettings.ts b/src/platform/editorSettings.ts
index 4443d8897..6471898dd 100644
--- a/src/platform/editorSettings.ts
+++ b/src/platform/editorSettings.ts
@@ -186,7 +186,7 @@ export const EDITOR_EXTRA_DEFAULTS = {
formatterOnTag: "@formatter:on",
formatterTagsRegexp: false,
},
- encodings: { global: "utf-8", project: "utf-8", properties: "iso-8859-1", utf8Bom: "never" },
+ encodings: { global: "utf-8", project: "utf-8", properties: "iso-8859-1", nativeToAscii: false, utf8Bom: "never" },
};
export type EditorExtras = typeof EDITOR_EXTRA_DEFAULTS;
diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json
index ef01ed415..9727509b3 100644
--- a/src/platform/locales/text/zh.json
+++ b/src/platform/locales/text/zh.json
@@ -565,6 +565,7 @@
"Default Tab name": "默认标签页名称",
"Default directory": "默认目录",
"Default encoding": "默认编码",
+ "Transparent native-to-ascii conversion": "透明的 native-to-ascii 转换",
"Default encoding for properties files": "属性文件的默认编码",
"Default value": "默认值",
"Definition": "定义",