feat(editor): remember the encoding chosen for a file or folder (#5510)

The encoding chosen for a file from the status bar (Reload or Convert) is remembered for that file across reopening and restarts, and a folder can have an encoding its files inherit (project settings). A converted file keeps its new encoding once saved. Precedence: a file's own choice, then the .editorconfig charset, then the folder mapping.

Co-authored-by: LittleGuava <[email protected]>
Цей коміт міститься в:
Fabio Nunes authored and GitHub committed 2026-11-27 10:43:43 +08:00
1 джерело f0fe910017
коміт d41feefc07
21 files changed
+852 -41

No files matched your search

+39
Переглянути файл
@@ -562,6 +562,25 @@ pub struct EncodingSettings {
pub native_to_ascii: bool,
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
pub utf8_bom: String,
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
/// relative to the project with `/` separators. The status bar's choice is kept here.
#[serde(deserialize_with = "labels")]
#[specta(type = BTreeMap<String, String>)]
pub mappings: BTreeMap<String, String>,
}
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
return Ok(BTreeMap::new());
};
Ok(entries
.into_iter()
.filter_map(|(path, label)| match label {
serde_json::Value::String(label) => Some((path, label)),
_ => None,
})
.collect())
}
impl Default for EncodingSettings {
@@ -572,10 +591,30 @@ impl Default for EncodingSettings {
properties: "iso-8859-1".into(),
native_to_ascii: false,
utf8_bom: "never".into(),
mappings: BTreeMap::new(),
}
}
}
#[cfg(test)]
mod encoding_mappings_tests {
use super::EncodingSettings;
#[test]
fn encoding_mappings_keep_the_entries_that_are_labels() {
let json = serde_json::json!({
"project": "gbk",
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
});
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
assert_eq!(settings.project, "gbk");
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
assert!(not_a_table.mappings.is_empty());
assert!(EncodingSettings::default().mappings.is_empty());
}
}
#[cfg(test)]
mod auto_import_tests {
use super::{AutoImportSettings, ImportsOnPaste};
+19 -3
Переглянути файл
@@ -67,7 +67,12 @@ pub async fn doc_edit(host: &Host, window: &str, doc: DocId, base_version: u32,
#[command(trust = always)]
pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
let project = host.project(window)?;
host.blocking(move || project.documents.save(doc)).await?;
host.blocking(move || {
project.documents.save(doc)?;
remember_saved_encodings(&project);
Ok(())
})
.await?;
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
@@ -83,7 +88,13 @@ pub async fn doc_reload_from_disk(host: &Host, window: &str, doc: DocId) -> IdeR
#[command(trust = always)]
pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bool> {
let project = host.project(window)?;
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
let saved = host
.blocking(move || {
let saved = project.documents.autosave(doc)?;
remember_saved_encodings(&project);
Ok(saved)
})
.await?;
if saved {
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
}
@@ -93,7 +104,12 @@ pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bo
#[command(trust = always)]
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
let project = host.project(window)?;
host.blocking(move || project.documents.save_all()).await?;
host.blocking(move || {
let saved = project.documents.save_all();
remember_saved_encodings(&project);
saved
})
.await?;
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
+49 -3
Переглянути файл
@@ -1,11 +1,13 @@
use crate::Host;
use crate::ops::blocking;
use crate::project::Project;
use ide_command::command;
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
use ide_core::{DocId, IdeEvent, IdeResult, OutlineItem, Range, TextEdit};
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
use std::path::PathBuf;
use ide_workspace::settings::SettingsScope;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
use std::path::{Path, PathBuf};
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
/// editor buffer, so syntax features and language-server requests work in it.
@@ -66,6 +68,49 @@ pub async fn doc_set_encoding(
host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
}
/// Keeps the encoding the user chose for a project file in the project's File Encodings
/// mappings, so the file opens in it again. A converted document is kept once it is saved:
/// until then its file is still in the old encoding. Nothing is kept for a document without
/// a file in the project.
#[command(trust = always)]
pub async fn doc_remember_encoding(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
let info = project.documents.snapshot(doc)?;
if info.uri.is_some() || project.documents.keep_encoding_when_saved(doc)? {
return Ok(());
}
remember_encoding(&project, &info.path, &info.encoding)
})
.await
}
/// Keeps the encodings of the converted documents a save has just written.
pub(super) fn remember_saved_encodings(project: &Project) {
for (path, encoding) in project.documents.take_saved_encodings() {
if let Err(e) = remember_encoding(project, &path, &encoding) {
tracing::warn!("the encoding of {} was not kept: {e}", path.display());
}
}
}
fn remember_encoding(project: &Project, path: &Path, encoding: &str) -> IdeResult<()> {
const MAPPINGS: &str = "editor.encodings.mappings";
if project.light {
return Ok(());
}
let Some(file) = ide_workspace::file_defaults::mapping_key(&project.root, path) else {
return Ok(());
};
if project.settings.effective().editor.encodings.mappings.get(&file).is_some_and(|kept| kept == encoding) {
return Ok(());
}
let settings = project.settings.set_map_entry(SettingsScope::Project, MAPPINGS, &file, encoding.into())?;
project.documents.set_file_defaults(FileDefaults::from_settings(&settings, Some(&project.root)));
project.sink.emit(IdeEvent::SettingsChanged { key: MAPPINGS.into() });
Ok(())
}
#[command(trust = always)]
pub async fn doc_set_bom(host: &Host, window: &str, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
// Adds or removes the BOM on a UTF-8 document; the change is written on save.
@@ -263,6 +308,7 @@ ide_command::domain!(
doc_outline,
doc_python_facts,
doc_rearrange,
doc_remember_encoding,
doc_selection_ranges,
doc_set_bom,
doc_set_encoding,
+95
Переглянути файл
@@ -221,3 +221,98 @@ async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
f.sync().await;
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
}
const MAPPINGS_CHANGED: &str = "editor.encodings.mappings";
impl Fixture {
fn project_settings(&self) -> PathBuf {
self.project.settings.file(ide_workspace::settings::SettingsScope::Project).unwrap().to_path_buf()
}
fn mappings_changed(&self) -> usize {
let events = self.events.lock();
events.iter().filter(|e| matches!(e, IdeEvent::SettingsChanged { key } if key == MAPPINGS_CHANGED)).count()
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remembered_encoding_is_written_once_and_used_when_the_file_is_reopened() {
let f = Fixture::new();
let settings = f.project_settings();
std::fs::write(&f.path, "ação\n").unwrap();
let doc = f.open(&f.path).await;
assert_eq!(doc.encoding, "utf-8");
// Changing the encoding alone (Reload from Disk, an RPC client) keeps nothing.
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
assert!(!settings.exists());
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
let written = std::fs::read_to_string(&settings).unwrap();
assert_eq!(written, "[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n");
assert_eq!(f.mappings_changed(), 1);
// The same choice again leaves the file alone.
let stamp = std::fs::metadata(&settings).unwrap().modified().unwrap();
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
assert_eq!(std::fs::metadata(&settings).unwrap().modified().unwrap(), stamp);
assert_eq!(f.mappings_changed(), 1);
doc_close(&f.host, "main", doc.id).await.unwrap();
let reopened = f.open(&f.path).await;
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", "ação\n"));
// A file outside the project has no place in the project's settings.
let outside = f.open(&f.outside).await;
doc_set_encoding(&f.host, "main", outside.id, "iso-8859-15".into(), true).await.unwrap();
doc_remember_encoding(&f.host, "main", outside.id).await.unwrap();
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn converted_encoding_is_remembered_once_the_file_is_saved_in_it() {
let f = Fixture::new();
let settings = f.project_settings();
std::fs::write(&f.path, "ação\n").unwrap();
let doc = f.open(&f.path).await;
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), false).await.unwrap();
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
// The file is still UTF-8 on disk: closing without saving must not leave it mapped.
assert!(!settings.exists());
doc_close(&f.host, "main", doc.id).await.unwrap();
let reopened = f.open(&f.path).await;
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("utf-8", "ação\n"));
doc_set_encoding(&f.host, "main", reopened.id, "iso-8859-15".into(), false).await.unwrap();
doc_remember_encoding(&f.host, "main", reopened.id).await.unwrap();
doc_save(&f.host, "main", reopened.id).await.unwrap();
assert_eq!(std::fs::read(&f.path).unwrap(), b"a\xe7\xe3o\n");
assert_eq!(
std::fs::read_to_string(&settings).unwrap(),
"[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n"
);
assert_eq!(f.mappings_changed(), 1);
// Later saves keep nothing more.
doc_save(&f.host, "main", reopened.id).await.unwrap();
assert_eq!(f.mappings_changed(), 1);
doc_close(&f.host, "main", reopened.id).await.unwrap();
let again = f.open(&f.path).await;
assert_eq!((again.encoding.as_str(), again.text.as_str()), ("iso-8859-15", "ação\n"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn encoding_stays_changed_when_it_cannot_be_remembered() {
let f = Fixture::new();
let settings = f.project_settings();
std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
std::fs::write(&settings, "[editor\n").unwrap();
let doc = f.open(&f.path).await;
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
let err = doc_remember_encoding(&f.host, "main", doc.id).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
assert_eq!(std::fs::read_to_string(&settings).unwrap(), "[editor\n");
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().encoding, "iso-8859-15");
assert_eq!(f.mappings_changed(), 0);
}
+1 -2
Переглянути файл
@@ -1530,8 +1530,7 @@ impl Project {
}
pub fn staged_file_encoding(&self, path: &Path, bytes: &[u8]) -> ide_vcs::TextEncoding {
let defaults = self.documents.file_defaults();
let charset = ide_vfs::detect_encoding(bytes, defaults.fallback_for(path));
let charset = self.documents.detect_encoding(path, bytes);
self.vcs_text_encoding(path, charset)
}
+81 -12
Переглянути файл
@@ -1,5 +1,5 @@
use crate::editorconfig::{EditorConfig, EditorConfigProps};
use crate::file_defaults::FileDefaults;
use crate::file_defaults::{EncodingSource, FileDefaults};
use ide_core::error::ErrorKind;
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink, TextEdit};
use ide_text::{AppliedChange, ByteEdit, Document, LineEnding};
@@ -168,6 +168,8 @@ struct DocState {
can_reload_encoding: bool,
/// The user picked `encoding`; reloads keep it instead of detecting again.
encoding_chosen: bool,
/// The user converted the text to `encoding`; it is theirs to keep once a save writes it.
encoding_unsaved: bool,
/// Disk state we last loaded or wrote; changes matching it are our own.
disk_mtime: f64,
disk_len: u64,
@@ -254,8 +256,15 @@ fn configured_fallback<'a>(
path: &Path,
editorconfig: Option<&EditorConfigProps>,
) -> Option<ide_vfs::Fallback<'a>> {
let fallback = defaults.fallback_for(&absolute(path));
match editorconfig.filter(|_| defaults.editorconfig).and_then(EditorConfigProps::encoding) {
let path = absolute(path);
let charset = editorconfig.filter(|_| defaults.editorconfig).and_then(EditorConfigProps::encoding);
let inherited = defaults.inherited_encoding_for(&path);
let fallback = if inherited.source == EncodingSource::Folder && charset.is_some() {
defaults.project_encoding_for(&path).fallback()
} else {
inherited.fallback()
};
match charset {
Some(("utf-8", _)) => fallback.map(|f| ide_vfs::Fallback { ascii: false, ..f }),
Some((encoding, _)) if !encoding.starts_with("utf-16") => Some(ide_vfs::Fallback { encoding, ascii: true }),
_ => fallback,
@@ -364,13 +373,20 @@ impl Documents {
/// Closed-file readers use the same decoding as document opening.
pub fn load_file(&self, path: &Path) -> IdeResult<ide_vfs::LoadedText> {
let defaults = self.file_defaults();
Self::load_with_defaults(path, &defaults, self.editorconfig_for(path, &defaults).as_ref())
Ok(Self::load_with_defaults(path, &defaults, self.editorconfig_for(path, &defaults).as_ref())?.0)
}
/// 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 editorconfig = self.editorconfig_for(path, &defaults);
let configured = defaults.configured_encoding_for(&absolute(path));
if configured.source == EncodingSource::File
&& let Some(enc) = encoding_rs::Encoding::for_label(configured.label.as_bytes())
&& !enc.decode_with_bom_removal(bytes).0.contains(char::REPLACEMENT_CHARACTER)
{
return enc;
}
ide_vfs::detect_encoding(bytes, configured_fallback(&defaults, path, editorconfig.as_ref()))
}
@@ -385,6 +401,10 @@ impl Documents {
pub fn configured_encoding_for(&self, path: &Path) -> Option<String> {
let defaults = self.file_defaults();
let editorconfig = self.editorconfig_for(path, &defaults);
let configured = defaults.configured_encoding_for(&absolute(path));
if configured.source == EncodingSource::File {
return Some(configured.label.to_owned());
}
configured_fallback(&defaults, path, editorconfig.as_ref()).map(|f| f.encoding.to_owned())
}
@@ -404,16 +424,30 @@ impl Documents {
Self::load_as(path, encoding, self.native_to_ascii_for(path))
}
/// Loads `path` as the settings say. `true`: decoded in the encoding chosen for this
/// very file, as "Reload with Encoding" does, instead of detecting it.
fn load_with_defaults(
path: &Path,
defaults: &FileDefaults,
editorconfig: Option<&EditorConfigProps>,
) -> IdeResult<ide_vfs::LoadedText> {
let mut loaded = ide_vfs::load_text_with_fallback(path, configured_fallback(defaults, path, editorconfig))?;
) -> IdeResult<(ide_vfs::LoadedText, bool)> {
let path_abs = absolute(path);
let configured = defaults.configured_encoding_for(&path_abs);
if configured.source == EncodingSource::File {
let loaded = Self::load_as(path, configured.label, defaults.native_to_ascii_for(path))?;
// The bytes are not text in that encoding (the file changed outside the IDE):
// open it as if nothing was chosen, rather than show and save broken characters.
// A single-byte encoding decodes any bytes, so this only catches the others.
if !loaded.text.contains(char::REPLACEMENT_CHARACTER) {
return Ok((loaded, true));
}
}
let fallback = configured_fallback(defaults, path, editorconfig);
let mut loaded = ide_vfs::load_text_with_fallback(path, fallback)?;
if !loaded.binary && defaults.native_to_ascii_for(path) {
loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
}
Ok(loaded)
Ok((loaded, false))
}
pub fn file_defaults(&self) -> FileDefaults {
@@ -495,7 +529,7 @@ impl Documents {
}
let defaults = self.file_defaults();
let editorconfig = self.editorconfig_for(path, &defaults);
let loaded = Self::load_with_defaults(path, &defaults, editorconfig.as_ref())?;
let (loaded, encoding_chosen) = 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);
@@ -511,8 +545,14 @@ impl Documents {
// An empty file has nothing to detect: Code Style / File Encodings defaults apply.
if empty_file && !loaded.binary {
doc.set_line_ending(defaults.line_ending);
encoding = defaults.encoding.clone();
has_bom = defaults.encoding == "utf-8" && defaults.utf8_bom;
if !encoding_chosen {
let configured = defaults.configured_encoding_for(&absolute(path));
encoding = match configured.source {
EncodingSource::Folder => configured.label.to_owned(),
_ => defaults.encoding.clone(),
};
has_bom = encoding == "utf-8" && defaults.utf8_bom;
}
}
if let Some(ec) = &editorconfig {
if let Some(le) = ec.end_of_line {
@@ -520,6 +560,7 @@ impl Documents {
}
if let Some((enc, bom)) = ec.encoding()
&& empty_file
&& !encoding_chosen
{
(encoding, has_bom) = (enc.to_owned(), bom);
}
@@ -542,7 +583,8 @@ impl Documents {
binary: loaded.binary,
dirty: false,
can_reload_encoding: true,
encoding_chosen: false,
encoding_chosen,
encoding_unsaved: false,
disk_mtime: loaded.mtime_ms,
disk_len: disk_len(path),
disk_conflict: false,
@@ -620,6 +662,7 @@ impl Documents {
dirty: false,
can_reload_encoding,
encoding_chosen: false,
encoding_unsaved: false,
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
@@ -681,6 +724,7 @@ impl Documents {
dirty: false,
can_reload_encoding: false,
encoding_chosen: false,
encoding_unsaved: false,
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
@@ -1294,6 +1338,30 @@ impl Documents {
})
}
/// Whether the encoding the user chose for `doc` is still to reach its file: the text was
/// converted and not saved. It is then reported by [`Documents::take_saved_encodings`]
/// once a save has written it.
pub fn keep_encoding_when_saved(&self, doc: DocId) -> IdeResult<bool> {
self.with_doc(doc, |st| {
st.encoding_unsaved = st.dirty;
Ok(st.dirty)
})
}
/// The files saved in the encoding their text was converted to since
/// [`Documents::keep_encoding_when_saved`], with that encoding. Each is reported once.
pub fn take_saved_encodings(&self) -> Vec<(PathBuf, String)> {
let ids: Vec<DocId> = self.registry.lock().docs.keys().copied().collect();
let saved = |id| {
self.with_doc(id, |st| {
let saved = st.encoding_unsaved && !st.dirty;
st.encoding_unsaved &= st.dirty;
Ok(saved.then(|| (st.path.clone(), st.encoding.clone())))
})
};
ids.into_iter().filter_map(|id| saved(id).ok().flatten()).collect()
}
/// Load Changes from Disk: drops the buffer's unsaved changes and reads its file again in
/// the buffer's encoding, after the file changed on disk (`IdeEvent::DocDiskConflict`).
pub fn discard_and_reload(&self, doc: DocId) -> IdeResult<()> {
@@ -1303,6 +1371,7 @@ impl Documents {
}
let loaded = Self::load_as(&st.path, &st.encoding, st.native_to_ascii)?;
st.has_bom = loaded.has_bom;
st.encoding_unsaved = false;
self.replace_locked(doc, st, &loaded.text)?;
st.synced(loaded.mtime_ms);
self.set_dirty(doc, st, false);
@@ -1473,7 +1542,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, st.editorconfig.as_ref())?
Self::load_with_defaults(&st.path, &defaults, st.editorconfig.as_ref())?.0
};
st.native_to_ascii = native_to_ascii;
loaded
+1 -1
Переглянути файл
@@ -850,7 +850,7 @@ impl Documents {
let loaded = if state.encoding_chosen {
Self::load_as(path, &state.encoding, native_to_ascii)?
} else {
Self::load_with_defaults(path, &defaults, state.editorconfig.as_ref())?
Self::load_with_defaults(path, &defaults, state.editorconfig.as_ref())?.0
};
state.native_to_ascii = native_to_ascii;
self.replace_locked(id, state, &loaded.text)?;
+212 -11
Переглянути файл
@@ -4,7 +4,8 @@
use ide_core::settings::Settings;
use ide_text::LineEnding;
use std::path::{Path, PathBuf};
use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Debug, PartialEq)]
pub struct FileDefaults {
@@ -21,6 +22,34 @@ pub struct FileDefaults {
pub native_to_ascii: bool,
pub editorconfig: bool,
pub root: Option<PathBuf>,
/// File Encodings mappings: a file's or a folder's path with its encoding. An entry
/// naming the file itself is the user's choice for it; one naming a folder above it
/// covers the files inside.
pub mappings: Vec<(PathBuf, String)>,
}
/// Where the encoding configured for a file comes from, strongest first.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EncodingSource {
File,
Properties,
Folder,
Project,
Global,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ConfiguredEncoding<'a> {
pub label: &'a str,
pub source: EncodingSource,
}
impl<'a> ConfiguredEncoding<'a> {
/// The label for files that are not valid UTF-8 or are plain ASCII (`None`: detect).
pub fn fallback(self) -> Option<ide_vfs::Fallback<'a>> {
(self.label != "utf-8")
.then_some(ide_vfs::Fallback { encoding: self.label, ascii: self.source != EncodingSource::Properties })
}
}
impl Default for FileDefaults {
@@ -51,20 +80,47 @@ impl FileDefaults {
native_to_ascii: enc.native_to_ascii,
editorconfig: style.editorconfig,
root: root.map(Path::to_path_buf),
mappings: root.map(|root| mappings(root, &enc.mappings)).unwrap_or_default(),
}
}
/// 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<ide_vfs::Fallback<'_>> {
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, true)
} else {
(&self.global_fallback, true)
/// The encoding the settings give `path`: the one chosen for the file itself, else the
/// one it [inherits](Self::inherited_encoding_for).
pub fn configured_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
match self.mappings.iter().find(|(mapped, _)| path == mapped) {
Some((_, label)) => ConfiguredEncoding { label, source: EncodingSource::File },
None => self.inherited_encoding_for(path),
}
}
/// The encoding of `path` without a choice for the file itself: the `.properties`
/// default, the nearest mapped folder above it, then the project's or the global one.
pub fn inherited_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
let folder = || {
let above = self.mappings.iter().filter(|(mapped, _)| path != mapped && path.starts_with(mapped));
above.max_by_key(|(mapped, _)| mapped.components().count())
};
(label != "utf-8").then_some(ide_vfs::Fallback { encoding: label, ascii })
if path.extension().is_some_and(|e| e == "properties") {
ConfiguredEncoding { label: &self.properties_fallback, source: EncodingSource::Properties }
} else if let Some((_, label)) = folder() {
ConfiguredEncoding { label, source: EncodingSource::Folder }
} else {
self.project_encoding_for(path)
}
}
/// The project's encoding for a file inside it, the global one for any other.
pub fn project_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
if self.root.as_ref().is_none_or(|r| path.starts_with(r)) {
ConfiguredEncoding { label: &self.project_fallback, source: EncodingSource::Project }
} else {
ConfiguredEncoding { label: &self.global_fallback, source: EncodingSource::Global }
}
}
/// Encoding for `path` when it is not valid UTF-8 or is plain ASCII (`None`: detect).
pub fn fallback_for(&self, path: &Path) -> Option<ide_vfs::Fallback<'_>> {
self.configured_encoding_for(path).fallback()
}
pub fn native_to_ascii_for(&self, path: &Path) -> bool {
@@ -81,6 +137,49 @@ impl FileDefaults {
}
}
/// The `[editor.encodings.mappings]` key of `path`: its path inside the project `root`,
/// with `/` separators. `None` for anything else.
pub fn mapping_key(root: &Path, path: &Path) -> Option<String> {
let segments: Option<Vec<&str>> = path
.strip_prefix(root)
.ok()?
.components()
.map(|c| match c {
Component::Normal(name) => name.to_str(),
_ => None,
})
.collect();
segments.filter(|s| !s.is_empty()).map(|s| s.join("/"))
}
/// The mapped paths under `root`. An entry whose key is not such a path, or whose value is
/// not an encoding label, is left out.
fn mappings(root: &Path, entries: &BTreeMap<String, String>) -> Vec<(PathBuf, String)> {
let path_of = |key: &str| {
let mut path = root.to_path_buf();
for segment in key.strip_suffix('/').unwrap_or(key).split('/') {
let mut components = Path::new(segment).components();
let plain = matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none();
if !plain || segment.contains('\\') {
return None;
}
path.push(segment);
}
Some(path)
};
let mapping = |(key, label): (&String, &String)| {
let label = normalize(label);
match (path_of(key), ide_vfs::encode("", &label, false)) {
(Some(path), Ok(_)) => Some((path, label)),
_ => {
tracing::warn!("ignoring the encoding mapping {key:?} = {label:?}");
None
}
}
};
entries.iter().filter_map(mapping).collect()
}
fn normalize(label: &str) -> String {
let l = label.trim().to_ascii_lowercase();
match l.as_str() {
@@ -108,4 +207,106 @@ mod tests {
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");
}
fn mapped(entries: &[(&str, &str)], root: &Path) -> FileDefaults {
let mut s = Settings::default();
s.editor.encodings.project = "gbk".into();
s.editor.encodings.mappings = entries.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
FileDefaults::from_settings(&s, Some(root))
}
#[test]
fn encoding_mappings_resolve_a_file_before_its_folders_and_the_project() {
let root = Path::new("/p");
let d = mapped(
&[
("src", "ISO-8859-15"),
("src/legacy", "koi8-r"),
("src/legacy/A.java", "windows-1252"),
("src/utf", "utf-8"),
("src/app.properties", "big5"),
],
root,
);
let fallback = |rel: &str| d.fallback_for(&root.join(rel));
assert_eq!(fallback("src/legacy/A.java"), Some(ide_vfs::Fallback { encoding: "windows-1252", ascii: true }));
assert_eq!(
fallback("src/legacy/B.java"),
Some(ide_vfs::Fallback { encoding: "koi8-r", ascii: true }),
"the longest folder wins"
);
assert_eq!(fallback("src/main/C.java"), Some(ide_vfs::Fallback { encoding: "iso-8859-15", ascii: true }));
assert_eq!(
fallback("srcs/C.java"),
Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }),
"a folder is matched by whole path segments"
);
assert_eq!(fallback("other/C.java"), Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }));
assert_eq!(fallback("src/utf/D.java"), None, "a UTF-8 mapping does not fall through to the project");
// `.properties` keep their own default inside a mapped folder; only their own entry overrides it.
assert_eq!(
fallback("src/legacy/b.properties"),
Some(ide_vfs::Fallback { encoding: "iso-8859-1", ascii: false })
);
assert_eq!(fallback("src/app.properties"), Some(ide_vfs::Fallback { encoding: "big5", ascii: true }));
assert_eq!(d.fallback_for(Path::new("/elsewhere/src/C.java")), None);
let source = |rel: &str| d.configured_encoding_for(&root.join(rel)).source;
assert_eq!(source("src/legacy/A.java"), EncodingSource::File);
assert_eq!(source("src/legacy/B.java"), EncodingSource::Folder);
assert_eq!(source("src/legacy/b.properties"), EncodingSource::Properties);
assert_eq!(source("other/C.java"), EncodingSource::Project);
assert_eq!(d.configured_encoding_for(Path::new("/elsewhere/C.java")).source, EncodingSource::Global);
}
#[test]
fn invalid_encoding_mappings_are_dropped() {
let root = Path::new("/p");
let d = mapped(
&[
("ok", "iso-8859-15"),
("unknown", "klingon-1"),
("", "koi8-r"),
("/abs", "koi8-r"),
("../up", "koi8-r"),
("a/./b", "koi8-r"),
("a//b", "koi8-r"),
("back\\slash", "koi8-r"),
],
root,
);
assert_eq!(d.mappings, [(root.join("ok"), "iso-8859-15".to_owned())]);
assert_eq!(d.fallback_for(&root.join("up/A.java")), Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }));
assert!(mapped(&[("ok", "iso-8859-15")], root).mappings.len() == 1);
// Without a project there is nothing the paths are relative to.
let mut s = Settings::default();
s.editor.encodings.mappings.insert("ok".into(), "gbk".into());
assert!(FileDefaults::from_settings(&s, None).mappings.is_empty());
}
#[test]
fn mapping_key_is_the_path_inside_the_project_with_slashes() {
let root = Path::new("/p");
assert_eq!(mapping_key(root, &root.join("src").join("a.b").join("A.java")).as_deref(), Some("src/a.b/A.java"));
assert_eq!(mapping_key(root, Path::new("/elsewhere/A.java")), None);
assert_eq!(mapping_key(root, root), None);
assert_eq!(mapping_key(root, Path::new("untitled:Untitled-1")), None);
let d = mapped(&[("src/a.b/A.java", "koi8-r")], root);
assert_eq!(
d.fallback_for(&root.join("src/a.b/A.java")),
Some(ide_vfs::Fallback { encoding: "koi8-r", ascii: true })
);
}
#[test]
fn nothing_mapped_resolves_as_before() {
let d = FileDefaults::from_settings(&Settings::default(), Some(Path::new("/p")));
assert!(d.mappings.is_empty());
assert_eq!(d.fallback_for(Path::new("/p/src/A.java")), None);
assert_eq!(
d.fallback_for(Path::new("/p/a.properties")),
Some(ide_vfs::Fallback { encoding: "iso-8859-1", ascii: false })
);
assert_eq!(d.configured_encoding_for(Path::new("/p/src/A.java")).label, "utf-8");
}
}
+75 -2
Переглянути файл
@@ -392,8 +392,35 @@ impl SettingsStore {
{
return Err(IdeError::invalid(format!("{setting} belongs to user settings")));
}
self.set_segments(scope, key, &key.split('.').collect::<Vec<_>>(), value)
}
/// Sets (`null`: removes) the `entry` of the map setting `map`, e.g. `editor.encodings.mappings`.
/// Unlike a dotted key of [`set`](Self::set), `entry` may hold dots: a file path.
pub fn set_map_entry(
&self,
scope: SettingsScope,
map: &str,
entry: &str,
value: serde_json::Value,
) -> IdeResult<Settings> {
if scope == SettingsScope::Project
&& let Some(setting) = user_only_setting(map, &serde_json::json!({ entry: value }))
{
return Err(IdeError::invalid(format!("{setting} belongs to user settings")));
}
let segments: Vec<&str> = map.split('.').chain([entry]).collect();
self.set_segments(scope, &format!("{map}.{entry}"), &segments, value)
}
fn set_segments(
&self,
scope: SettingsScope,
key: &str,
segments: &[&str],
value: serde_json::Value,
) -> IdeResult<Settings> {
let file = self.file(scope).ok_or_else(|| IdeError::invalid("no project is open"))?.to_path_buf();
let segments: Vec<&str> = key.split('.').collect();
if segments.iter().any(|s| s.is_empty()) {
return Err(IdeError::invalid(format!("invalid settings key {key:?}")));
}
@@ -421,7 +448,7 @@ impl SettingsStore {
.parse()
.map_err(|e| IdeError::invalid(format!("{} is not valid TOML; fix it first: {e}", file.display())))?;
let new_value = if value.is_null() { None } else { Some(json_to_toml(&value)?) };
set_in_document(&mut doc, &segments, new_value, map_entry);
set_in_document(&mut doc, segments, new_value, map_entry);
let new_text = doc.to_string();
// Validate the resulting stack before touching the disk.
@@ -792,6 +819,52 @@ mod tests {
);
}
#[test]
fn map_entry_named_by_a_path_is_written_under_its_table() {
let tmp = tempfile::tempdir().unwrap();
let cfg = tmp.path().join("cfg");
let proj = tmp.path().join("proj");
let file = proj.join(".openidea/settings.toml");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, "[editor]\ntabSize = 8 # wide\n").unwrap();
let store = SettingsStore::load(&cfg, Some(&proj));
let key = "editor.encodings.mappings";
let s = store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", json!("iso-8859-15")).unwrap();
assert_eq!(s.editor.encodings.mappings.get("src/a.b/A.java").map(String::as_str), Some("iso-8859-15"));
assert_eq!(s.editor.tab_size, 8);
let written =
"[editor]\ntabSize = 8 # wide\n\n[editor.encodings.mappings]\n\"src/a.b/A.java\" = \"iso-8859-15\"\n";
assert_eq!(std::fs::read_to_string(&file).unwrap(), written);
// Setting it again changes nothing; another entry joins the table; `null` removes one.
store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", json!("iso-8859-15")).unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), written);
store.set_map_entry(SettingsScope::Project, key, "web", json!("gbk")).unwrap();
let s = store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", Json::Null).unwrap();
assert_eq!(s.editor.encodings.mappings.into_iter().collect::<Vec<_>>(), [("web".into(), "gbk".into())]);
for (map, entry) in [("editor.encodings.nope", "a"), (key, "")] {
let err = store.set_map_entry(SettingsScope::Project, map, entry, json!("gbk")).unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
}
}
#[test]
fn an_encoding_mapping_that_is_not_a_label_does_not_drop_the_project_settings() {
let tmp = tempfile::tempdir().unwrap();
let proj = tmp.path().join("proj");
std::fs::create_dir_all(proj.join(".openidea")).unwrap();
std::fs::write(
proj.join(".openidea/settings.toml"),
"[editor]\ntabSize = 8\n[editor.encodings.mappings]\nsrc = \"gbk\"\ncount = 5\n",
)
.unwrap();
let s = SettingsStore::load(&tmp.path().join("cfg"), Some(&proj)).effective();
assert_eq!(s.editor.tab_size, 8);
assert_eq!(s.editor.encodings.mappings.into_iter().collect::<Vec<_>>(), [("src".into(), "gbk".into())]);
}
#[test]
fn set_console_log_colors() {
let tmp = tempfile::tempdir().unwrap();
+127
Переглянути файл
@@ -1735,3 +1735,130 @@ fn a_file_declared_utf8_that_is_not_utf8_is_decoded_with_the_project_encoding()
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
}
/// `[editor.encodings.mappings]` as the host hands it over: project paths with their labels.
fn encoding_mappings(f: &Fixture, entries: &[(&str, &str)]) {
let mut defaults = f.docs.file_defaults();
defaults.mappings = entries.iter().map(|(rel, label)| (in_root(f, rel), (*label).to_owned())).collect();
f.docs.set_file_defaults(defaults);
}
fn in_root(f: &Fixture, rel: &str) -> PathBuf {
rel.split('/').fold(f.root.clone(), |path, segment| path.join(segment))
}
#[test]
fn encoding_mapping_of_a_file_survives_closing_and_reopening_it() {
let f = fixture();
let path = f.root.join("A.java");
fs::write(&path, "// ação\n").unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!(doc.encoding, "utf-8");
f.docs.set_encoding(doc.id, "iso-8859-15", true).unwrap();
let chosen = f.docs.snapshot(doc.id).unwrap();
assert_eq!(chosen.text, "// ação\n");
f.docs.close(doc.id);
encoding_mappings(&f, &[("A.java", "iso-8859-15")]);
let reopened = f.docs.open(&path).unwrap();
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", chosen.text.as_str()));
// A later change on disk is read in the remembered encoding too.
fs::write(&path, b"// a\xe7\xe3o \xa4\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let reloaded = f.docs.snapshot(reopened.id).unwrap();
assert_eq!((reloaded.encoding.as_str(), reloaded.text.as_str()), ("iso-8859-15", "// ação €\n"));
assert_eq!(f.docs.load_file(&path).unwrap().encoding, "iso-8859-15", "closed-file readers agree");
}
#[test]
fn encoding_mapping_of_a_file_to_utf8_holds_in_a_latin_project() {
let f = fixture();
latin_project(&f);
let path = f.root.join("A.java");
fs::write(&path, b"class A {}\n").unwrap();
encoding_mappings(&f, &[("A.java", "utf-8")]);
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 encoding_mapping_of_a_file_beats_editorconfig_and_a_folder_mapping_loses_to_it() {
let f = fixture();
let mut defaults = f.docs.file_defaults();
defaults.project_fallback = "gbk".into();
f.docs.set_file_defaults(defaults);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = latin1\nend_of_line = crlf\n").unwrap();
fs::create_dir(f.root.join("src")).unwrap();
for name in ["src/A.java", "src/B.java", "src/notes.txt", "other.txt"] {
fs::write(in_root(&f, name), b"plain ascii\n").unwrap();
}
fs::write(in_root(&f, "src/new.txt"), b"").unwrap();
fs::write(in_root(&f, "src/latin.txt"), b"a\xe7\xe3o \xa4\n").unwrap();
encoding_mappings(&f, &[("src", "iso-8859-15"), ("src/A.java", "koi8-r")]);
let open = |name: &str| f.docs.open(&in_root(&f, name)).unwrap();
let file = open("src/A.java");
assert_eq!(file.encoding, "koi8-r", "the file's own mapping beats .editorconfig");
assert_eq!(file.line_ending, LineEnding::CrLf, ".editorconfig still sets the rest");
assert_eq!(open("src/B.java").encoding, "windows-1252", ".editorconfig beats the folder mapping");
assert_eq!(open("src/notes.txt").encoding, "iso-8859-15", "the folder mapping beats the project encoding");
assert_eq!(open("src/new.txt").encoding, "iso-8859-15", "a new file takes its folder's encoding");
assert_eq!(open("other.txt").encoding, "gbk");
let latin = open("src/latin.txt");
assert_eq!((latin.encoding.as_str(), latin.text.as_str()), ("iso-8859-15", "ação €\n"));
}
#[test]
fn encoding_mapping_of_a_folder_is_left_out_where_editorconfig_sets_the_charset() {
let f = fixture();
let mut defaults = f.docs.file_defaults();
defaults.project_fallback = "gbk".into();
f.docs.set_file_defaults(defaults);
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = latin1\n").unwrap();
fs::create_dir(f.root.join("src")).unwrap();
let path = in_root(&f, "src/B.java");
fs::write(&path, b"// \xd6\xd0\n").unwrap();
let unmapped = f.docs.open(&path).unwrap();
f.docs.close(unmapped.id);
encoding_mappings(&f, &[("src", "koi8-r")]);
let mapped = f.docs.open(&path).unwrap();
assert_eq!((mapped.encoding, mapped.text), (unmapped.encoding, unmapped.text));
assert_eq!(f.docs.load_file(&path).unwrap().encoding, "windows-1252", "closed-file readers agree");
}
#[test]
fn encoding_mapping_a_file_no_longer_decodes_in_falls_back_to_detection() {
let f = fixture();
latin_project(&f);
let path = f.root.join("A.java");
fs::write(&path, b"// a\xe7\xe3o\n").unwrap();
encoding_mappings(&f, &[("A.java", "utf-8")]);
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.encoding.as_str(), doc.text.as_str()), ("iso-8859-15", "// ação\n"));
}
#[test]
fn without_encoding_mappings_files_open_as_before() {
let f = fixture();
let settings = ide_core::settings::Settings::default();
f.docs.set_file_defaults(ide_workspace::FileDefaults::from_settings(&settings, Some(&f.root)));
assert!(f.docs.file_defaults().mappings.is_empty());
for (name, bytes) in [
("ascii.java", &b"class A {}\n"[..]),
("utf8.java", "// ação\n".as_bytes()),
("latin.java", &b"// a\xe7\xe3o de gra\xe7a, cora\xe7\xe3o\n"[..]),
("empty.java", &b""[..]),
] {
let path = f.root.join(name);
fs::write(&path, bytes).unwrap();
let detected = ide_vfs::load_text(&path).unwrap();
let doc = f.docs.open(&path).unwrap();
assert_eq!((doc.encoding, doc.text), (detected.encoding, detected.text), "{name}");
}
}
+10
Переглянути файл
@@ -140,6 +140,16 @@ Settings › Appearance & Behavior › Appearance, unless noted.
Sub-tables such as `[editor.general]`, `[editor.appearance]`, `[editor.completion]`, `[editor.tabs]`, `[editor.codeStyle]` and `[editor.encodings]` hold the options of the matching Editor pages.
`[editor.encodings.mappings]` in a project's `.openidea/settings.toml` gives a file or a folder its own encoding. Keys are paths relative to the project, with `/` separators. Choosing an encoding in the status bar adds the file here; after **Convert**, once the file is saved.
```toml
[editor.encodings.mappings]
"src/main/java" = "iso-8859-15" # every file in the folder
"web/legacy/index.jsp" = "windows-1252"
```
A file's own entry wins over `.editorconfig`. A folder's entry applies where `.editorconfig` sets no `charset`, and wins over the project encoding; the nearest folder wins. An entry with an unknown encoding or a path outside the project is ignored.
### `[files]`
| Key | Default | Description |
+10
Переглянути файл
@@ -140,6 +140,16 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
`[editor.general]`、`[editor.appearance]`、`[editor.completion]`、`[editor.tabs]`、`[editor.codeStyle]`、`[editor.encodings]` 等子表保存对应编辑器页面的选项。
项目 `.openidea/settings.toml` 中的 `[editor.encodings.mappings]` 为单个文件或文件夹指定编码。键是相对于项目的路径,使用 `/` 分隔。在状态栏中选择编码时,该文件会被添加到这里;使用 **Convert** 时,在保存文件之后添加。
```toml
[editor.encodings.mappings]
"src/main/java" = "iso-8859-15" # 文件夹中的所有文件
"web/legacy/index.jsp" = "windows-1252"
```
文件自身的条目优先于 `.editorconfig`。文件夹的条目在 `.editorconfig` 未设置 `charset` 时生效,并优先于项目编码;最近的文件夹优先。编码未知或路径在项目之外的条目会被忽略。
### `[files]`
| 键 | 默认值 | 说明 |
+1
Переглянути файл
@@ -244,6 +244,7 @@ doc_outline always project_host bin
doc_python_facts always project_host bindings async
doc_rearrange always project_host bindings async
doc_reload_from_disk always project_host bindings async
doc_remember_encoding always project_host bindings async
doc_save always project_host bindings async
doc_save_all always project_host bindings async
doc_save_as always project_host bindings async
+37 -3
Переглянути файл
@@ -623,6 +623,13 @@ export const commands = {
docRearrange: (doc: DocId) => typedError<TextEdit[], IdeError>(__TAURI_INVOKE("doc_rearrange", { doc })),
/** Load Changes from Disk: discards the buffer's unsaved changes and reads its file again. */
docReloadFromDisk: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_reload_from_disk", { doc })),
/**
* Keeps the encoding the user chose for a project file in the project's File Encodings
* mappings, so the file opens in it again. A converted document is kept once it is saved:
* until then its file is still in the old encoding. Nothing is kept for a document without
* a file in the project.
*/
docRememberEncoding: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_remember_encoding", { doc })),
docSave: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_save", { doc })),
docSaveAll: () => typedError<null, IdeError>(__TAURI_INVOKE("doc_save_all")),
/**
@@ -6867,7 +6874,7 @@ export type EditorSettings_Deserialize = {
gutterIconsDisabled?: string[],
showGutterIcons?: boolean,
codeStyle?: CodeStyleSettings_Deserialize,
encodings?: EncodingSettings,
encodings?: EncodingSettings_Deserialize,
};
export type EditorSettings_Serialize = {
@@ -6927,7 +6934,7 @@ export type EditorSettings_Serialize = {
gutterIconsDisabled: string[],
showGutterIcons: boolean,
codeStyle: CodeStyleSettings_Serialize,
encodings: EncodingSettings,
encodings: EncodingSettings_Serialize,
};
/** Editor › General › Editor Tabs. */
@@ -6960,7 +6967,10 @@ export type EditorTabsSettings = {
export type EmptyCherryPickAction = "skip" | "createEmpty";
/** Editor › File Encodings. */
export type EncodingSettings = {
export type EncodingSettings = EncodingSettings_Serialize | EncodingSettings_Deserialize;
/** Editor › File Encodings. */
export type EncodingSettings_Deserialize = {
/** Fallback for files outside the project that are not valid UTF-8 (WHATWG label). */
global?: string,
/** Encoding of new files and fallback for project files that are not valid UTF-8. */
@@ -6971,6 +6981,30 @@ export type EncodingSettings = {
nativeToAscii?: boolean,
/** Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows). */
utf8Bom?: string,
/**
* Encoding (WHATWG label) of a file or of the files in a folder, by its path
* relative to the project with `/` separators. The status bar's choice is kept here.
*/
mappings?: { [key in string]: string },
};
/** Editor › File Encodings. */
export type EncodingSettings_Serialize = {
/** Fallback for files outside the project that are not valid UTF-8 (WHATWG label). */
global: string,
/** Encoding of new files and fallback for project files that are not valid UTF-8. */
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,
/**
* Encoding (WHATWG label) of a file or of the files in a folder, by its path
* relative to the project with `/` separators. The status bar's choice is kept here.
*/
mappings: { [key in string]: string },
};
export type EntryKind = "file" | "dir" | "symlink";
+3
Переглянути файл
@@ -60,6 +60,8 @@ export interface DocBackend {
setLineEnding(doc: DocId, lineEnding: LineEnding): Promise<void>;
/** "Reload with Encoding" (`reload`) or "Convert to Encoding"; resolves to the new encoding and BOM state. */
setEncoding(doc: DocId, encoding: string, reload: boolean): Promise<DocumentEncoding>;
/** Keeps the encoding the user chose for a project file in the project's settings, for the next time it opens. */
rememberEncoding?(doc: DocId): Promise<void>;
/** Adds or removes the BOM on a UTF-8 document; the change is written on save. */
setBom(doc: DocId, hasBom: boolean): Promise<DocumentEncoding>;
outline(doc: DocId): Promise<OutlineItem[]>;
@@ -106,6 +108,7 @@ export const ipcBackend: DocBackend = {
snapshot: (doc) => call(commands.docSnapshot(doc)),
setLineEnding: async (doc, le) => void (await call(commands.docSetLineEnding(doc, le))),
setEncoding: (doc, encoding, reload) => call(commands.docSetEncoding(doc, encoding, reload)),
rememberEncoding: async (doc) => void (await call(commands.docRememberEncoding(doc))),
setBom: (doc, hasBom) => call(commands.docSetBom(doc, hasBom)),
outline: (doc) => call(commands.docOutline(doc)),
folding: (doc) => call(commands.docFolding(doc)),
+10 -2
Переглянути файл
@@ -534,12 +534,20 @@ function EncodingPicker({ meta }: { meta: DocMeta }) {
setTarget(null);
const model = editorController().manager.get(meta.path);
if (!model || !(reload ? canReload : canConvert)) return;
void editorController()
.manager.backend.setEncoding(meta.doc, encoding, reload)
const { backend } = editorController().manager;
void backend
.setEncoding(meta.doc, encoding, reload)
.then((enc) => {
model.setMeta({ encoding: enc.encoding, hasBom: enc.hasBom, ...(reload ? {} : { dirty: true }) });
// Reopening the tab must fetch the re-decoded contents, not the old cache.
if (reload && isVirtualUri(meta.path)) invalidateVirtualDocument(meta.path);
backend.rememberEncoding?.(meta.doc).catch((e: unknown) =>
notifications().notify({
level: "warning",
title: tx("The encoding was not saved to the project settings"),
body: e instanceof Error ? e.message : String(e),
}),
);
})
.catch((e: unknown) =>
notifications().notify({
+51 -1
Переглянути файл
@@ -4,13 +4,15 @@ import type { EditorStatus } from "../controller";
import type { DocMeta } from "../model/document";
const setEncoding = vi.fn();
const rememberEncoding = vi.fn();
const setMeta = vi.fn();
const notify = vi.fn();
vi.mock("../controller", async () => {
const { create } = await import("zustand");
return {
editorController: () => ({
manager: { get: () => ({ setMeta }), backend: { setEncoding } },
manager: { get: () => ({ setMeta }), backend: { setEncoding, rememberEncoding } },
slots: new Map(),
}),
useEditorStatus: create<{ status: EditorStatus | null }>(() => ({ status: null })),
@@ -20,6 +22,11 @@ vi.mock("../controller", async () => {
};
});
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify }),
}));
vi.mock("@/platform/virtualDocs", () => ({
isVirtualUri: (s: string) => s.startsWith("jdt:") || s.startsWith("jar:"),
invalidateVirtualDocument: vi.fn(),
@@ -63,6 +70,7 @@ const button = (name: string) => screen.getByRole<HTMLButtonElement>("button", {
beforeEach(() => {
vi.clearAllMocks();
rememberEncoding.mockResolvedValue(undefined);
useDocMeta.setState({}, true);
useEditorStatus.setState({ status: null });
});
@@ -142,3 +150,45 @@ it("offers ISO-8859-15, the Latin-9 encoding of legacy Western European projects
expect(setEncoding).toHaveBeenCalledWith(1, "iso-8859-15", false);
view.unmount();
});
describe("remembering the chosen encoding", () => {
const pick = (action: "Reload" | "Convert") => {
const view = openPicker(meta({ path: "/p/Main.java", readOnly: false }));
choose("ISO-8859-15");
fireEvent.click(button(action));
return view;
};
it.each(["Reload", "Convert"] as const)("keeps the choice once %s has applied it", async (action) => {
setEncoding.mockResolvedValue({ encoding: "iso-8859-15", hasBom: false });
const view = pick(action);
expect(rememberEncoding).not.toHaveBeenCalled();
await waitFor(() => expect(rememberEncoding).toHaveBeenCalledWith(1));
expect(rememberEncoding).toHaveBeenCalledTimes(1);
expect(notify).not.toHaveBeenCalled();
view.unmount();
});
it("keeps nothing when the encoding could not be applied", async () => {
setEncoding.mockRejectedValue(new Error("unmappable character"));
const view = pick("Convert");
await waitFor(() => expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error" })));
expect(rememberEncoding).not.toHaveBeenCalled();
view.unmount();
});
it("keeps the new encoding and warns when the project settings cannot be written", async () => {
setEncoding.mockResolvedValue({ encoding: "iso-8859-15", hasBom: false });
rememberEncoding.mockRejectedValue(new Error("settings.toml is not valid TOML"));
const view = pick("Convert");
await waitFor(() =>
expect(notify).toHaveBeenCalledWith({
level: "warning",
title: "The encoding was not saved to the project settings",
body: "settings.toml is not valid TOML",
}),
);
expect(setMeta).toHaveBeenCalledWith({ encoding: "iso-8859-15", hasBom: false, dirty: true });
view.unmount();
});
});
+17
Переглянути файл
@@ -0,0 +1,17 @@
import { expect, it } from "vitest";
import { EDITOR_EXTRA_DEFAULTS, validateEditorExtras } from "./editorSettings";
it("has no encoding mappings unless the settings name some", () => {
expect(EDITOR_EXTRA_DEFAULTS.encodings.mappings).toEqual({});
expect(validateEditorExtras(undefined).encodings.mappings).toEqual({});
expect(validateEditorExtras({ encodings: { mappings: "gbk" } }).encodings.mappings).toEqual({});
});
it("keeps the encoding mappings that name a label", () => {
const raw = {
encodings: { project: "gbk", mappings: { "src/main/java": "iso-8859-15", "src/A.java": 5, lib: null } },
};
const { encodings } = validateEditorExtras(raw);
expect(encodings.mappings).toEqual({ "src/main/java": "iso-8859-15" });
expect(encodings.project).toBe("gbk");
});
+12 -1
Переглянути файл
@@ -260,7 +260,15 @@ export const EDITOR_EXTRA_DEFAULTS = {
formatterOnTag: "@formatter:on",
formatterTagsRegexp: false,
},
encodings: { global: "utf-8", project: "utf-8", properties: "iso-8859-1", nativeToAscii: false, utf8Bom: "never" },
encodings: {
global: "utf-8",
project: "utf-8",
properties: "iso-8859-1",
nativeToAscii: false,
utf8Bom: "never",
/** Project-relative path of a file or folder (`/` separators) to its encoding label. */
mappings: {} as Record<string, string>,
},
};
export type EditorExtras = typeof EDITOR_EXTRA_DEFAULTS;
@@ -326,6 +334,9 @@ export function validateEditorExtras(raw: unknown): EditorExtras {
if (!DOCSTRING_FORMATS.includes(out.docstringFormat)) out.docstringFormat = "rest";
for (const k of ["codeVisionUsagesPosition", "codeVisionAuthorPosition"] as const)
if (!["top", "right"].includes(out.inlay[k])) out.inlay[k] = "top";
out.encodings.mappings = Object.fromEntries(
Object.entries(out.encodings.mappings).filter(([, label]) => typeof label === "string"),
);
out.rainbowBracketColors = Math.min(5, Math.max(2, Math.round(out.rainbowBracketColors)));
out.fontWeight = fontWeightOf(out.fontWeight, EDITOR_EXTRA_DEFAULTS.fontWeight);
out.boldFontWeight = fontWeightOf(out.boldFontWeight, EDITOR_EXTRA_DEFAULTS.boldFontWeight);
+1
Переглянути файл
@@ -896,6 +896,7 @@
"Add UTF-8 BOM": "Add UTF-8 BOM",
"Remove UTF-8 BOM": "Remove UTF-8 BOM",
"Cannot change the UTF-8 BOM": "Cannot change the UTF-8 BOM",
"The encoding was not saved to the project settings": "The encoding was not saved to the project settings",
"Convert to cURL and Copy": "Convert to cURL and Copy",
"Add Environment to Public File": "Add Environment to Public File",
"Add Environment to Private File": "Add Environment to Private File",
+1
Переглянути файл
@@ -1606,6 +1606,7 @@
"Add UTF-8 BOM": "添加 UTF-8 BOM",
"Remove UTF-8 BOM": "移除 UTF-8 BOM",
"Cannot change the UTF-8 BOM": "无法更改 UTF-8 BOM",
"The encoding was not saved to the project settings": "编码未保存到项目设置",
"Copied code keeps the editor's syntax colors and font when pasted into documents and mail.": "复制的代码粘贴到文档和邮件中时会保留编辑器的语法颜色和字体。",
"Copy": "复制",
"Copy / Paste Special": "复制/选择性粘贴",