Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions src/lib/checkFiles.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -100,9 +101,23 @@ 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;
const diskDoc = Text.of(String(text ?? "").split("\n"));
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;

if (!currentDoc?.eq?.(diskDoc)) {
Expand All @@ -120,7 +135,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;
}
Expand All @@ -129,8 +144,8 @@ export default async function checkFiles() {
} catch (error) {
// ignore
}
} else if (mtime != null && file.hasVersionMetadata) {
file.markLoaded({ mtime });
} else if (file.hasVersionMetadata) {
file.markLoaded({ mtime, eol: diskEol });
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}
}
}
Expand Down
91 changes: 73 additions & 18 deletions src/lib/editorFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -349,6 +350,9 @@ 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'|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
*/

Expand Down Expand Up @@ -416,6 +420,9 @@ export default class EditorFile {
* @type {string}
*/
encoding = appSettings.value.defaultFileEncoding;
#eol = "unix";
#savedEol = "unix";
#eolOverridden = false;
/**
* Weather file is readonly
* @type {boolean}
Expand Down Expand Up @@ -698,6 +705,20 @@ export default class EditorFile {
options?.diskMtime ?? options?.savedMtime,
);
this.hasDiskConflict = !!options?.hasDiskConflict;
this.#eol = normalizeEol(options?.eol ?? detectEol(options?.text));
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 ||
Expand Down Expand Up @@ -951,30 +972,42 @@ 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;
}

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'|'unit'} value
* @param {'windows'|'unix'} value
*/
set eol(value) {
if (this.type !== "editor") return;
if (this.eol === value) return;
let text = getDocText(this.session.doc);

if (value === "windows") {
text = text.replace(/\n(?<!\r\n)/g, "\r\n");
} else {
text = text.replace(/\r/g, "");
value = normalizeEol(value);
if (this.eol === value) {
if (this.#savedEol === null) this.#eolOverridden = true;
return;
}

// Update the document in the session
this.session.setValue(text);
this.#eolOverridden = true;
this.#eol = value;
this.refreshUnsavedState();
editorManager.onupdate("file-changed");
editorManager.emit("update", "file-changed");
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
editorManager.scheduleAutosave?.(this);
}

/**
Expand Down Expand Up @@ -1007,6 +1040,7 @@ export default class EditorFile {
this.savedVersion = this.docVersion;
this.hasDiskConflict = false;
this.#savedDoc = this.#rawSession?.doc || this.#savedDoc;
this.#savedEol = this.#eol;
}
this.#isUnsaved = value;

Expand Down Expand Up @@ -1085,16 +1119,22 @@ export default class EditorFile {
hasUnsavedChanges() {
if (this.type !== "editor") return false;
const currentDoc = this.#rawSession?.doc;
const eolChanged =
this.#savedEol === null
? this.#eolOverridden
: this.#eol !== this.#savedEol;
if (currentDoc && this.#savedDoc) {
return (
this.hasDiskConflict ||
this.deletedFile ||
eolChanged ||
!currentDoc.eq(this.#savedDoc)
);
}
return (
this.hasDiskConflict ||
this.deletedFile ||
eolChanged ||
this.docVersion !== this.savedVersion
);
}
Expand All @@ -1104,8 +1144,14 @@ export default class EditorFile {
return this.#isUnsaved;
}

markLoaded({ mtime, isUnsaved = false, savedDoc = null } = {}) {
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;
}
if (this.#savedEol === null) this.#savedEol = this.#eol;
this.docVersion = isUnsaved ? 1 : 0;
this.savedVersion = isUnsaved ? 0 : this.docVersion;
this.cacheVersion = -1;
Expand Down Expand Up @@ -1133,8 +1179,9 @@ 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.#eolOverridden = false;
this.savedVersion = Number.isFinite(savedVersion)
? savedVersion
: this.docVersion;
Expand All @@ -1143,6 +1190,7 @@ export default class EditorFile {
this.hasDiskConflict = false;
this.#hasVersionMetadata = true;
this.#savedDoc = savedDoc || this.#rawSession?.doc || null;
this.#savedEol = normalizeEol(eol ?? this.#eol);
this.isUnsaved = this.hasUnsavedChanges();
}

Expand Down Expand Up @@ -1909,6 +1957,7 @@ export default class EditorFile {
if (!this.#tab) return;
let file = null;
let loadedMtime = this.savedMtime;
let loadedEol = null;
let savedDoc = null;

if (!cacheExists && isTransportFile) {
Expand Down Expand Up @@ -1945,6 +1994,7 @@ export default class EditorFile {
if (!this.#tab) return;
loadedMtime = helpers.getStatMtime(stat);
const diskValue = await file.readFile(this.encoding);
loadedEol = detectEol(diskValue);
savedDoc = EditorState.create({ doc: diskValue }).doc;
value = diskValue;
} else {
Expand All @@ -1968,7 +2018,12 @@ export default class EditorFile {
// Recovery data is the document, not a newly verified disk snapshot.
this.#savedDoc = isUnsaved ? null : this.#rawSession.doc;
} else {
this.markLoaded({ mtime: loadedMtime, isUnsaved, savedDoc });
this.markLoaded({
mtime: loadedMtime,
isUnsaved,
savedDoc,
eol: loadedEol ?? detectEol(value),
});
}
this.#loadOptions = null;
this.markChanged = true;
Expand Down
32 changes: 19 additions & 13 deletions src/lib/editorManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -3429,6 +3446,7 @@ async function EditorManager($header, $body) {
isCodeMirror: true,
addFile,
readOnlyCompartment,
scheduleAutosave,
getFile,
getFilePane,
getPaneFiles,
Expand Down Expand Up @@ -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);
Expand Down
18 changes: 13 additions & 5 deletions src/lib/saveFile.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import fsOperation, { hasProvider } from "fileSystem";
import { Text } from "@codemirror/state";
import { getDocText } from "cm/editorUtils";
import toast from "components/toast";
import confirm from "dialogs/confirm";
import prompt from "dialogs/prompt";
import select from "dialogs/select";
import recents from "lib/recents";
import FileBrowser from "pages/fileBrowser";
import { detectEol, getEolSeparator } from "utils/eol";
import helpers from "utils/helpers";
import Url from "utils/Url";
import config from "./config";
Expand Down Expand Up @@ -147,9 +147,8 @@ async function saveFile(
if (!fileOnDevice || !isCurrent()) return false;

if (!isSaveAs && !isNewFile) {
const source = Text.of(
(await fileOnDevice.readFile(encoding)).split(/\r\n?|\n/),
);
const diskText = await fileOnDevice.readFile(encoding);
const source = Text.of(diskText.split(/\r\n?|\n/));
if (!isCurrent()) return false;
let unchanged = source.eq(file.session.doc);
if (!unchanged && baseline) {
Expand All @@ -159,6 +158,11 @@ async function saveFile(
if (!isCurrent()) return false;
unchanged = helpers.getStatMtime(stat) === file.savedMtime;
}
if (unchanged && file.savedEol === null) {
file.adoptEol(detectEol(diskText));
} else if (unchanged && file.savedEol) {
unchanged = detectEol(diskText) === file.savedEol;
}
if (!unchanged) {
file.hasDiskConflict = true;
file.refreshUnsavedState();
Expand Down Expand Up @@ -186,7 +190,10 @@ async function saveFile(

const savedDoc = file.session?.doc || null;
const savedVersion = file.docVersion;
const data = getDocText(savedDoc);
const savedEol = file.eol;
const data = savedDoc
? savedDoc.sliceString(0, savedDoc.length, getEolSeparator(savedEol))
: "";
if (!isCurrent()) return false;

await fileOnDevice.writeFile(data, encoding);
Expand All @@ -197,6 +204,7 @@ async function saveFile(
mtime: helpers.getStatMtime(stat),
savedDoc,
savedVersion,
eol: savedEol,
});
saved = true;

Expand Down
3 changes: 3 additions & 0 deletions src/lib/saveState.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ export default function saveState() {
scrollLeft,
editable: file.editable,
encoding: file.encoding,
eol: file.eol,
savedEol: file.savedEol,
eolOverridden: file.eolOverridden,
render: activeFile?.id === file.id,
folds: file.restoredFolds ?? getAllFolds(file.session),
};
Expand Down
11 changes: 11 additions & 0 deletions src/utils/eol.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export function detectEol(text) {
return String(text ?? "").includes("\r") ? "windows" : "unix";
}

export function normalizeEol(value) {
return value === "windows" ? "windows" : "unix";
}

export function getEolSeparator(value) {
return normalizeEol(value) === "windows" ? "\r\n" : "\n";
}
Loading