From e65a0a6a4f66909e476cd37d928a67be900bb77c Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Tue, 1 Dec 2026 12:45:38 +0000 Subject: [PATCH 1/4] fix(editor): track file line endings as state --- src/lib/editorFile.js | 53 +++++++++++++------ src/lib/saveFile.js | 14 +++-- src/utils/eol.js | 11 ++++ tests/unit/fileSaveEvents.test.js | 2 + tests/unit/pluginFileRestoration.test.js | 67 ++++++++++++++++++++++++ 5 files changed, 125 insertions(+), 22 deletions(-) create mode 100644 src/utils/eol.js diff --git a/src/lib/editorFile.js b/src/lib/editorFile.js index b4a0841a9..1d14d6af2 100644 --- a/src/lib/editorFile.js +++ b/src/lib/editorFile.js @@ -19,6 +19,7 @@ import { openTabContextMenuOnRelease } from "handlers/tabContextMenu"; import tag from "html-tag-js"; import quickToolsAdapters from "lib/quickToolsAdapter"; import { applyHighlightStyles } from "utils/codeHighlight"; +import { detectEol, normalizeEol } from "utils/eol"; import haptic from "utils/haptic"; import helpers from "utils/helpers"; import loadMimeTypes from "utils/mimeTypes"; @@ -349,6 +350,8 @@ function maybeRecommendLanguageModeExtension(file, modeInfo) { * @property {object} [pane] target editor pane * @property {boolean} [isPanePlaceholder] temporary empty tab for an empty pane * @property {boolean} [persistInSession] restore the tab in a future app session + * @property {'unix'|'windows'} [eol] current end-of-line style + * @property {'unix'|'windows'} [savedEol] end-of-line style last saved or loaded from disk * @property {boolean} [highlightStyles] adopt static CodeMirror highlight CSS into the custom tab shadow root */ @@ -416,6 +419,8 @@ export default class EditorFile { * @type {string} */ encoding = appSettings.value.defaultFileEncoding; + #eol = "unix"; + #savedEol = "unix"; /** * Weather file is readonly * @type {boolean} @@ -698,6 +703,8 @@ export default class EditorFile { options?.diskMtime ?? options?.savedMtime, ); this.hasDiskConflict = !!options?.hasDiskConflict; + this.#eol = normalizeEol(options?.eol ?? detectEol(options?.text)); + this.#savedEol = normalizeEol(options?.savedEol ?? this.#eol); this.#hasVersionMetadata = options?.docVersion !== undefined || options?.savedVersion !== undefined || @@ -951,30 +958,26 @@ export default class EditorFile { * End of line */ get eol() { - const { doc } = this.session; - for (let lineNumber = 1; lineNumber <= doc.lines; lineNumber++) { - if (doc.line(lineNumber).text.includes("\r")) return "windows"; - } - return "unix"; + return this.#eol; + } + + get savedEol() { + return this.#savedEol; } /** * End of line - * @param {'windows'|'unit'} value + * @param {'windows'|'unix'} value */ set eol(value) { if (this.type !== "editor") return; + value = normalizeEol(value); if (this.eol === value) return; - let text = getDocText(this.session.doc); - - if (value === "windows") { - text = text.replace(/\n(? null, getIconForFile: () => "file", diff --git a/tests/unit/pluginFileRestoration.test.js b/tests/unit/pluginFileRestoration.test.js index 04268d0dc..1d41a8a5d 100644 --- a/tests/unit/pluginFileRestoration.test.js +++ b/tests/unit/pluginFileRestoration.test.js @@ -14,6 +14,7 @@ import { createEditorReadOnlyExtension, } from "cm/editorReadOnly"; import tag from "html-tag-js"; +import { detectEol, getEolSeparator, normalizeEol } from "utils/eol"; import { readRemoteFilePreview } from "utils/remoteFilePreview"; import { afterEach, expect, it, vi } from "vitest"; import { loadSourceModule } from "../helpers/loadSourceModule"; @@ -139,6 +140,7 @@ function setup() { "pages/fileBrowser": {}, "utils/helpers": helpers, "utils/Url": url, + "utils/eol": { detectEol, getEolSeparator, normalizeEol }, "./config": {}, "./editorFile": {}, "./openFolder": {}, @@ -186,6 +188,7 @@ function setup() { "html-tag-js": tag, "utils/Url": url, "utils/remoteFilePreview": { readRemoteFilePreview }, + "utils/eol": { detectEol, getEolSeparator, normalizeEol }, "utils/helpers": helpers, "./config": { DEFAULT_FILE_SESSION: "default" }, "./loadPlugins": { isInitialPluginLoadComplete: () => false }, @@ -211,6 +214,7 @@ function setup() { ); return { AUTO_SAVE, + EditorFile, confirm, error, stat, @@ -584,6 +588,7 @@ it("continues resume checks past unavailable, failing, and read-only HTTP provid "@codemirror/state": { Text }, "dialogs/alert": vi.fn(), "dialogs/confirm": f.confirm, + "utils/eol": { detectEol }, "utils/helpers": { getStatMtime: () => null }, }, { editorManager: f.manager, strings: {}, console: { warn } }, @@ -683,3 +688,65 @@ it.each([ editor.destroy(); } }); + +it("detects CRLF before CodeMirror normalization and toggles EOL as file state", async () => { + const f = setup(); + f.cache.set("file:///lazy-crlf.txt", "lazy\r\ntext\r\n"); + const direct = new f.EditorFile("direct-crlf.txt", { + id: "direct-crlf", + uri: "file:///direct-crlf.txt", + text: "one\r\ntwo\r\n", + isUnsaved: false, + render: false, + }); + const lazy = new f.EditorFile("lazy-crlf.txt", { + id: "lazy-crlf", + uri: "file:///lazy-crlf.txt", + render: false, + }); + + expect(direct.eol).toBe("windows"); + expect(direct.savedEol).toBe("windows"); + expect(direct.session.doc.toString()).toBe("one\ntwo\n"); + await lazy.load(); + expect(lazy.eol).toBe("windows"); + expect(lazy.savedEol).toBe("windows"); + + direct.eol = "unix"; + expect(direct.eol).toBe("unix"); + expect(direct.session.doc.toString()).toBe("one\ntwo\n"); + expect(direct.isUnsaved).toBe(true); + expect(f.manager.onupdate).toHaveBeenCalledWith("file-changed"); + expect(f.manager.emit).toHaveBeenCalledWith("update", "file-changed"); + + direct.eol = "windows"; + expect(direct.isUnsaved).toBe(false); +}); + +it("saves the selected EOL instead of always writing LF", async () => { + const f = setup(); + const uri = "file:///eol-save.txt"; + f.cache.set(uri, "one\r\ntwo\r\n"); + const file = new f.EditorFile("eol-save.txt", { + id: "eol-save", + uri, + text: "one\r\ntwo\r\n", + isUnsaved: false, + render: false, + }); + + await file.save(); + expect(f.cache.get(uri)).toBe("one\r\ntwo\r\n"); + expect(file.isUnsaved).toBe(false); + + file.eol = "unix"; + expect(file.isUnsaved).toBe(true); + await file.save(); + expect(f.cache.get(uri)).toBe("one\ntwo\n"); + expect(file.isUnsaved).toBe(false); + + file.eol = "windows"; + await file.save(); + expect(f.cache.get(uri)).toBe("one\r\ntwo\r\n"); + expect(file.isUnsaved).toBe(false); +}); From 1f6e88f10b01ae4819f0a089c53b5ff93c03963b Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Tue, 1 Dec 2026 12:45:38 +0000 Subject: [PATCH 2/4] fix(editor): preserve line ending state across reloads --- src/lib/checkFiles.js | 8 +++++--- src/lib/saveState.js | 2 ++ tests/unit/sessionPersistence.test.js | 15 +++++++++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/lib/checkFiles.js b/src/lib/checkFiles.js index 584ac1191..2891304e1 100644 --- a/src/lib/checkFiles.js +++ b/src/lib/checkFiles.js @@ -2,6 +2,7 @@ import fsOperation from "fileSystem"; import { Text } from "@codemirror/state"; import alert from "dialogs/alert"; import confirm from "dialogs/confirm"; +import { detectEol } from "utils/eol"; import helpers from "utils/helpers"; let checkFileEnabled = true; @@ -102,7 +103,8 @@ export default async function checkFiles() { const text = await fs.readFile(file.encoding); if (!file.tab) return; - const diskDoc = Text.of(String(text ?? "").split("\n")); + const diskEol = detectEol(text); + const diskDoc = Text.of(String(text ?? "").split(/\r\n?|\n/)); const currentDoc = file.session?.doc; if (!currentDoc?.eq?.(diskDoc)) { @@ -120,7 +122,7 @@ export default async function checkFiles() { file.markChanged = false; try { file.session.setValue(text); - file.markLoaded({ mtime }); + file.markLoaded({ mtime, eol: diskEol }); } finally { file.markChanged = true; } @@ -130,7 +132,7 @@ export default async function checkFiles() { // ignore } } else if (mtime != null && file.hasVersionMetadata) { - file.markLoaded({ mtime }); + file.markLoaded({ mtime, eol: diskEol }); } } } diff --git a/src/lib/saveState.js b/src/lib/saveState.js index 7437dc22a..c0c830be2 100644 --- a/src/lib/saveState.js +++ b/src/lib/saveState.js @@ -106,6 +106,8 @@ export default function saveState() { scrollLeft, editable: file.editable, encoding: file.encoding, + eol: file.eol, + savedEol: file.savedEol, render: activeFile?.id === file.id, folds: file.restoredFolds ?? getAllFolds(file.session), }; diff --git a/tests/unit/sessionPersistence.test.js b/tests/unit/sessionPersistence.test.js index 0082d1914..34dfaf0e6 100644 --- a/tests/unit/sessionPersistence.test.js +++ b/tests/unit/sessionPersistence.test.js @@ -145,6 +145,19 @@ describe("file session persistence", () => { expect(JSON.parse(localStorage.files)[0].folds).toEqual(file.restoredFolds); }); + it("persists current and saved EOL state", () => { + const file = createOpenFile("file:///eol.js", {}); + file.eol = "windows"; + file.isUnsaved = true; + globalThis.editorManager.files.push(file); + + saveState(); + + const savedFile = JSON.parse(localStorage.files)[0]; + expect(savedFile.eol).toBe("windows"); + expect(savedFile.savedEol).toBe("unix"); + }); + it("keeps the restored cursor while a remote tab is still loading", () => { const file = createOpenFile("sftp://example.com/restored.js", {}); file.loaded = false; @@ -191,6 +204,8 @@ function createOpenFile(uri, options) { lastScrollLeft: 0, editable: true, encoding: "UTF-8", + eol: "unix", + savedEol: "unix", persistInSession: options.persistInSession, }; } From 75a96ff5804487627d607717f8f0b804d2c45610 Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Tue, 1 Dec 2026 13:59:52 +0000 Subject: [PATCH 3/4] fix: harden EOL state restoration and saving --- src/lib/checkFiles.js | 2 +- src/lib/editorFile.js | 43 ++++++++-- src/lib/editorManager.js | 32 ++++--- src/lib/saveFile.js | 8 +- src/lib/saveState.js | 1 + tests/unit/pluginFileRestoration.test.js | 102 +++++++++++++++++++++++ tests/unit/sessionPersistence.test.js | 3 + 7 files changed, 169 insertions(+), 22 deletions(-) diff --git a/src/lib/checkFiles.js b/src/lib/checkFiles.js index 2891304e1..d616975c7 100644 --- a/src/lib/checkFiles.js +++ b/src/lib/checkFiles.js @@ -131,7 +131,7 @@ export default async function checkFiles() { } catch (error) { // ignore } - } else if (mtime != null && file.hasVersionMetadata) { + } else if (file.hasVersionMetadata) { file.markLoaded({ mtime, eol: diskEol }); } } diff --git a/src/lib/editorFile.js b/src/lib/editorFile.js index 1d14d6af2..a9aca37cb 100644 --- a/src/lib/editorFile.js +++ b/src/lib/editorFile.js @@ -351,7 +351,8 @@ function maybeRecommendLanguageModeExtension(file, modeInfo) { * @property {boolean} [isPanePlaceholder] temporary empty tab for an empty pane * @property {boolean} [persistInSession] restore the tab in a future app session * @property {'unix'|'windows'} [eol] current end-of-line style - * @property {'unix'|'windows'} [savedEol] end-of-line style last saved or loaded from disk + * @property {'unix'|'windows'|null} [savedEol] end-of-line style last saved or loaded from disk + * @property {boolean} [eolOverridden] whether the current end-of-line style was explicitly selected * @property {boolean} [highlightStyles] adopt static CodeMirror highlight CSS into the custom tab shadow root */ @@ -421,6 +422,7 @@ export default class EditorFile { encoding = appSettings.value.defaultFileEncoding; #eol = "unix"; #savedEol = "unix"; + #eolOverridden = false; /** * Weather file is readonly * @type {boolean} @@ -704,7 +706,19 @@ export default class EditorFile { ); this.hasDiskConflict = !!options?.hasDiskConflict; this.#eol = normalizeEol(options?.eol ?? detectEol(options?.text)); - this.#savedEol = normalizeEol(options?.savedEol ?? this.#eol); + if (options?.savedEol !== undefined) { + this.#savedEol = + options.savedEol === null ? null : normalizeEol(options.savedEol); + } else if ( + options?.eol !== undefined || + options?.text !== undefined || + !options?.uri + ) { + this.#savedEol = this.#eol; + } else { + this.#savedEol = null; + } + this.#eolOverridden = !!options?.eolOverridden; this.#hasVersionMetadata = options?.docVersion !== undefined || options?.savedVersion !== undefined || @@ -965,6 +979,17 @@ export default class EditorFile { return this.#savedEol; } + adoptEol(value) { + value = normalizeEol(value); + this.#savedEol = value; + if (!this.#eolOverridden) this.#eol = value; + this.refreshUnsavedState(); + } + + get eolOverridden() { + return this.#eolOverridden; + } + /** * End of line * @param {'windows'|'unix'} value @@ -972,12 +997,17 @@ export default class EditorFile { set eol(value) { if (this.type !== "editor") return; value = normalizeEol(value); - if (this.eol === value) return; + if (this.eol === value) { + if (this.#savedEol === null) this.#eolOverridden = true; + return; + } + this.#eolOverridden = true; this.#eol = value; this.refreshUnsavedState(); editorManager.onupdate("file-changed"); editorManager.emit("update", "file-changed"); + editorManager.scheduleAutosave?.(this); } /** @@ -1089,7 +1119,7 @@ export default class EditorFile { hasUnsavedChanges() { if (this.type !== "editor") return false; const currentDoc = this.#rawSession?.doc; - const eolChanged = this.#eol !== this.#savedEol; + const eolChanged = this.#savedEol !== null && this.#eol !== this.#savedEol; if (currentDoc && this.#savedDoc) { return ( this.hasDiskConflict || @@ -1117,6 +1147,7 @@ export default class EditorFile { this.#eol = normalizeEol(eol); this.#savedEol = this.#eol; } + if (this.#savedEol === null) this.#savedEol = this.#eol; this.docVersion = isUnsaved ? 1 : 0; this.savedVersion = isUnsaved ? 0 : this.docVersion; this.cacheVersion = -1; @@ -1144,7 +1175,7 @@ export default class EditorFile { if (!this.#isUnsaved) this.isUnsaved = true; } - markSaved({ mtime, savedDoc, savedVersion } = {}) { + markSaved({ mtime, savedDoc, savedVersion, eol } = {}) { const normalizedMtime = helpers.normalizeMtime(mtime); this.savedVersion = Number.isFinite(savedVersion) ? savedVersion @@ -1154,7 +1185,7 @@ export default class EditorFile { this.hasDiskConflict = false; this.#hasVersionMetadata = true; this.#savedDoc = savedDoc || this.#rawSession?.doc || null; - this.#savedEol = this.#eol; + this.#savedEol = normalizeEol(eol ?? this.#eol); this.isUnsaved = this.hasUnsavedChanges(); } diff --git a/src/lib/editorManager.js b/src/lib/editorManager.js index 0e30b6f2c..649fd6cbd 100644 --- a/src/lib/editorManager.js +++ b/src/lib/editorManager.js @@ -200,6 +200,23 @@ async function EditorManager($header, $body) { docSyncTimers.delete(file); } + function scheduleAutosave(file) { + const { autosave } = appSettings.value; + if (!file?.uri || !file.isUnsaved || !autosave) return; + const timers = getDocSyncTimers(file); + if (timers.autosaveTimeout) clearTimeout(timers.autosaveTimeout); + timers.autosaveTimeout = setTimeout(() => { + timers.autosaveTimeout = null; + file.save(AUTO_SAVE)?.catch?.((error) => { + warnRecoverable( + `Failed to autosave ${file.filename || file.uri}`, + error, + `autosave-${file.id}`, + ); + }); + }, autosave); + } + function isCoarsePointerDevice() { if (typeof window !== "undefined") { try { @@ -3429,6 +3446,7 @@ async function EditorManager($header, $body) { isCodeMirror: true, addFile, readOnlyCompartment, + scheduleAutosave, getFile, getFilePane, getPaneFiles, @@ -3977,19 +3995,7 @@ async function EditorManager($header, $body) { manager.emit("update", "file-changed"); toggleProblemButton(); - const { autosave } = appSettings.value; - if (file.uri && file.isUnsaved && autosave) { - timers.autosaveTimeout = setTimeout(() => { - timers.autosaveTimeout = null; - file.save(AUTO_SAVE)?.catch?.((error) => { - warnRecoverable( - `Failed to autosave ${file.filename || file.uri}`, - error, - `autosave-${file.id}`, - ); - }); - }, autosave); - } + scheduleAutosave(file); file.markChanged = true; }, TIMEOUT_VALUE); diff --git a/src/lib/saveFile.js b/src/lib/saveFile.js index de08c9006..76f36bc28 100644 --- a/src/lib/saveFile.js +++ b/src/lib/saveFile.js @@ -158,7 +158,9 @@ async function saveFile( if (!isCurrent()) return false; unchanged = helpers.getStatMtime(stat) === file.savedMtime; } - if (unchanged && file.savedEol) { + if (unchanged && file.savedEol === null) { + file.adoptEol(detectEol(diskText)); + } else if (unchanged && file.savedEol) { unchanged = detectEol(diskText) === file.savedEol; } if (!unchanged) { @@ -188,8 +190,9 @@ async function saveFile( const savedDoc = file.session?.doc || null; const savedVersion = file.docVersion; + const savedEol = file.eol; const data = savedDoc - ? savedDoc.sliceString(0, savedDoc.length, getEolSeparator(file.eol)) + ? savedDoc.sliceString(0, savedDoc.length, getEolSeparator(savedEol)) : ""; if (!isCurrent()) return false; @@ -201,6 +204,7 @@ async function saveFile( mtime: helpers.getStatMtime(stat), savedDoc, savedVersion, + eol: savedEol, }); saved = true; diff --git a/src/lib/saveState.js b/src/lib/saveState.js index c0c830be2..0763f0409 100644 --- a/src/lib/saveState.js +++ b/src/lib/saveState.js @@ -108,6 +108,7 @@ export default function saveState() { encoding: file.encoding, eol: file.eol, savedEol: file.savedEol, + eolOverridden: file.eolOverridden, render: activeFile?.id === file.id, folds: file.restoredFolds ?? getAllFolds(file.session), }; diff --git a/tests/unit/pluginFileRestoration.test.js b/tests/unit/pluginFileRestoration.test.js index 1d41a8a5d..cec90cd6f 100644 --- a/tests/unit/pluginFileRestoration.test.js +++ b/tests/unit/pluginFileRestoration.test.js @@ -546,6 +546,7 @@ it("allows unchanged-source edits and stops failed or obsolete source verificati it("continues resume checks past unavailable, failing, and read-only HTTP providers", async () => { const f = setup(); + f.cache.set("file:///local.js", "local\ncontent"); f.cache.set("file:///cache/offline", "cached"); f.cache.set("file:///cache/broken", "cached"); f.cache.set("file:///cache/http", "remote content"); @@ -593,12 +594,14 @@ it("continues resume checks past unavailable, failing, and read-only HTTP provid }, { editorManager: f.manager, strings: {}, console: { warn } }, ); + f.cache.set("file:///local.js", "local\r\ncontent"); f.read.mockClear(); await checkFiles(); expect(warn).toHaveBeenCalledOnce(); expect(f.read).toHaveBeenCalledWith("file:///local.js", "utf-8"); expect(f.confirm).not.toHaveBeenCalled(); expect(f.cache.get("file:///cache/offline")).toBe("cached"); + expect(f.manager.getFile("local", "id").eol).toBe("windows"); expect(f.manager.files.every((file) => file.tab)).toBe(true); }); @@ -750,3 +753,102 @@ it("saves the selected EOL instead of always writing LF", async () => { expect(f.cache.get(uri)).toBe("one\r\ntwo\r\n"); expect(file.isUnsaved).toBe(false); }); + +it("keeps an EOL toggle made during a save unsaved", async () => { + const f = setup(); + const uri = "file:///eol-race.txt"; + f.cache.set(uri, "one\ntwo\n"); + const file = new f.EditorFile("eol-race.txt", { + id: "eol-race", + uri, + text: "one\ntwo\n", + isUnsaved: false, + render: false, + }); + await vi.runAllTimersAsync(); + + let finishWrite; + let writeText; + f.write.mockImplementationOnce((target, text) => { + writeText = text; + return new Promise((resolve) => { + finishWrite = () => resolve(f.cache.set(target, text)); + }); + }); + file.eol = "windows"; + const saving = file.save(); + await vi.waitFor(() => expect(finishWrite).toBeTypeOf("function")); + expect(writeText).toBe("one\r\ntwo\r\n"); + + file.eol = "unix"; + finishWrite(); + expect(await saving).toBe(true); + expect(f.cache.get(uri)).toBe("one\r\ntwo\r\n"); + expect(file.savedEol).toBe("windows"); + expect(file.eol).toBe("unix"); + expect(file.isUnsaved).toBe(true); +}); + +it("recovers missing legacy EOL metadata from disk before saving", async () => { + const f = setup(); + const uri = "file:///legacy-crlf.txt"; + f.cache.set(uri, "one\r\ntwo\r\n"); + f.cache.set("file:///cache/legacy-eol", "one\ntwo\n"); + await f.restoreFiles([ + { + id: "legacy-eol", + uri, + filename: "legacy-crlf.txt", + isUnsaved: false, + }, + ]); + const [file] = f.manager.files; + await file.load(); + + expect(file.eol).toBe("unix"); + expect(file.savedEol).toBe(null); + expect(await file.save()).toBe(true); + expect(f.confirm).not.toHaveBeenCalled(); + expect(f.cache.get(uri)).toBe("one\r\ntwo\r\n"); + expect(file.eol).toBe("windows"); + expect(file.savedEol).toBe("windows"); + expect(file.isUnsaved).toBe(false); +}); + +it("delegates EOL-only changes to autosave scheduling", () => { + const f = setup(); + f.manager.scheduleAutosave = vi.fn(); + const file = new f.EditorFile("autosave-eol.txt", { + id: "autosave-eol", + uri: "file:///autosave-eol.txt", + text: "one\ntwo\n", + isUnsaved: false, + render: false, + }); + + file.eol = "windows"; + expect(f.manager.scheduleAutosave).toHaveBeenCalledWith(file); +}); + +it("preserves an explicit EOL choice while recovering legacy metadata", async () => { + const f = setup(); + const uri = "file:///legacy-explicit-eol.txt"; + f.cache.set(uri, "one\ntwo\n"); + f.cache.set("file:///cache/legacy-explicit-eol", "one\ntwo\n"); + await f.restoreFiles([ + { + id: "legacy-explicit-eol", + uri, + filename: "legacy-explicit-eol.txt", + isUnsaved: false, + }, + ]); + const [file] = f.manager.files; + await file.load(); + + file.eol = "windows"; + expect(await file.save()).toBe(true); + expect(f.cache.get(uri)).toBe("one\r\ntwo\r\n"); + expect(file.eol).toBe("windows"); + expect(file.savedEol).toBe("windows"); +}); diff --git a/tests/unit/sessionPersistence.test.js b/tests/unit/sessionPersistence.test.js index 34dfaf0e6..4e0ef7ade 100644 --- a/tests/unit/sessionPersistence.test.js +++ b/tests/unit/sessionPersistence.test.js @@ -148,6 +148,7 @@ describe("file session persistence", () => { it("persists current and saved EOL state", () => { const file = createOpenFile("file:///eol.js", {}); file.eol = "windows"; + file.eolOverridden = true; file.isUnsaved = true; globalThis.editorManager.files.push(file); @@ -156,6 +157,7 @@ describe("file session persistence", () => { const savedFile = JSON.parse(localStorage.files)[0]; expect(savedFile.eol).toBe("windows"); expect(savedFile.savedEol).toBe("unix"); + expect(savedFile.eolOverridden).toBe(true); }); it("keeps the restored cursor while a remote tab is still loading", () => { @@ -206,6 +208,7 @@ function createOpenFile(uri, options) { encoding: "UTF-8", eol: "unix", savedEol: "unix", + eolOverridden: false, persistInSession: options.persistInSession, }; } From ceb88d9669f2ea646227617304ee5871df2b9bc6 Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Tue, 1 Dec 2026 19:52:55 +0000 Subject: [PATCH 4/4] fix: preserve pending EOL choices --- src/lib/checkFiles.js | 15 +++++- src/lib/editorFile.js | 7 ++- tests/unit/pluginFileRestoration.test.js | 64 ++++++++++++++++++++++++ 3 files changed, 84 insertions(+), 2 deletions(-) diff --git a/src/lib/checkFiles.js b/src/lib/checkFiles.js index d616975c7..404f8e640 100644 --- a/src/lib/checkFiles.js +++ b/src/lib/checkFiles.js @@ -101,8 +101,21 @@ export default async function checkFiles() { if (file.isUnsaved) return; + const docVersion = file.docVersion; + const eol = file.eol; + const savedEol = file.savedEol; + const uri = file.uri; const text = await fs.readFile(file.encoding); - if (!file.tab) return; + if ( + !file.tab || + file.isUnsaved || + file.uri !== uri || + file.docVersion !== docVersion || + file.eol !== eol || + file.savedEol !== savedEol + ) { + return; + } const diskEol = detectEol(text); const diskDoc = Text.of(String(text ?? "").split(/\r\n?|\n/)); const currentDoc = file.session?.doc; diff --git a/src/lib/editorFile.js b/src/lib/editorFile.js index a9aca37cb..e65dc282f 100644 --- a/src/lib/editorFile.js +++ b/src/lib/editorFile.js @@ -1119,7 +1119,10 @@ export default class EditorFile { hasUnsavedChanges() { if (this.type !== "editor") return false; const currentDoc = this.#rawSession?.doc; - const eolChanged = this.#savedEol !== null && this.#eol !== this.#savedEol; + const eolChanged = + this.#savedEol === null + ? this.#eolOverridden + : this.#eol !== this.#savedEol; if (currentDoc && this.#savedDoc) { return ( this.hasDiskConflict || @@ -1143,6 +1146,7 @@ export default class EditorFile { markLoaded({ mtime, isUnsaved = false, savedDoc = null, eol } = {}) { const normalizedMtime = helpers.normalizeMtime(mtime); + this.#eolOverridden = false; if (eol !== undefined) { this.#eol = normalizeEol(eol); this.#savedEol = this.#eol; @@ -1177,6 +1181,7 @@ export default class EditorFile { markSaved({ mtime, savedDoc, savedVersion, eol } = {}) { const normalizedMtime = helpers.normalizeMtime(mtime); + this.#eolOverridden = false; this.savedVersion = Number.isFinite(savedVersion) ? savedVersion : this.docVersion; diff --git a/tests/unit/pluginFileRestoration.test.js b/tests/unit/pluginFileRestoration.test.js index cec90cd6f..6ddd83b8c 100644 --- a/tests/unit/pluginFileRestoration.test.js +++ b/tests/unit/pluginFileRestoration.test.js @@ -852,3 +852,67 @@ it("preserves an explicit EOL choice while recovering legacy metadata", async () expect(file.eol).toBe("windows"); expect(file.savedEol).toBe("windows"); }); + +it("marks an explicit EOL choice unsaved while legacy metadata is unknown", async () => { + const f = setup(); + const uri = "file:///legacy-dirty-eol.txt"; + f.cache.set(uri, "one\r\ntwo\r\n"); + f.cache.set("file:///cache/legacy-dirty-eol", "one\ntwo\n"); + await f.restoreFiles([ + { + id: "legacy-dirty-eol", + uri, + filename: "legacy-dirty-eol.txt", + isUnsaved: false, + }, + ]); + const [file] = f.manager.files; + await file.load(); + + expect(file.savedEol).toBe(null); + expect(file.isUnsaved).toBe(false); + file.eol = "windows"; + expect(file.isUnsaved).toBe(true); +}); + +it("does not adopt a disk EOL after the user changes it during a file check", async () => { + const f = setup(); + const uri = "file:///check-eol-race.txt"; + f.cache.set(uri, "one\ntwo\n"); + const file = new f.EditorFile("check-eol-race.txt", { + id: "check-eol-race", + uri, + text: "one\ntwo\n", + isUnsaved: false, + render: false, + }); + f.manager.activeFile = file; + const { default: checkFiles } = loadSourceModule( + "src/lib/checkFiles.js", + { + fileSystem: f.fs, + "@codemirror/state": { Text }, + "dialogs/alert": vi.fn(), + "dialogs/confirm": f.confirm, + "utils/eol": { detectEol }, + "utils/helpers": { getStatMtime: () => null }, + }, + { editorManager: f.manager, strings: {}, console: { warn: vi.fn() } }, + ); + let finishRead; + f.read.mockImplementationOnce(async (target) => { + await new Promise((resolve) => { + finishRead = resolve; + }); + return f.cache.get(target); + }); + + const checking = checkFiles(); + await vi.waitFor(() => expect(finishRead).toBeTypeOf("function")); + file.eol = "windows"; + finishRead(); + await checking; + + expect(file.eol).toBe("windows"); + expect(file.isUnsaved).toBe(true); +});