From 3d3ed6e1206382a79d892aa26083ced0b4e290d8 Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Mon, 30 Nov 2026 08:00:08 +0800 Subject: [PATCH] fix(editor): update the status bar when a file's encoding or line ending changes (#6882) When another program rewrote a clean open file in a different encoding or line ending, Documents::reload_from_disk re-detected and stored the new values but nothing sent them to the editor's DocMeta, so the status bar kept the old encoding and line separator until the tab was reopened; Load Changes from Disk had the same gap for the BOM. Adds IdeEvent::DocEncoding (modelled on DocLanguage): both reload paths emit it through one helper only when the encoding, BOM or line ending changed, and the DocumentManager updates the meta. Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- crates/ide-core/src/event.rs | 9 +++++ crates/ide-host/src/rpc.rs | 1 + crates/ide-text/src/lib.rs | 9 +++++ crates/ide-workspace/src/documents.rs | 22 +++++++++++ crates/ide-workspace/tests/documents.rs | 52 +++++++++++++++++++++++++ src/bindings.ts | 7 ++++ src/editor/core/backend.ts | 5 +++ src/editor/core/model/document.test.ts | 23 +++++++++++ src/editor/core/model/document.ts | 5 +++ 9 files changed, 133 insertions(+) diff --git a/crates/ide-core/src/event.rs b/crates/ide-core/src/event.rs index 882397d94..747b9b3bd 100644 --- a/crates/ide-core/src/event.rs +++ b/crates/ide-core/src/event.rs @@ -174,6 +174,15 @@ pub enum IdeEvent { /// See `DocumentInfo::ui_mode`. ui_mode: Option, }, + /// A reload from disk changed an open document's encoding, BOM or line ending (the file + /// was rewritten by another program), which the editor only learns when it opens. + DocEncoding { + doc: DocId, + encoding: String, + has_bom: bool, + /// A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`. + line_ending: String, + }, /// Full replacement of diagnostics for one file from one producer. Diagnostics { path: crate::IpcPath, diff --git a/crates/ide-host/src/rpc.rs b/crates/ide-host/src/rpc.rs index 66d33d6c7..fdda38269 100644 --- a/crates/ide-host/src/rpc.rs +++ b/crates/ide-host/src/rpc.rs @@ -375,6 +375,7 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool { | IdeEvent::DocDiskConflict { .. } | IdeEvent::WorkspaceEditApplied { .. } | IdeEvent::DocLanguage { .. } + | IdeEvent::DocEncoding { .. } | IdeEvent::Diagnostics { .. } | IdeEvent::Task { .. } | IdeEvent::IndexState { .. } diff --git a/crates/ide-text/src/lib.rs b/crates/ide-text/src/lib.rs index 0df3cf628..36841e6ee 100644 --- a/crates/ide-text/src/lib.rs +++ b/crates/ide-text/src/lib.rs @@ -36,6 +36,15 @@ impl LineEnding { } } + /// The serialized form (`serde(rename_all = "camelCase")`) the frontend's `LineEnding` uses. + pub fn name(self) -> &'static str { + match self { + Self::Lf => "lf", + Self::CrLf => "crLf", + Self::Cr => "cr", + } + } + /// The dominant line ending of `text`; ties and text without any line /// break resolve to [`LineEnding::Lf`]. pub fn detect(text: &str) -> Self { diff --git a/crates/ide-workspace/src/documents.rs b/crates/ide-workspace/src/documents.rs index 98f7a7144..d6f92edd5 100644 --- a/crates/ide-workspace/src/documents.rs +++ b/crates/ide-workspace/src/documents.rs @@ -1406,6 +1406,24 @@ impl Documents { ids.into_iter().filter_map(|id| saved(id).ok().flatten()).collect() } + /// The encoding, BOM and line ending the editor shows for a document. + fn encoding_state(st: &DocState) -> (String, bool, LineEnding) { + (st.encoding.clone(), st.has_bom, st.doc.line_ending()) + } + + /// The editor reads these at open; no reply carries a change made by a reload back, so + /// tell it when `before` no longer holds. + fn announce_encoding(&self, doc: DocId, st: &DocState, before: (String, bool, LineEnding)) { + if before != Self::encoding_state(st) { + self.sink.emit(IdeEvent::DocEncoding { + doc, + encoding: st.encoding.clone(), + has_bom: st.has_bom, + line_ending: st.doc.line_ending().name().to_owned(), + }); + } + } + /// 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<()> { @@ -1413,12 +1431,14 @@ impl Documents { if st.uri.is_some() || st.binary { return Err(IdeError::invalid("only a file's text can be reloaded from disk")); } + let before = Self::encoding_state(st); 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); + self.announce_encoding(doc, st, before); Ok(()) }) } @@ -1603,6 +1623,7 @@ impl Documents { self.disk_conflict(id, st, &meta); return Ok(()); } + let before = Self::encoding_state(st); st.encoding = loaded.encoding; st.has_bom = loaded.has_bom; st.large = loaded.large; @@ -1610,6 +1631,7 @@ impl Documents { st.doc.set_line_ending(ec_eol.unwrap_or_else(|| LineEnding::detect(&loaded.text))); self.replace_locked(id, st, &loaded.text)?; st.synced(loaded.mtime_ms); + self.announce_encoding(id, st, before); Ok(()) }); if let Err(e) = result { diff --git a/crates/ide-workspace/tests/documents.rs b/crates/ide-workspace/tests/documents.rs index 408804bab..d3cb2ef7c 100644 --- a/crates/ide-workspace/tests/documents.rs +++ b/crates/ide-workspace/tests/documents.rs @@ -812,6 +812,58 @@ fn external_changes_redetect_an_encoding_the_user_never_chose() { assert_eq!((snapshot.text.as_str(), snapshot.encoding.as_str()), ("wide", "utf-16le")); } +#[test] +fn external_reload_tells_the_editor_the_new_encoding_and_line_ending() { + let f = fixture(); + let path = f.root.join("plain.txt"); + fs::write(&path, "a\r\nb\r\n").unwrap(); + let info = f.docs.open(&path).unwrap(); + fs::write(&path, ide_vfs::encode("a\nb\n", "utf-16le", true).unwrap()).unwrap(); + f.docs.on_disk_changed(std::slice::from_ref(&path)); + let seen: Vec<_> = f + .events + .lock() + .iter() + .filter_map(|e| match e { + IdeEvent::DocEncoding { doc, encoding, has_bom, line_ending } if *doc == info.id => { + Some((encoding.clone(), *has_bom, line_ending.clone())) + } + _ => None, + }) + .collect(); + assert_eq!(seen, [("utf-16le".to_owned(), true, "lf".to_owned())]); + + // A reload that changes none of them stays quiet. + fs::write(&path, ide_vfs::encode("a\nb\nc\n", "utf-16le", true).unwrap()).unwrap(); + f.docs.on_disk_changed(std::slice::from_ref(&path)); + assert_eq!(f.docs.snapshot(info.id).unwrap().text, "a\nb\nc\n"); + let count = f.events.lock().iter().filter(|e| matches!(e, IdeEvent::DocEncoding { .. })).count(); + assert_eq!(count, 1); +} + +#[test] +fn load_changes_from_disk_tells_the_editor_a_new_bom() { + let f = fixture(); + let path = f.root.join("plain.txt"); + fs::write(&path, "text").unwrap(); + let info = f.docs.open(&path).unwrap(); + f.docs.replace_all(info.id, "edited").unwrap(); + fs::write(&path, b"\xEF\xBB\xBFtext").unwrap(); + f.docs.discard_and_reload(info.id).unwrap(); + let seen: Vec<_> = f + .events + .lock() + .iter() + .filter_map(|e| match e { + IdeEvent::DocEncoding { doc, encoding, has_bom, .. } if *doc == info.id => { + Some((encoding.clone(), *has_bom)) + } + _ => None, + }) + .collect(); + assert_eq!(seen, [("utf-8".to_owned(), true)]); +} + #[test] fn utf8_bom_is_added_and_removed_on_save() { let f = fixture(); diff --git a/src/bindings.ts b/src/bindings.ts index 813bb4d31..56916018e 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -9465,6 +9465,13 @@ byAgent: boolean } | { type: "docLanguage"; doc: DocId; language: LanguageId; /** See `DocumentInfo::ui_mode`. */ uiMode: string | null } | +/** + * A reload from disk changed an open document's encoding, BOM or line ending (the file + * was rewritten by another program), which the editor only learns when it opens. + */ +{ type: "docEncoding"; doc: DocId; encoding: string; hasBom: boolean; +/** A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`. */ +lineEnding: string } | /** Full replacement of diagnostics for one file from one producer. */ { type: "diagnostics"; path: IpcPath; source: string; items: Diagnostic[] } | /** Progress of a background task; `fraction` is `None` when indeterminate. */ diff --git a/src/editor/core/backend.ts b/src/editor/core/backend.ts index b4ddd73bb..f1c378b73 100644 --- a/src/editor/core/backend.ts +++ b/src/editor/core/backend.ts @@ -95,6 +95,10 @@ export interface DocBackend { * Type), or its own mode (`DocumentInfo.uiMode`). */ onLanguage?(handler: (e: { doc: DocId; language: string; uiMode: string | null }) => void): () => void; + /** A reload from disk changed an open document's encoding, BOM or line ending. */ + onEncoding?( + handler: (e: { doc: DocId; encoding: string; hasBom: boolean; lineEnding: LineEnding }) => void, + ): () => void; } export const ipcBackend: DocBackend = { @@ -130,6 +134,7 @@ export const ipcBackend: DocBackend = { return () => void listener.then((unlisten) => unlisten()); }, onLanguage: (h) => onIdeEvent("docLanguage", (e) => h(e)), + onEncoding: (h) => onIdeEvent("docEncoding", (e) => h({ ...e, lineEnding: e.lineEnding as LineEnding })), }; // --------------------------------------------------------------------------- diff --git a/src/editor/core/model/document.test.ts b/src/editor/core/model/document.test.ts index 95721a72a..dcb31b6dd 100644 --- a/src/editor/core/model/document.test.ts +++ b/src/editor/core/model/document.test.ts @@ -624,6 +624,29 @@ describe("DocumentManager + slots", () => { expect(slot.currentState().facet(languageFacet)?.name).not.toBe("angular"); }); + it("follows the encoding and line ending a reload from disk changed", async () => { + const { backend, manager } = setup({ "/p/a.txt": "abc" }); + let handler: Parameters>[0] = () => {}; + backend.onEncoding = (h) => { + handler = h; + return () => {}; + }; + manager.stop(); + manager.start(); + const model = await manager.acquire("/p/a.txt"); + try { + handler({ doc: model.doc, encoding: "utf-16le", hasBom: true, lineEnding: "crLf" }); + expect(useDocMeta.getState()["/p/a.txt"]).toMatchObject({ + encoding: "utf-16le", + hasBom: true, + lineEnding: "crLf", + }); + } finally { + manager.releaseProjectDocuments(); + manager.stop(); + } + }); + it.each(["ts", "mts", "cts"])("loads Angular inline templates for .%s documents", async (ext) => { const path = `/p/src/app.${ext}`; const { manager } = setup({ diff --git a/src/editor/core/model/document.ts b/src/editor/core/model/document.ts index ce0884a95..f346a7edc 100644 --- a/src/editor/core/model/document.ts +++ b/src/editor/core/model/document.ts @@ -914,6 +914,11 @@ export class DocumentManager { this.backend.onPatched((e) => this.modelsOf(e.doc).forEach((m) => m.sync.remote(e))), this.backend.onLanguage?.((e) => this.modelsOf(e.doc).forEach((m) => m.setLanguage(e.language, e.uiMode))) ?? (() => {}), + this.backend.onEncoding?.((e) => + this.modelsOf(e.doc).forEach((m) => + m.setMeta({ encoding: e.encoding, hasBom: e.hasBom, lineEnding: e.lineEnding }), + ), + ) ?? (() => {}), this.backend.onDirty((e) => this.modelsOf(e.doc).forEach((m) => m.onBackendDirty(e))), ); let prev = useEditorRegistry.getState().contributions;