From 21b7f709b978fcf536c8100b851ea3bbca4ac9ec Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:11:36 +0100 Subject: [PATCH 01/36] showFileInfo faster word counting, 10-20% --- src/lib/showFileInfo.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/showFileInfo.js b/src/lib/showFileInfo.js index 1520f7c3cb..541227cabf 100644 --- a/src/lib/showFileInfo.js +++ b/src/lib/showFileInfo.js @@ -43,7 +43,7 @@ export default async function showFileInfo(url) { if (options.isEditor) { const value = await fs.readFile(settings.value.defaultFileEncoding); options.lineCount = value.split(/\n+/).length; - options.wordCount = value.split(/\s+|\n+/).length; + options.wordCount = value.split(/\S+/).length; if (/s?ftp:/.test(protocol)) { options.shareUri = Url.join(CACHE_STORAGE, name); From c063149458363fd7abfe50a216a697ee788aea21 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:27:55 +0100 Subject: [PATCH 02/36] Update immersive-fullscreen.js --- hooks/immersive-fullscreen.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hooks/immersive-fullscreen.js b/hooks/immersive-fullscreen.js index 0d776d7d83..068bb84e21 100644 --- a/hooks/immersive-fullscreen.js +++ b/hooks/immersive-fullscreen.js @@ -22,9 +22,9 @@ module.exports = function prepareImmersiveFullscreen(context) { // Markers delimit our generated blocks so each prepare can replace them safely, // including when only the controller changes. let source = original - .replace(/\r\n/g, "\n") + .replaceAll("\r\n", "\n") .replace( - /^[ \t]*\/\/ ACODE_FULLSCREEN_BEGIN ([a-z]+)\n[\s\S]*?^[ \t]*\/\/ ACODE_FULLSCREEN_END \1\n/gm, + /^[ \t]*\/\/ ACODE_FULLSCREEN_BEGIN ([a-z]+)\n[^]*?^[ \t]*\/\/ ACODE_FULLSCREEN_END \1\n/gm, "", ); if (/ACODE_FULLSCREEN_(BEGIN|END)/.test(source)) { From 68e993b47894490c9910d5643577141978d7de39 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:30:12 +0100 Subject: [PATCH 03/36] Update post-process.js --- hooks/post-process.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/hooks/post-process.js b/hooks/post-process.js index 449669cf4c..97a5d77af2 100644 --- a/hooks/post-process.js +++ b/hooks/post-process.js @@ -94,7 +94,7 @@ function stripLauncherFilterFromMainActivity() { let content = fs.readFileSync(manifestPath, 'utf-8'); const updated = content.replace( - /(]*\bname="MainActivity"[^>]*>)\s*]*>\s*]*\/>\s*]*\/>\s*<\/intent-filter>/, + /(]*?\bname="MainActivity"[^>]*>)\s*]*>\s*]*\/>\s*]*\/>\s*<\/intent-filter>/, '$1' ); @@ -200,7 +200,7 @@ function enableStaticContext() { const mainActivityPath = path.join( prefix, 'platforms/android/app/src/main/java', - packageName.replace(/\./g, '/'), + packageName.replaceAll(".", "/"), 'MainActivity.java' ); @@ -262,7 +262,7 @@ function disableSplashFadeOnRealmeAndroid13() { const mainActivityPath = path.join( prefix, 'platforms/android/app/src/main/java', - packageName.replace(/\./g, '/'), + packageName.replaceAll(".", "/"), 'MainActivity.java' ); @@ -335,7 +335,7 @@ function removeLegacyKeyboardWorkaround() { const mainActivityPath = path.join( prefix, 'platforms/android/app/src/main/java', - packageName.replace(/\./g, '/'), + packageName.replaceAll(".", "/"), 'MainActivity.java' ); From 8098e410b517de1653776af0b2d7aa283a0db556 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:35:20 +0100 Subject: [PATCH 04/36] Update clientManager.ts --- src/cm/lsp/clientManager.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cm/lsp/clientManager.ts b/src/cm/lsp/clientManager.ts index 6d08882604..135f70912f 100644 --- a/src/cm/lsp/clientManager.ts +++ b/src/cm/lsp/clientManager.ts @@ -1458,7 +1458,7 @@ function applyTextEdits( if (fromResult == null || toResult == null) continue; const insert = typeof edit.newText === "string" - ? edit.newText.replace(/\r\n/g, "\n") + ? edit.newText.replaceAll("\r\n", "\n") : ""; changes.push({ from: fromResult, to: toResult, insert }); } @@ -1639,6 +1639,6 @@ function contentUriToFileUri(uri: string): string | null { function buildFileUri(pathname: string): string | null { if (!pathname) return null; const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`; - const encoded = encodeURI(normalized).replace(/#/g, "%23"); + const encoded = encodeURI(normalized).replaceAll("#", "%23"); return `file://${encoded}`; } From 217655267f21e4295eccf91824df827cb078f73b Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:08:16 +0100 Subject: [PATCH 05/36] Update documentColors.ts --- src/cm/lsp/documentColors.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cm/lsp/documentColors.ts b/src/cm/lsp/documentColors.ts index efacbb851e..ce55175960 100644 --- a/src/cm/lsp/documentColors.ts +++ b/src/cm/lsp/documentColors.ts @@ -213,7 +213,7 @@ function applyTextEdits( if (!mapped) continue; const insert = typeof edit.newText === "string" - ? edit.newText.replace(/\r\n/g, "\n") + ? edit.newText.replaceAll("\r\n", "\n") : ""; changes.push({ from: mapped.from, to: mapped.to, insert }); } From 1491f8d288d2a01267cd8085167eb02651938b37 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:12:52 +0100 Subject: [PATCH 06/36] Update index.js --- src/cm/themes/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cm/themes/index.js b/src/cm/themes/index.js index 71c95dc1eb..739f35b6bf 100644 --- a/src/cm/themes/index.js +++ b/src/cm/themes/index.js @@ -180,7 +180,7 @@ export function getThemeConfig(id) { export function getThemeExtensions(id, fallback = [oneDark]) { const fallbackExtensions = normalizeExtensions(fallback); const theme = - getThemeById(id) || getThemeById(String(id || "").replace(/-/g, "_")); + getThemeById(id) || getThemeById(String(id || "").replaceAll("-", "_")); return resolveThemeEntryExtensions(theme, fallbackExtensions); } From d018640bd42db4a47f13738f9e183ff25cecc174 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:16:04 +0100 Subject: [PATCH 07/36] Update canvasOptions.ts --- src/cm/canvasOptions.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cm/canvasOptions.ts b/src/cm/canvasOptions.ts index 1f363ae4e4..e50403b7a4 100644 --- a/src/cm/canvasOptions.ts +++ b/src/cm/canvasOptions.ts @@ -302,7 +302,7 @@ export function getCanvasTheme( ): CanvasThemeSpec { // Resolve ids like getThemeExtensions does ("one-dark" -> "one_dark"). const theme = - getThemeById(themeId) || getThemeById(String(themeId).replace(/-/g, "_")); + getThemeById(themeId) || getThemeById(String(themeId).replaceAll('-', "_")); const config = (theme?.config || getThemeConfig(themeId) || {}) as ThemeConfig; @@ -541,7 +541,7 @@ let nextThemeEntryId = 1; */ function themeEntryKey(themeId: string): string { const entry = - getThemeById(themeId) || getThemeById(String(themeId).replace(/-/g, "_")); + getThemeById(themeId) || getThemeById(String(themeId).replaceAll('-', "_")); if (!entry) return "0"; let n = themeEntryIds.get(entry); if (!n) themeEntryIds.set(entry, (n = nextThemeEntryId++)); From e0e562fc2023c01eb8b66a3c9f700a5d5cf490b7 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:17:52 +0100 Subject: [PATCH 08/36] Update canvasOptions.ts --- src/cm/canvasOptions.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cm/canvasOptions.ts b/src/cm/canvasOptions.ts index e50403b7a4..d7a9c35574 100644 --- a/src/cm/canvasOptions.ts +++ b/src/cm/canvasOptions.ts @@ -302,7 +302,7 @@ export function getCanvasTheme( ): CanvasThemeSpec { // Resolve ids like getThemeExtensions does ("one-dark" -> "one_dark"). const theme = - getThemeById(themeId) || getThemeById(String(themeId).replaceAll('-', "_")); + getThemeById(themeId) || getThemeById(String(themeId).replaceAll("-", "_")); const config = (theme?.config || getThemeConfig(themeId) || {}) as ThemeConfig; @@ -541,7 +541,7 @@ let nextThemeEntryId = 1; */ function themeEntryKey(themeId: string): string { const entry = - getThemeById(themeId) || getThemeById(String(themeId).replaceAll('-', "_")); + getThemeById(themeId) || getThemeById(String(themeId).replaceAll("-", "_")); if (!entry) return "0"; let n = themeEntryIds.get(entry); if (!n) themeEntryIds.set(entry, (n = nextThemeEntryId++)); From 18c6d83338f8cae2963407bd1d7cbe2f58a30f2a Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:19:14 +0100 Subject: [PATCH 09/36] Update commandRegistry.js --- src/cm/commandRegistry.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cm/commandRegistry.js b/src/cm/commandRegistry.js index 16068769fe..bdf544e867 100644 --- a/src/cm/commandRegistry.js +++ b/src/cm/commandRegistry.js @@ -1343,8 +1343,8 @@ function runLspCommand(commandFn, options = {}) { function humanizeCommandName(name) { return name - .replace(/([a-z0-9])([A-Z])/g, "$1 $2") - .replace(/_/g, " ") + .replace(/[a-z0-9](?=[A-Z])/g, "$& ") + .replaceAll("_", " ") .replace(/^./, (char) => char.toUpperCase()); } From 9685bffe0ddbd137f428db370037220dbdb8eca6 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:20:01 +0100 Subject: [PATCH 10/36] Update commandRegistry.js --- src/cm/commandRegistry.js | 2106 +++++++------------------------------ 1 file changed, 366 insertions(+), 1740 deletions(-) diff --git a/src/cm/commandRegistry.js b/src/cm/commandRegistry.js index bdf544e867..44e9159372 100644 --- a/src/cm/commandRegistry.js +++ b/src/cm/commandRegistry.js @@ -1,1837 +1,463 @@ -import fsOperation from "fileSystem"; -import * as cmCommands from "@codemirror/commands"; -import { - cursorCharLeft, - cursorCharRight, - cursorDocEnd, - cursorDocStart, - cursorGroupLeft, - cursorGroupRight, - cursorLineDown, - cursorLineEnd, - cursorLineStart, - cursorLineUp, - cursorMatchingBracket, - cursorPageDown, - cursorPageUp, - deleteCharBackward, - deleteCharForward, - deleteGroupBackward, - deleteGroupForward, - deleteLineBoundaryForward, - deleteToLineEnd, - deleteToLineStart, - indentLess, - indentMore, - indentSelection, - insertBlankLine, - insertNewlineAndIndent, - lineComment, - lineUncomment, - redo, - selectAll, - selectCharLeft, - selectCharRight, - selectDocEnd, - selectDocStart, - selectGroupLeft, - selectGroupRight, - selectLine, - selectLineDown, - selectLineEnd, - selectLineStart, - selectLineUp, - selectMatchingBracket, - selectPageDown, - selectPageUp, - simplifySelection, - toggleBlockComment, - toggleLineComment, - undo, -} from "@codemirror/commands"; -import { - foldCode, - indentUnit as indentUnitFacet, - unfoldCode, -} from "@codemirror/language"; -import { - closeLintPanel, - forceLinting, - nextDiagnostic, - openLintPanel, - previousDiagnostic, -} from "@codemirror/lint"; -import { - LSPPlugin, - formatDocument as lspFormatDocument, -} from "@codemirror/lsp-client"; -import { Compartment, EditorSelection } from "@codemirror/state"; -import { keymap } from "@codemirror/view"; -import { focusEditorIfEditable } from "cm/editorReadOnly"; -import { - copyLineDownFoldAware, - copyLineUpFoldAware, - deleteLineFoldAware, - moveLineDownFoldAware, - moveLineUpFoldAware, -} from "cm/foldAwareLineCommands"; -import { foldAllCodeBlocks, unfoldAllCodeBlocks } from "cm/foldingCommands"; -import { - canonicalizeKeyBinding, - keyBindingsConflict, - toCodeMirrorKey, -} from "cm/keyBindingUtils"; -import { - renameSymbol as acodeRenameSymbol, - clearDiagnosticsEffect, - clientManager, - jumpToDeclaration as lspJumpToDeclaration, - jumpToDefinition as lspJumpToDefinition, - jumpToImplementation as lspJumpToImplementation, - jumpToTypeDefinition as lspJumpToTypeDefinition, - nextSignature as lspNextSignature, - prevSignature as lspPrevSignature, - showSignatureHelp as lspShowSignatureHelp, -} from "cm/lsp"; -import { - closeReferencesPanel as acodeCloseReferencesPanel, - findAllReferences as acodeFindAllReferences, - findAllReferencesInTab as acodeFindAllReferencesInTab, -} from "cm/lsp/references"; -import { showDocumentSymbols } from "components/symbolsPanel"; -import toast from "components/toast"; -import prompt from "dialogs/prompt"; -import actions from "handlers/quickTools"; -import keyBindings, { - APP_KEY_BINDING_NAMES, - CODEMIRROR_COMMAND_NAMES, -} from "lib/keyBindings"; -import settings from "lib/settings"; -import Url from "utils/Url"; +import type { Extension } from "@codemirror/state"; -const commandKeymapCompartment = new Compartment(); +export type LanguageExtensionProvider = () => Extension | Promise; -/** - * @typedef {import("@codemirror/view").EditorView} EditorView - */ - -/** - * @typedef {{ - * name: string; - * description?: string; - * readOnly?: boolean; - * run: (view?: EditorView | null) => boolean | void; - * requiresView?: boolean; - * defaultDescription?: string; - * defaultKey?: string | null; - * key?: string | null; - * }} CommandEntry - */ - -/** @type {Map} */ -const commandMap = new Map(); - -/** @type {Record} */ -let resolvedKeyBindings = keyBindings; - -/** @type {Record} */ -let cachedResolvedKeyBindings = {}; - -/** @type {Record} */ -let cachedEffectiveKeyBindings = {}; - -/** @type {{key: string, command: string, shadowedBy: string}[]} */ -let cachedKeyBindingConflicts = []; - -let resolvedKeyBindingsVersion = 0; - -/** @type {import("@codemirror/view").KeyBinding[]} */ -let cachedKeymap = []; - -/** @type {Set} */ -const commandViews = new Set(); - -const CODEMIRROR_COMMAND_ENTRIES = Object.entries(cmCommands).filter( - ([name, value]) => - typeof value === "function" && CODEMIRROR_COMMAND_NAMES.has(name), -); - -const CODEMIRROR_COMMAND_MAP = new Map( - CODEMIRROR_COMMAND_ENTRIES.map(([name, fn]) => [name, fn]), -); - -registerCoreCommands(); -registerLspCommands(); -registerLintCommands(); -registerCommandsFromKeyBindings(); -rebuildKeymap(); - -function registerCoreCommands() { - addCommand({ - name: "focusEditor", - description: "Focus editor", - readOnly: true, - requiresView: false, - run(view) { - const resolvedView = resolveView(view); - if (resolvedView) focusEditorIfEditable(resolvedView); - return true; - }, - }); - addCommand({ - name: "findFile", - description: "Find file in workspace", - readOnly: true, - requiresView: false, - run() { - acode.exec("find-file"); - return true; - }, - }); - addCommand({ - name: "closeCurrentTab", - description: "Close current tab", - readOnly: false, - requiresView: false, - run() { - acode.exec("close-current-tab"); - return true; - }, - }); - addCommand({ - name: "newPane", - description: "Create new editor pane", - readOnly: true, - requiresView: false, - run() { - acode.exec("new-pane"); - return true; - }, - }); - addCommand({ - name: "moveTabToNewPane", - description: "Move current tab to new pane", - readOnly: true, - requiresView: false, - run() { - acode.exec("move-tab-to-new-pane"); - return true; - }, - }); - addCommand({ - name: "closePane", - description: "Close active editor pane", - readOnly: true, - requiresView: false, - run() { - acode.exec("close-pane"); - return true; - }, - }); - addCommand({ - name: "focusNextPane", - description: "Focus next editor pane", - readOnly: true, - requiresView: false, - run() { - acode.exec("focus-next-pane"); - return true; - }, - }); - addCommand({ - name: "focusPreviousPane", - description: "Focus previous editor pane", - readOnly: true, - requiresView: false, - run() { - acode.exec("focus-previous-pane"); - return true; - }, - }); - addCommand({ - name: "closeAllTabs", - description: "Close all tabs", - readOnly: false, - requiresView: false, - run() { - acode.exec("close-all-tabs"); - return true; - }, - }); - addCommand({ - name: "togglePinnedTab", - description: "Pin or unpin current tab", - readOnly: true, - requiresView: false, - run() { - acode.exec("toggle-pin-tab"); - return true; - }, - }); - addCommand({ - name: "newFile", - description: "Create new file", - readOnly: true, - requiresView: false, - run() { - acode.exec("new-file"); - return true; - }, - }); - addCommand({ - name: "openFile", - description: "Open a file", - readOnly: true, - requiresView: false, - run() { - acode.exec("open-file"); - return true; - }, - }); - addCommand({ - name: "openFolder", - description: "Open a folder", - readOnly: true, - requiresView: false, - run() { - acode.exec("open-folder"); - return true; - }, - }); - addCommand({ - name: "saveFile", - description: "Save current file", - readOnly: true, - requiresView: false, - run() { - acode.exec("save"); - return true; - }, - }); - addCommand({ - name: "saveFileAs", - description: "Save as current file", - readOnly: true, - requiresView: false, - run() { - acode.exec("save-as"); - return true; - }, - }); - addCommand({ - name: "saveAllChanges", - description: "Save all changes", - readOnly: true, - requiresView: false, - run() { - acode.exec("save-all-changes"); - return true; - }, - }); - addCommand({ - name: "nextFile", - description: "Open next file tab", - readOnly: true, - requiresView: false, - run() { - acode.exec("next-file"); - return true; - }, - }); - addCommand({ - name: "prevFile", - description: "Open previous file tab", - readOnly: true, - requiresView: false, - run() { - acode.exec("prev-file"); - return true; - }, - }); - addCommand({ - name: "nextFileHistory", - description: "Open next file tab from history", - readOnly: true, - requiresView: false, - run() { - acode.exec("next-file-history"); - return true; - }, - }); - addCommand({ - name: "prevFileHistory", - description: "Open previous file tab from history", - readOnly: true, - requiresView: false, - run() { - acode.exec("prev-file-history"); - return true; - }, - }); - addCommand({ - name: "showSettingsMenu", - description: "Show settings menu", - readOnly: true, - requiresView: false, - run() { - acode.exec("open", "settings"); - return true; - }, - }); - addCommand({ - name: "renameFile", - description: "Rename active file", - readOnly: true, - requiresView: false, - run() { - acode.exec("rename"); - return true; - }, - }); - addCommand({ - name: "run", - description: "Preview HTML and MarkDown", - readOnly: true, - requiresView: false, - run() { - acode.exec("run"); - return true; - }, - }); - addCommand({ - name: "openInAppBrowser", - description: "Open In-App Browser", - readOnly: true, - requiresView: false, - run: openInAppBrowserCommand, - }); - addCommand({ - name: "toggleFullscreen", - description: "Toggle full screen mode", - readOnly: true, - requiresView: false, - run() { - acode.exec("toggle-fullscreen"); - return true; - }, - }); - addCommand({ - name: "toggleSidebar", - description: "Toggle sidebar", - readOnly: true, - requiresView: false, - run() { - acode.exec("toggle-sidebar"); - return true; - }, - }); - addCommand({ - name: "toggleMenu", - description: "Toggle main menu", - readOnly: true, - requiresView: false, - run() { - acode.exec("toggle-menu"); - return true; - }, - }); - addCommand({ - name: "toggleEditMenu", - description: "Toggle edit menu", - readOnly: true, - requiresView: false, - run() { - acode.exec("toggle-editmenu"); - return true; - }, - }); - addCommand({ - name: "selectall", - description: "Select all", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return selectAll(resolvedView); - }, - }); - addCommand({ - name: "gotoline", - description: "Go to line...", - readOnly: true, - requiresView: false, - run() { - acode.exec("goto"); - return true; - }, - }); - addCommand({ - name: "find", - description: "Find", - readOnly: true, - requiresView: false, - run() { - acode.exec("find"); - return true; - }, - }); - addCommand({ - name: "copy", - description: "Copy", - readOnly: true, - requiresView: true, - run: copyCommand, - }); - addCommand({ - name: "cut", - description: "Cut", - readOnly: false, - requiresView: true, - run: cutCommand, - }); - addCommand({ - name: "paste", - description: "Paste", - readOnly: false, - requiresView: true, - run: pasteCommand, - }); - - addCommand({ - name: "share", - description: "Share", - readOnly: true, - requiresView: true, - run: shareCommand, - }); - addCommand({ - name: "problems", - description: "Show errors and warnings", - readOnly: true, - requiresView: false, - run() { - acode.exec("open", "problems"); - return true; - }, - }); - addCommand({ - name: "replace", - description: "Replace", - readOnly: true, - requiresView: false, - run() { - acode.exec("replace"); - return true; - }, - }); - addCommand({ - name: "openCommandPalette", - description: "Open command palette", - readOnly: true, - requiresView: false, - run() { - acode.exec("command-palette"); - return true; - }, - }); - addCommand({ - name: "modeSelect", - description: "Change language mode...", - readOnly: true, - requiresView: false, - run() { - acode.exec("syntax"); - return true; - }, - }); - addCommand({ - name: "toggleQuickTools", - description: "Toggle quick tools", - readOnly: true, - requiresView: false, - run() { - actions("toggle"); - return true; - }, - }); - addCommand({ - name: "selectWord", - description: "Select current word", - readOnly: false, - requiresView: true, - run: selectWordCommand, - }); - addCommand({ - name: "openLogFile", - description: "Open Log File", - readOnly: true, - requiresView: false, - run() { - acode.exec("open-log-file"); - return true; - }, - }); - addCommand({ - name: "increaseUiZoom", - description: "Increase UI zoom", - readOnly: true, - requiresView: false, - run: () => adjustUiZoom(10), - }); - addCommand({ - name: "decreaseUiZoom", - description: "Decrease UI zoom", - readOnly: true, - requiresView: false, - run: () => adjustUiZoom(-10), - }); - addCommand({ - name: "increaseFontSize", - description: "Increase editor font size", - readOnly: true, - requiresView: false, - run: () => adjustFontSize(1), - }); - addCommand({ - name: "decreaseFontSize", - description: "Decrease editor font size", - readOnly: true, - requiresView: false, - run: () => adjustFontSize(-1), - }); - addCommand({ - name: "openPluginsPage", - description: "Open Plugins Page", - readOnly: true, - requiresView: false, - run() { - acode.exec("open", "plugins"); - return true; - }, - }); - addCommand({ - name: "openFileExplorer", - description: "File Explorer", - readOnly: true, - requiresView: false, - run() { - acode.exec("open", "file_browser"); - return true; - }, - }); - addCommand({ - name: "copyDeviceInfo", - description: "Copy Device info", - readOnly: true, - requiresView: false, - run() { - acode.exec("copy-device-info"); - return true; - }, - }); - addCommand({ - name: "changeAppTheme", - description: "Change App Theme", - readOnly: true, - requiresView: false, - run() { - acode.exec("change-app-theme"); - return true; - }, - }); - addCommand({ - name: "changeEditorTheme", - description: "Change Editor Theme", - readOnly: true, - requiresView: false, - run() { - acode.exec("change-editor-theme"); - return true; - }, - }); - addCommand({ - name: "openTerminal", - description: "Open Terminal", - readOnly: true, - requiresView: false, - run() { - acode.exec("new-terminal"); - return true; - }, - }); - addCommand({ - name: "acode:showWelcome", - description: "Show Welcome", - readOnly: true, - requiresView: false, - run() { - acode.exec("welcome"); - return true; - }, - }); - addCommand({ - name: "run-tests", - description: "Run Tests", - key: "Ctrl-Shift-T", - readOnly: true, - requiresView: false, - run() { - acode.exec("run-tests"); - return true; - }, - }); - addCommand({ - name: "dev:openInspector", - description: "Open Inspector", - run() { - acode.exec("open-inspector"); - return true; - }, - readOnly: true, - requiresView: false, - }); - addCommand({ - name: "dev:toggleDevTools", - description: "Toggle Developer Tools", - run() { - acode.exec("toggle-inspector"); - return true; - }, - readOnly: true, - requiresView: false, - key: "Ctrl-Shift-I", - }); - - // Additional editor-centric helpers mapped to CodeMirror primitives that have existing key bindings in defaults. - addCommand({ - name: "duplicateSelection", - description: "Duplicate selection", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return copyLineDownFoldAware(resolvedView); - }, - }); - addCommand({ - name: "copylinesdown", - description: "Copy lines down", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return copyLineDownFoldAware(resolvedView); - }, - }); - addCommand({ - name: "copylinesup", - description: "Copy lines up", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return copyLineUpFoldAware(resolvedView); - }, - }); - addCommand({ - name: "movelinesdown", - description: "Move lines down", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return moveLineDownFoldAware(resolvedView); - }, - }); - addCommand({ - name: "movelinesup", - description: "Move lines up", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return moveLineUpFoldAware(resolvedView); - }, - }); - addCommand({ - name: "removeline", - description: "Remove line", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return deleteLineFoldAware(resolvedView); - }, - }); - addCommand({ - name: "insertlineafter", - description: "Insert line after", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return insertBlankLine(resolvedView); - }, - }); - addCommand({ - name: "selectline", - description: "Select line", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return selectLine(resolvedView); - }, - }); - addCommand({ - name: "selectlinesdown", - description: "Select line down", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return selectLineDown(resolvedView); - }, - }); - addCommand({ - name: "selectlinesup", - description: "Select line up", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return selectLineUp(resolvedView); - }, - }); - addCommand({ - name: "selectlinestart", - description: "Select line start", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return selectLineStart(resolvedView); - }, - }); - addCommand({ - name: "selectlineend", - description: "Select line end", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return selectLineEnd(resolvedView); - }, - }); - addCommand({ - name: "indent", - description: "Indent", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - const { state } = resolvedView; - const hasSelection = state.selection.ranges.some((range) => !range.empty); - if (hasSelection) { - return indentMore(resolvedView); - } - const indentString = - state.facet(indentUnitFacet) || - (settings?.value?.softTab - ? " ".repeat(Math.max(1, Number(settings?.value?.tabSize) || 2)) - : "\t"); - const insert = indentString && indentString.length ? indentString : "\t"; - resolvedView.dispatch( - state.changeByRange((range) => ({ - changes: { from: range.from, to: range.to, insert }, - range: EditorSelection.cursor(range.from + insert.length), - })), - ); - return true; - }, - }); - addCommand({ - name: "outdent", - description: "Outdent", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return indentLess(resolvedView); - }, - }); - addCommand({ - name: "indentselection", - description: "Indent selection", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return indentSelection(resolvedView); - }, - }); - addCommand({ - name: "newline", - description: "Insert newline", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return insertNewlineAndIndent(resolvedView); - }, - }); - addCommand({ - name: "joinlines", - description: "Join lines", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return deleteLineBoundaryForward(resolvedView); - }, - }); - addCommand({ - name: "deletetolinestart", - description: "Delete to line start", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return deleteToLineStart(resolvedView); - }, - }); - addCommand({ - name: "deletetolineend", - description: "Delete to line end", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return deleteToLineEnd(resolvedView); - }, - }); - addCommand({ - name: "togglecomment", - description: "Toggle comment", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return toggleLineComment(resolvedView); - }, - }); - addCommand({ - name: "comment", - description: "Add line comment", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return lineComment(resolvedView); - }, - }); - addCommand({ - name: "uncomment", - description: "Remove line comment", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return lineUncomment(resolvedView); - }, - }); - addCommand({ - name: "toggleBlockComment", - description: "Toggle block comment", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return toggleBlockComment(resolvedView); - }, - }); - addCommand({ - name: "undo", - description: "Undo", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return undo(resolvedView); - }, - }); - addCommand({ - name: "redo", - description: "Redo", - readOnly: false, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return redo(resolvedView); - }, - }); - addCommand({ - name: "simplifySelection", - description: "Simplify selection", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return simplifySelection(resolvedView); - }, - }); - addCommand({ - name: "foldCode", - description: "Fold the Lines that are selected (if possible)", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return foldCode(resolvedView); - }, - }); - addCommand({ - name: "unfoldCode", - description: "Unfold folded ranges on selected lines.", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return unfoldCode(resolvedView); - }, - }); - addCommand({ - name: "foldAll", - description: - "Fold all - top-level ranges usually depends on the syntax tree. It may not work reliably if the document isn't fully parsed (e.g., just initialized or too large to parse completely)", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return foldAllCodeBlocks(resolvedView); - }, - }); - addCommand({ - name: "unfoldAll", - description: "Unfold all folded code.", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return unfoldAllCodeBlocks(resolvedView); - }, - }); +export interface AddModeOptions { + aliases?: string[]; + filenameMatchers?: RegExp[]; + /** Mode whose formatter (and Prettier parser) this mode reuses. */ + formatAs?: string; } -function registerLspCommands() { - addCommand({ - name: "formatDocument", - description: "Format document (Language Server)", - readOnly: false, - requiresView: true, - run: runLspCommand(lspFormatDocument), - }); - addCommand({ - name: "renameSymbol", - description: "Rename symbol (Language Server)", - readOnly: false, - requiresView: true, - run: runLspCommand(acodeRenameSymbol), - }); - addCommand({ - name: "showSignatureHelp", - description: "Show signature help", - readOnly: true, - requiresView: true, - run: runLspCommand(lspShowSignatureHelp), - }); - addCommand({ - name: "nextSignature", - description: "Next signature", - readOnly: true, - requiresView: true, - run: runLspCommand(lspNextSignature, { silentOnMissing: true }), - }); - addCommand({ - name: "prevSignature", - description: "Previous signature", - readOnly: true, - requiresView: true, - run: runLspCommand(lspPrevSignature, { silentOnMissing: true }), - }); - addCommand({ - name: "jumpToDefinition", - description: "Go to definition (Language Server)", - readOnly: true, - requiresView: true, - run: runLspCommand(lspJumpToDefinition), - }); - addCommand({ - name: "jumpToDeclaration", - description: "Go to declaration (Language Server)", - readOnly: true, - requiresView: true, - run: runLspCommand(lspJumpToDeclaration), - }); - addCommand({ - name: "jumpToTypeDefinition", - description: "Go to type definition (Language Server)", - readOnly: true, - requiresView: true, - run: runLspCommand(lspJumpToTypeDefinition), - }); - addCommand({ - name: "jumpToImplementation", - description: "Go to implementation (Language Server)", - readOnly: true, - requiresView: true, - run: runLspCommand(lspJumpToImplementation), - }); - addCommand({ - name: "findReferences", - description: "Find all references (Language Server)", - readOnly: true, - requiresView: true, - async run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - const plugin = LSPPlugin.get(resolvedView); - if (!plugin) { - notifyLspUnavailable(); - return false; - } - return acodeFindAllReferences(resolvedView); - }, - }); - addCommand({ - name: "closeReferencePanel", - description: "Close references panel", - readOnly: true, - requiresView: false, - run() { - return acodeCloseReferencesPanel(); - }, - }); - addCommand({ - name: "findReferencesInTab", - description: "Find all references in new tab (Language Server)", - readOnly: true, - requiresView: true, - async run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - const plugin = LSPPlugin.get(resolvedView); - if (!plugin) { - notifyLspUnavailable(); - return false; - } - return acodeFindAllReferencesInTab(resolvedView); - }, - }); - addCommand({ - name: "restartAllLspServers", - description: "Restart all running LSP servers", - readOnly: true, - requiresView: false, - async run() { - const activeClients = clientManager.getActiveClients(); - if (!activeClients.length) { - toast("No LSP servers are currently running"); - return true; - } - const count = activeClients.length; - toast(`Restarting ${count} LSP server${count > 1 ? "s" : ""}...`); +export interface ModesByName { + [name: string]: Mode; +} - // Dispose all clients (also clears diagnostics) - await clientManager.dispose(); +const modesByName: ModesByName = {}; +const modes: Mode[] = []; - // Trigger reconnect for active file - editorManager?.restartLsp?.(); - return true; - }, - }); - addCommand({ - name: "stopAllLspServers", - description: "Stop all running LSP servers", - readOnly: true, - requiresView: false, - async run() { - const activeClients = clientManager.getActiveClients(); - if (!activeClients.length) { - toast("No LSP servers are currently running"); - return true; - } - const count = activeClients.length; +const FILE_NAME_CACHE_LIMIT = 2000; - // Dispose all clients - await clientManager.dispose(); - toast(`Stopped ${count} LSP server${count > 1 ? "s" : ""}`); - return true; - }, - }); - addCommand({ - name: "documentSymbols", - description: "Go to Symbol in Document...", - readOnly: true, - requiresView: true, - async run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return showDocumentSymbols(resolvedView); - }, - }); +interface NamedCheck { + mode: Mode; + exactName?: string; + matcher?: RegExp; } -function registerLintCommands() { - addCommand({ - name: "openLintPanel", - description: "Open lint panel", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return openLintPanel(resolvedView); - }, - }); - addCommand({ - name: "closeLintPanel", - description: "Close lint panel", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return closeLintPanel(resolvedView); - }, - }); - addCommand({ - name: "nextDiagnostic", - description: "Go to next diagnostic", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return nextDiagnostic(resolvedView); - }, - }); - addCommand({ - name: "previousDiagnostic", - description: "Go to previous diagnostic", - readOnly: true, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return previousDiagnostic(resolvedView); - }, - }); +interface ModeIndex { + sorted: Mode[]; + namedChecks: NamedCheck[]; + extensions: Map; + rankByMode: Map; } -function registerCommandsFromKeyBindings() { - Object.entries(keyBindings).forEach(([name, binding]) => { - if (commandMap.has(name)) return; - const description = binding?.description || humanizeCommandName(name); - const readOnly = binding?.readOnly ?? false; - const requiresView = !!binding?.editorOnly; - const commandFn = CODEMIRROR_COMMAND_MAP.get(name); +let modeIndex: ModeIndex | null = null; +const resolvedByFileName = new Map(); - if (binding?.action) { - addCommand({ - name, - description, - readOnly, - requiresView, - run(view) { - try { - if (requiresView) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - } - acode.exec(binding.action); - return true; - } catch (error) { - console.error(`Failed to execute action ${binding.action}`, error); - return false; - } - }, - }); - return; - } - - if (commandFn) { - addCommand({ - name, - description, - readOnly, - requiresView: true, - run(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - return commandFn(resolvedView); - }, - }); - } - }); +function normalizeModeKey(value: string): string { + return String(value ?? "") + .trim() + .toLowerCase(); } -function addCommand(entry) { - const command = { - ...entry, - defaultDescription: entry.description || entry.name, - defaultKey: entry.key ?? null, - key: entry.key ?? null, - }; - commandMap.set(entry.name, command); +function normalizeAliases(aliases: string[] = [], name: string): string[] { + const normalized = new Set(); + for (const alias of aliases) { + const key = normalizeModeKey(alias); + if (!key || key === name) continue; + normalized.add(key); + } + return [...normalized]; } -function resolveView(view) { - return view || editorManager?.editor || null; +function escapeRegExp(value: string): string { + return String(value ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -function notifyLspUnavailable() { - toast?.("Language server not available"); +function fileNameFromPath(path: string): string { + const value = String(path ?? ""); + const slash = value.lastIndexOf("/"); + const backslash = value.lastIndexOf("\\"); + const sep = slash > backslash ? slash : backslash; + return sep === -1 ? value : value.slice(sep + 1); } -function runLspCommand(commandFn, options = {}) { - return (view) => { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - const plugin = LSPPlugin.get(resolvedView); - if (!plugin) { - if (!options?.silentOnMissing) { - notifyLspUnavailable(); - } - return false; - } - const result = commandFn(resolvedView); - return result !== false; - }; +function invalidateModeIndex(): void { + modeIndex = null; + resolvedByFileName.clear(); } -function humanizeCommandName(name) { - return name - .replace(/[a-z0-9](?=[A-Z])/g, "$& ") - .replaceAll("_", " ") - .replace(/^./, (char) => char.toUpperCase()); +/** + * Initialize CodeMirror mode list functionality + */ +export function initModes(): void { + // CodeMirror modes don't need the same ace.define wrapper + // but we maintain the same API structure for compatibility } -function copyCommand(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - const { state } = resolvedView; - const texts = state.selection.ranges.map((range) => { - if (range.empty) { - const line = state.doc.lineAt(range.head); - return state.doc.sliceString(line.from, line.to); +/** + * Add language mode to CodeMirror editor + */ +export function addMode( + name: string, + extensions: string | string[], + caption?: string, + languageExtension: LanguageExtensionProvider | null = null, + options: AddModeOptions = {}, +): void { + const filename = normalizeModeKey(name); + const mode = new Mode( + filename, + caption, + extensions, + languageExtension, + options, + ); + modesByName[filename] = mode; + mode.aliases.forEach((alias) => { + if (!modesByName[alias]) { + modesByName[alias] = mode; } - return state.doc.sliceString(range.from, range.to); }); - const textToCopy = texts.join("\n"); - cordova.plugins.clipboard.copy(textToCopy); - return true; + modes.push(mode); + invalidateModeIndex(); } -function cutCommand(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - const { state } = resolvedView; - const ranges = state.selection.ranges; - const segments = []; - let changes = []; - ranges.forEach((range) => { - if (range.empty) { - const line = state.doc.lineAt(range.head); - segments.push(state.doc.sliceString(line.from, line.to)); - changes.push({ from: line.from, to: line.to, insert: "" }); - return; +/** + * Remove language mode from CodeMirror editor + */ +export function removeMode(name: string): void { + const filename = normalizeModeKey(name); + const mode = modesByName[filename]; + if (!mode) return; + + delete modesByName[mode.name]; + mode.aliases.forEach((alias) => { + if (modesByName[alias] === mode) { + delete modesByName[alias]; } - segments.push(state.doc.sliceString(range.from, range.to)); - changes.push({ from: range.from, to: range.to, insert: "" }); - }); - cordova.plugins.clipboard.copy(segments.join("\n")); - resolvedView.dispatch({ - changes, - selection: EditorSelection.single( - changes[0]?.from ?? state.selection.main.from, - ), }); - return true; -} -function pasteCommand(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - cordova.plugins.clipboard.paste((text = "") => { - // replaceSelection measures the inserted text after line-ending - // normalization, so CRLF clipboard text can't push the cursor past - // the end of the document. - resolvedView.dispatch(resolvedView.state.replaceSelection(String(text)), { - userEvent: "input.paste", - }); - }); - return true; + const modeIndexInList = modes.findIndex( + (registeredMode) => registeredMode === mode, + ); + if (modeIndexInList >= 0) { + modes.splice(modeIndexInList, 1); + } + invalidateModeIndex(); } -function shareCommand(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; +/** + * Calculates a specificity score for a mode. + * Higher score means more specific. + * - Anchored patterns (e.g., "^Dockerfile") get a base score of 1000. + * - Non-anchored patterns (extensions) are scored by length. + */ +function getModeSpecificityScore(modeInstance: Mode): number { + if (modeInstance.name.toLowerCase() === "text") { + return 0; + } - const { state } = resolvedView; - const ranges = state.selection.ranges; - const segments = []; + const extensionsStr = modeInstance.extensions; + let maxScore = 0; + + if (extensionsStr) { + const patterns = extensionsStr.split("|"); + for (const pattern of patterns) { + let currentScore = 0; + if (pattern.startsWith("^")) { + // Exact filename match or anchored pattern + currentScore = 1000 + (pattern.length - 1); // Subtract 1 for '^' + } else { + // Extension match + currentScore = pattern.length; + } + if (currentScore > maxScore) { + maxScore = currentScore; + } + } + } - ranges.forEach((range) => { - if (range.empty) { - const line = state.doc.lineAt(range.head); - segments.push(state.doc.sliceString(line.from, line.to)); - return; + for (const matcher of modeInstance.filenameMatchers) { + const score = 1000 + matcher.source.length; + if (score > maxScore) { + maxScore = score; } + } - segments.push(state.doc.sliceString(range.from, range.to)); - }); + return maxScore; +} - const textToShare = segments.join("\n"); +function exactNameFromRegex(matcher: RegExp): string | null { + const otherFlags = matcher.flags.replaceAll("i", ""); + if (otherFlags) return null; - system.shareText(textToShare, console.log, console.error); + const source = matcher.source; + if ( + source.length < 2 || + source[0] !== "^" || + source[source.length - 1] !== "$" + ) { + return null; + } - return true; -} + const inner = source.slice(1, -1); + let name = ""; + for (let i = 0; i < inner.length; i++) { + const ch = inner[i]; + if (ch === "\\") { + const next = inner[i + 1]; + if (!next) return null; + name += next; + i++; + continue; + } + if ("^$|.*+?()[]{}".includes(ch)) return null; + name += ch; + } -function selectWordCommand(view) { - const resolvedView = resolveView(view); - if (!resolvedView) return false; - const { state } = resolvedView; - const ranges = state.selection.ranges.map((range) => { - const word = state.wordAt(range.head); - if (word) return EditorSelection.range(word.from, word.to); - const line = state.doc.lineAt(range.head); - return EditorSelection.range(line.from, line.to); - }); - resolvedView.dispatch({ - selection: EditorSelection.create(ranges, state.selection.mainIndex), - }); - return true; + return name ? name.toLowerCase() : null; } -async function openInAppBrowserCommand() { - const url = await prompt("Enter url", "", "url", { - placeholder: "http://", - match: /^https?:\/\/.+/, - }); - if (url) acode.exec("open-inapp-browser", url); - return true; +function rememberFirst(map: Map, key: string, mode: Mode): void { + if (key && !map.has(key)) { + map.set(key, mode); + } } -function adjustFontSize(delta) { - const current = settings?.value?.fontSize || "12px"; - const numeric = Number.parseInt(current, 10) || 12; - const next = Math.min(72, Math.max(6, numeric + delta)); - settings.value.fontSize = `${next}px`; - settings.update(false); - return true; -} +function getModeIndex(): ModeIndex { + if (modeIndex) return modeIndex; -function adjustUiZoom(delta) { - const current = Number(settings?.value?.uiZoom) || 100; - const next = Math.min(160, Math.max(70, current + delta)); - settings.value.uiZoom = next; - settings.update(false); - return true; -} + const ranked = modes.map((mode, index) => ({ + mode, + score: getModeSpecificityScore(mode), + index, + })); + ranked.sort((a, b) => { + const scoreDiff = b.score - a.score; + return scoreDiff !== 0 ? scoreDiff : b.index - a.index; + }); -function parseKeyString(keyString) { - if (!keyString) return []; - return String(keyString) - .split("|") - .map((combo) => combo.trim()) - .filter(Boolean); -} + const sorted = ranked.map((entry) => entry.mode); + const rankByMode = new Map(); + const namedChecks: NamedCheck[] = []; + const extensions = new Map(); -function hasOwnBindingOverride(name) { - return Object.prototype.hasOwnProperty.call(resolvedKeyBindings ?? {}, name); -} + for (let rank = 0; rank < sorted.length; rank++) { + rankByMode.set(sorted[rank], rank); + } -function resolveBindingInfo(name) { - const baseBinding = keyBindings[name] ?? null; - if (!hasOwnBindingOverride(name)) return baseBinding; + for (const { mode } of ranked) { + if (mode.extensions) { + for (const raw of mode.extensions.split("|")) { + const pattern = raw.trim(); + if (!pattern) continue; + if (pattern.startsWith("^")) { + namedChecks.push({ + mode, + exactName: pattern.slice(1).toLowerCase(), + }); + } else { + rememberFirst(extensions, pattern.toLowerCase(), mode); + } + } + } - const override = resolvedKeyBindings?.[name]; - if (override === null) { - return baseBinding ? { ...baseBinding, key: null } : { key: null }; + for (const matcher of mode.filenameMatchers) { + const exactName = exactNameFromRegex(matcher); + if (exactName) { + namedChecks.push({ mode, exactName }); + continue; + } + namedChecks.push({ mode, matcher }); + } } - if (!override || typeof override !== "object") { - return baseBinding; + modeIndex = { sorted, namedChecks, extensions, rankByMode }; + return modeIndex; +} + +function findModeByExtension( + fileNameLower: string, + extensions: Map, + rankByMode: Map, +): Mode | undefined { + let best: Mode | undefined; + let bestRank = Number.POSITIVE_INFINITY; + let dot = fileNameLower.indexOf("."); + while (dot >= 0 && dot < fileNameLower.length - 1) { + const mode = extensions.get(fileNameLower.slice(dot + 1)); + if (mode) { + const rank = rankByMode.get(mode) ?? Number.POSITIVE_INFINITY; + if (rank < bestRank) { + best = mode; + bestRank = rank; + } + } + dot = fileNameLower.indexOf(".", dot + 1); } - - return baseBinding ? { ...baseBinding, ...override } : override; + return best; } -function buildResolvedKeyBindingsSnapshot() { - const bindingNames = new Set([ - ...Object.keys(keyBindings), - ...Object.keys(resolvedKeyBindings ?? {}), - ]); +function resolveModeForPath(fileName: string): Mode { + const fallback = modesByName.text; + const index = getModeIndex(); + const fileNameLower = fileName.toLowerCase(); - return Object.fromEntries( - Array.from(bindingNames, (name) => [name, resolveBindingInfo(name)]).filter( - ([, binding]) => binding, - ), - ); -} - -function rebuildKeymap() { - cachedResolvedKeyBindings = buildResolvedKeyBindingsSnapshot(); - const candidates = []; - let order = 0; - commandMap.forEach((command, name) => { - const bindingInfo = resolveBindingInfo(name); - command.description = - bindingInfo?.description || command.defaultDescription; - const keySource = - bindingInfo && Object.prototype.hasOwnProperty.call(bindingInfo, "key") - ? bindingInfo.key - : (command.defaultKey ?? null); - command.key = keySource; - const combos = parseKeyString(keySource); - combos.forEach((combo) => { - const cmKey = toCodeMirrorKey(combo); - if (!cmKey) return; - candidates.push({ - name, - key: cmKey, - rawKey: combo, - order: order++, - priority: getBindingPriority(name), - }); - }); - }); - - candidates.sort( - (left, right) => right.priority - left.priority || left.order - right.order, - ); - - const bindings = []; - const claimedKeys = new Map(); - const effectiveKeys = new Map(); - const conflicts = []; - for (const candidate of candidates) { - const canonicalKey = canonicalizeKeyBinding(candidate.key); - const claimed = Array.from(claimedKeys.entries()).find(([key]) => - keyBindingsConflict(key, canonicalKey), - ); - if (claimed) { - const [claimedKey, owner] = claimed; - const appCommandShadowsCodeMirrorDefault = - APP_KEY_BINDING_NAMES.has(owner) && - CODEMIRROR_COMMAND_NAMES.has(candidate.name) && - candidate.priority === 10; - const repeatedKeyForSameCommand = - owner === candidate.name && claimedKey === canonicalKey; - if (!repeatedKeyForSameCommand && !appCommandShadowsCodeMirrorDefault) { - conflicts.push({ - key: candidate.key, - command: candidate.name, - shadowedBy: owner, - }); + for (const check of index.namedChecks) { + if (check.exactName) { + if ( + check.exactName === fileNameLower && + check.mode.supportsFile?.(fileName) + ) { + return check.mode; } continue; } - claimedKeys.set(canonicalKey, candidate.name); - if (!effectiveKeys.has(candidate.name)) { - effectiveKeys.set(candidate.name, []); + const matcher = check.matcher; + if (!matcher) continue; + matcher.lastIndex = 0; + if (matcher.test(fileName) && check.mode.supportsFile?.(fileName)) { + return check.mode; } - effectiveKeys.get(candidate.name).push(candidate.rawKey); - bindings.push({ - key: candidate.key, - run: (view) => executeCommand(candidate.name, view), - preventDefault: true, - }); } - cachedEffectiveKeyBindings = Object.fromEntries( - Object.entries(cachedResolvedKeyBindings).map(([name, binding]) => [ - name, - { - ...binding, - key: effectiveKeys.get(name)?.join("|") || null, - }, - ]), + const byExtension = findModeByExtension( + fileNameLower, + index.extensions, + index.rankByMode, ); - cachedKeyBindingConflicts = conflicts; - cachedKeymap = bindings; - resolvedKeyBindingsVersion += 1; - return bindings; -} + if (byExtension?.supportsFile?.(fileName)) return byExtension; -function getBindingPriority(name) { - if (APP_KEY_BINDING_NAMES.has(name)) return 40; - if (!Object.prototype.hasOwnProperty.call(keyBindings, name)) return 30; - - const override = resolvedKeyBindings?.[name]; - if ( - override && - typeof override === "object" && - Object.prototype.hasOwnProperty.call(override, "key") && - override.key !== keyBindings[name]?.key - ) { - return 20; + for (const mode of index.sorted) { + if (mode.supportsFile?.(fileName)) return mode; } - return 10; -} - -function resolveCommand(name) { - return commandMap.get(name) || null; -} - -function commandRunsInReadOnly(command, view) { - if (!view) return command.readOnly; - return view.state?.readOnly ? !!command.readOnly : true; + return fallback; } -export function executeCommand(name, view, args) { - const command = resolveCommand(name); - if (!command) return false; - const targetView = command.requiresView - ? resolveView(view) - : resolveView(view) || null; - if (command.requiresView && !targetView) return false; - if (!commandRunsInReadOnly(command, targetView)) return false; - try { - const result = command.run(targetView, args); - return result !== false; - } catch (error) { - console.error(`Failed to execute command ${name}`, error); - return false; +function cacheResolvedMode(fileNameLower: string, mode: Mode): Mode { + if (resolvedByFileName.size >= FILE_NAME_CACHE_LIMIT) { + resolvedByFileName.clear(); } + resolvedByFileName.set(fileNameLower, mode); + return mode; } -export function getRegisteredCommands() { - return Array.from(commandMap.values()).map((command) => ({ - name: command.name, - description: command.description || command.defaultDescription, - key: command.key || null, - })); -} - -export function getResolvedKeyBindings() { - return cachedResolvedKeyBindings; -} - -export function getEffectiveKeyBindings() { - return cachedEffectiveKeyBindings; -} +/** + * Get mode for file path + */ +export function getModeForPath(path: string): Mode { + const fileName = fileNameFromPath(path); + const cached = resolvedByFileName.get(fileName); + if (cached) return cached; -export function getKeyBindingConflicts() { - return cachedKeyBindingConflicts.map((conflict) => ({ ...conflict })); + return cacheResolvedMode(fileName, resolveModeForPath(fileName)); } -export function getResolvedKeyBindingsVersion() { - return resolvedKeyBindingsVersion; +/** + * Get all modes by name + */ +export function getModesByName(): ModesByName { + return modesByName; } -export function getCommandKeymapExtension() { - return commandKeymapCompartment.of(keymap.of(cachedKeymap)); +/** + * Get all modes array + */ +export function getModes(): Mode[] { + return modes; } -export async function setKeyBindings(view) { - await loadCustomKeyBindings(); - const bindings = rebuildKeymap(); - const resolvedView = resolveView(view); - if (resolvedView) commandViews.add(resolvedView); - for (const knownView of commandViews) { - if (!knownView.dom?.isConnected) { - commandViews.delete(knownView); - continue; - } - applyCommandKeymap(knownView, bindings); - } - return getKeyBindingConflicts(); +export function getMode(name: string): Mode | null { + return modesByName[normalizeModeKey(name)] || null; } -async function loadCustomKeyBindings() { - try { - const bindingsFile = fsOperation(KEYBINDING_FILE); - if (await bindingsFile.exists()) { - const bindings = await bindingsFile.readFile("json"); - if ( - !bindings || - typeof bindings !== "object" || - Array.isArray(bindings) - ) { - throw new TypeError("Key bindings must be a JSON object"); - } - - let updated = false; - Object.keys(keyBindings).forEach((key) => { - if (!(key in bindings)) { - bindings[key] = keyBindings[key]; - updated = true; - } - }); - resolvedKeyBindings = bindings; - if (updated) { - bindingsFile - .writeFile(JSON.stringify(bindings, undefined, 2)) - .catch((error) => { - window.log?.("error", "Failed to back-fill new key bindings!"); - window.log?.("error", error); - }); - } - } else { - throw new Error("Key binding file not found"); +/** + * Name of the mode that `name` formats as, with aliases resolved, or `null`. + */ +export function getFormatAsMode(name: string): string | null { + const formatAs = getMode(name)?.formatAs; + if (!formatAs) return null; + return getMode(formatAs)?.name ?? formatAs; +} + +export class Mode { + extensions: string; + caption: string; + name: string; + mode: string; + aliases: string[]; + extRe: RegExp | null; + filenameMatchers: RegExp[]; + formatAs: string | null; + languageExtension: LanguageExtensionProvider | null; + + constructor( + name: string, + caption: string | undefined, + extensions: string | string[], + languageExtension: LanguageExtensionProvider | null = null, + options: AddModeOptions = {}, + ) { + if (Array.isArray(extensions)) { + extensions = extensions.join("|"); } - } catch (error) { - await resetKeyBindings(); - resolvedKeyBindings = keyBindings; - } -} -export async function resetKeyBindings() { - try { - const fs = fsOperation(KEYBINDING_FILE); - const fileName = Url.basename(KEYBINDING_FILE); - const content = JSON.stringify(keyBindings, undefined, 2); - if (!(await fs.exists())) { - await fsOperation(DATA_STORAGE).createFile(fileName, content); + this.name = name; + this.mode = name; // CodeMirror uses different mode naming + this.extensions = extensions; + this.caption = caption || this.name.replaceAll("_", " "); + // Plugins may pass anything here; ignore what isn't the expected shape + const { aliases, filenameMatchers, formatAs } = + options && typeof options === "object" ? options : {}; + this.aliases = Array.isArray(aliases) + ? normalizeAliases(aliases, this.name) + : []; + this.filenameMatchers = Array.isArray(filenameMatchers) + ? filenameMatchers.filter((matcher) => matcher instanceof RegExp) + : []; + this.formatAs = + typeof formatAs === "string" && normalizeModeKey(formatAs) + ? normalizeModeKey(formatAs) + : null; + this.languageExtension = languageExtension; + let re = ""; + + if (!extensions) { + this.extRe = null; return; } - await fs.writeFile(content); - } catch (error) { - window.log?.("error", "Reset Keybinding failed!"); - window.log?.("error", error); - } -} -export { commandKeymapCompartment }; + const patterns = extensions + .split("|") + .map((pattern) => pattern.trim()) + .filter(Boolean); + const filenamePatterns = patterns + .filter((pattern) => pattern.startsWith("^")) + .map((pattern) => `^${escapeRegExp(pattern.slice(1))}$`); + const extensionPatterns = patterns + .filter((pattern) => !pattern.startsWith("^")) + .map((pattern) => escapeRegExp(pattern)); + const regexParts: string[] = []; + + if (extensionPatterns.length) { + regexParts.push(`^.*?\\.(${extensionPatterns.join("|")})$`); + } -export function registerExternalCommand(descriptor = {}) { - const normalized = normalizeExternalCommand(descriptor); - if (!normalized) return null; + regexParts.push(...filenamePatterns); - const { name } = normalized; - if (commandMap.has(name)) { - commandMap.delete(name); - } + if (!regexParts.length) { + this.extRe = null; + return; + } - addCommand(normalized); - const stored = commandMap.get(name); - if (stored) { - stored.key = normalized.key ?? stored.key; + re = + regexParts.length === 1 ? regexParts[0] : `(?:${regexParts.join("|")})`; + this.extRe = new RegExp(re, "i"); } - rebuildKeymap(); - return stored; -} - -export function removeExternalCommand(name) { - if (!name) return false; - const exists = commandMap.has(name); - if (!exists) return false; - commandMap.delete(name); - rebuildKeymap(); - return true; -} - -export function refreshCommandKeymap(view) { - const resolvedView = resolveView(view); - applyCommandKeymap(resolvedView); -} + supportsFile(filename: string): boolean { + if (this.extRe?.test(filename)) return true; -function normalizeExternalCommand(descriptor) { - const name = - typeof descriptor?.name === "string" ? descriptor.name.trim() : ""; - if (!name) { - console.warn("Command registration skipped: missing name", descriptor); - return null; - } - const exec = typeof descriptor?.exec === "function" ? descriptor.exec : null; - if (!exec) { - console.warn( - `Command registration skipped for "${name}": exec must be a function.`, - ); - return null; + return this.filenameMatchers.some((matcher) => { + matcher.lastIndex = 0; + return matcher.test(filename); + }); } - const requiresView = descriptor?.requiresView ?? true; - const key = normalizeExternalKey(descriptor?.bindKey); - - return { - name, - description: descriptor?.description || humanizeCommandName(name), - readOnly: descriptor?.readOnly ?? true, - requiresView, - key, - run(view, args) { - try { - const resolvedView = resolveView(view); - if (requiresView && !resolvedView) return false; - const result = exec(resolvedView || null, args); - return result !== false; - } catch (error) { - console.error(`Command \"${name}\" failed`, error); - return false; - } - }, - }; -} - -function normalizeExternalKey(bindKey) { - if (!bindKey) return null; - if (typeof bindKey === "string") return bindKey; - const combos = []; - if (typeof bindKey === "object") { - const pushCombo = (combo) => { - if (typeof combo === "string" && combo.trim()) combos.push(combo.trim()); - }; - pushCombo(bindKey.win); - pushCombo(bindKey.linux); - pushCombo(bindKey.mac); + /** + * Get the CodeMirror language extension + */ + getExtension(): LanguageExtensionProvider | null { + return this.languageExtension; } - return combos.length ? combos.join("|") : null; -} -function applyCommandKeymap(view, bindings = cachedKeymap) { - if (!view) return; - commandViews.add(view); - view.dispatch({ - effects: commandKeymapCompartment.reconfigure( - keymap.of(bindings ?? cachedKeymap), - ), - }); + /** + * Check if the language extension is available (loaded) + */ + isAvailable(): boolean { + return this.languageExtension !== null; + } } From ed3cd56f8a84962d043f06b167e9e548309a960e Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:21:29 +0100 Subject: [PATCH 11/36] Update supportedModes.ts --- src/cm/supportedModes.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cm/supportedModes.ts b/src/cm/supportedModes.ts index f16746a746..432618f081 100644 --- a/src/cm/supportedModes.ts +++ b/src/cm/supportedModes.ts @@ -25,9 +25,9 @@ function isSafeModeId(value: string): boolean { function slugifyModeId(value: string): string { return normalizeModeKey(value) - .replace(/\+\+/g, "pp") - .replace(/#/g, "sharp") - .replace(/&/g, "and") + .replaceAll("++", "pp") + .replaceAll("#", "sharp") + .replaceAll("&", "and") .replace(/[^a-z0-9._-]+/g, "-") .replace(/^-+|-+$/g, ""); } From 6a1b2b2611a3b0f136f2fec6a4cb39706c3fd342 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:24:19 +0100 Subject: [PATCH 12/36] Update console.js --- src/lib/console.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/console.js b/src/lib/console.js index 35a32cb2b9..402d61b529 100644 --- a/src/lib/console.js +++ b/src/lib/console.js @@ -625,9 +625,9 @@ import ConsoleExecutor, { } catch (error) { return data .toString() - .replace(/({).*(})/, "$1...$2") + .replace(/{.*}/, "{...}") .replace(/^function\s+[\w_$\d]+\s*/, "") - .replace(/\s*/g, ""); + .replace(/\s+/g, ""); } } From 33b8bc11527ea8ab4bd35ec1847b22410c933a53 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:26:02 +0100 Subject: [PATCH 13/36] Update editorFile.js --- src/lib/editorFile.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/editorFile.js b/src/lib/editorFile.js index 78fcb06881..22486097b9 100644 --- a/src/lib/editorFile.js +++ b/src/lib/editorFile.js @@ -967,7 +967,7 @@ export default class EditorFile { if (value === "windows") { text = text.replace(/\n(? Date: Mon, 16 Nov 2026 16:27:21 +0100 Subject: [PATCH 14/36] Update fonts.js --- src/lib/fonts.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/fonts.js b/src/lib/fonts.js index af2aec1ad1..82fe22fed9 100644 --- a/src/lib/fonts.js +++ b/src/lib/fonts.js @@ -280,7 +280,7 @@ async function loadFont(name) { } // Get all URL font references - const urls = [...css.matchAll(/url\((.*?)\)/g)].map((match) => match[1]); + const urls = [...css.matchAll(/\burl\(([^)]*)\)/g)].map((match) => match[1]); // Download and replace URLs for (const url of urls) { From dd329b3c6465c5169e21641e738d6982881cca0e Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:28:44 +0100 Subject: [PATCH 15/36] Update keyBindings.js --- src/lib/keyBindings.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/keyBindings.js b/src/lib/keyBindings.js index db48a80185..77c41f65a2 100644 --- a/src/lib/keyBindings.js +++ b/src/lib/keyBindings.js @@ -928,8 +928,8 @@ function parseKeyParts(combo) { function humanizeCommandName(name) { return name - .replace(/([a-z0-9])([A-Z])/g, "$1 $2") - .replace(/_/g, " ") + .replace(/[a-z0-9](?=[A-Z])/g, "$& ") + .replaceAll("_", " ") .replace(/^./, (char) => char.toUpperCase()); } From ed6f7dd66c24ceae86f99edac948d9a0d5d21137 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:29:36 +0100 Subject: [PATCH 16/36] Update prettierFormatter.js --- src/lib/prettierFormatter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/prettierFormatter.js b/src/lib/prettierFormatter.js index e95014c0cf..31dcaf3d8e 100644 --- a/src/lib/prettierFormatter.js +++ b/src/lib/prettierFormatter.js @@ -466,7 +466,7 @@ function evaluateUnaryExpression(node, scope) { } function normalizePath(path) { - let result = String(path || "").replace(/\\/g, "/"); + let result = String(path || "").replaceAll("\\", "/"); while (result.length > 1 && result.endsWith("/")) { const prefix = result.slice(0, -1); if (/^[a-z]+:\/{0,2}$/i.test(prefix)) break; From 7574af2c48834519080e7faadb3e533139d5bbc4 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:34:00 +0100 Subject: [PATCH 17/36] Update showFileInfo.js --- src/lib/showFileInfo.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/showFileInfo.js b/src/lib/showFileInfo.js index 541227cabf..842e7ea9a5 100644 --- a/src/lib/showFileInfo.js +++ b/src/lib/showFileInfo.js @@ -42,7 +42,7 @@ export default async function showFileInfo(url) { if (options.isEditor) { const value = await fs.readFile(settings.value.defaultFileEncoding); - options.lineCount = value.split(/\n+/).length; + options.lineCount = value.split("\n").length; options.wordCount = value.split(/\S+/).length; if (/s?ftp:/.test(protocol)) { From 0d8b97a2565a534d33ec8712ae5b20130fcf8dff Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:35:20 +0100 Subject: [PATCH 18/36] Update customTheme.js --- src/pages/customTheme/customTheme.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/customTheme/customTheme.js b/src/pages/customTheme/customTheme.js index 8131a7c329..c0f2440b18 100644 --- a/src/pages/customTheme/customTheme.js +++ b/src/pages/customTheme/customTheme.js @@ -82,7 +82,7 @@ export default function CustomThemeInclude() { function render() { const pascalToNormal = (str) => - str.replace(/([A-Z])/g, " $1").toLowerCase(); + str.replace(/[A-Z]/g, " $&").toLowerCase(); const customTheme = themes.get("custom"); $page.body = ( From 915a824abedaecc71ecac53d1be57a4b442d4d9d Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:37:25 +0100 Subject: [PATCH 19/36] Update fileBrowser.js --- src/pages/fileBrowser/fileBrowser.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/pages/fileBrowser/fileBrowser.js b/src/pages/fileBrowser/fileBrowser.js index 6ca4591abd..88b077a672 100644 --- a/src/pages/fileBrowser/fileBrowser.js +++ b/src/pages/fileBrowser/fileBrowser.js @@ -355,7 +355,7 @@ function FileBrowserInclude(mode, info, doesOpenLast = true) { let parts; if (typeof dir === "string") { if (dir.endsWith("/")) wantDirEnd = true; - dir = dir.replace(/\\/g, "/"); + dir = dir.replaceAll("\\", "/"); parts = dir.split("/"); } else { parts = dir; @@ -390,7 +390,7 @@ function FileBrowserInclude(mode, info, doesOpenLast = true) { const sanitizeZipPath = (p, isDir) => { if (!p) return ""; let path = String(p); - path = path.replace(/\\/g, "/"); + path = path.replaceAll("\\", "/"); path = path.replace(/^[a-zA-Z]+:\/\//, ""); path = path.replace(/^\/+/, ""); path = path.replace(/^[A-Za-z]:\//, ""); @@ -431,7 +431,7 @@ function FileBrowserInclude(mode, info, doesOpenLast = true) { `Extracting ${filePath} (${Math.round((current / total) * 100)}%)`, ); - let correctFile = filePath.replace(/\\/g, "/"); + let correctFile = filePath.replaceAll("\\", "/"); const isDirEntry = entry.dir || correctFile.endsWith("/"); if (isUnsafeAbsolutePath(filePath)) { @@ -1661,7 +1661,7 @@ function FileBrowserInclude(mode, info, doesOpenLast = true) { const fs = fsOperation(lclUrl); if (paths.length === 0) { - const data = project[fileUrl].replace(/<%name%>/g, projectName); + const data = project[fileUrl].replaceAll("<%name%>", projectName); await fs.createFile(filename, data); return; } From 0e83771e0b2e6eb065c1e6402239db9bea96e1a5 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:38:28 +0100 Subject: [PATCH 20/36] Update fontManager.js --- src/pages/fontManager/fontManager.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/fontManager/fontManager.js b/src/pages/fontManager/fontManager.js index d615aa1217..7a80f39b04 100644 --- a/src/pages/fontManager/fontManager.js +++ b/src/pages/fontManager/fontManager.js @@ -126,7 +126,7 @@ export default function fontManager() { const fontName = await prompt( "Font Name", - name.replace(/\.(ttf|otf|woff|woff2)$/i, ""), + name.replace(/\.(?:ttf|otf|woff|woff2)$/i, ""), ); if (!fontName) return; From 90d8f630b442402e0500180ef33f405607faf0c2 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:40:54 +0100 Subject: [PATCH 21/36] Update renderer.js --- src/pages/markdownPreview/renderer.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/markdownPreview/renderer.js b/src/pages/markdownPreview/renderer.js index 1de6a1caaf..6ab36196ee 100644 --- a/src/pages/markdownPreview/renderer.js +++ b/src/pages/markdownPreview/renderer.js @@ -23,7 +23,7 @@ function slugify(text) { .trim() .toLowerCase() .normalize("NFD") - .replace(/[\u0300-\u036f]/g, "") + .replace(/[\u0300-\u036f]+/g, "") .replace(/[^\p{L}\p{N}]+/gu, "-") .replace(/^-+|-+$/g, ""); } From 804a4c34ceae094c086c24932c60a37c588dbb68 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:44:40 +0100 Subject: [PATCH 22/36] Update welcome.js --- src/pages/welcome/welcome.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/welcome/welcome.js b/src/pages/welcome/welcome.js index 9822da8f99..db7e8413af 100644 --- a/src/pages/welcome/welcome.js +++ b/src/pages/welcome/welcome.js @@ -37,7 +37,7 @@ function createWelcomeContent() { const bindings = getResolvedKeyBindings(); const kb = (name) => { const binding = bindings[name]; - return binding?.key ? binding.key.split("|")[0].replace(/-/g, "+") : ""; + return binding?.key ? binding.key.split("|")[0].replaceAll("-", "+") : ""; }; return ( From 91459af5cc4888b139e96404c7cba9e01f4cdba2 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:46:34 +0100 Subject: [PATCH 23/36] Update worker.js --- src/sidebarApps/searchInFiles/worker.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sidebarApps/searchInFiles/worker.js b/src/sidebarApps/searchInFiles/worker.js index e4c3931403..0e2740cd56 100644 --- a/src/sidebarApps/searchInFiles/worker.js +++ b/src/sidebarApps/searchInFiles/worker.js @@ -203,7 +203,7 @@ function getSurrounding(content, word, start, end) { if (left > 0 && !/[\r\n]/.test(content[left - 1])) line = `...${line}`; if (right < content.length && !/[\r\n]/.test(content[right])) line += "..."; return [line, word.slice(0, max)].map((text) => - text.replace(/[\r\n]+/g, " ⏎ "), + text.replaceAll("\r\n", " ⏎ ").replaceAll("\n", " ⏎ ").replaceAll("\r", " ⏎ "), ); } From 2398282cac0e8836d0a60e9d15726b8dd07ea7f9 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:48:05 +0100 Subject: [PATCH 24/36] Update fileOperationExclusions.js --- src/utils/fileOperationExclusions.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/fileOperationExclusions.js b/src/utils/fileOperationExclusions.js index d59eed13ff..81e240082f 100644 --- a/src/utils/fileOperationExclusions.js +++ b/src/utils/fileOperationExclusions.js @@ -15,7 +15,7 @@ export function isExcludedFileOperationPath(url, patterns = []) { const parsedUrl = Url.parse(url).url; const pathname = Url.pathname(parsedUrl) || parsedUrl; - const normalizedPath = pathname.replace(/\\/g, "/").replace(/\/+$/, ""); + const normalizedPath = pathname.replaceAll("\\", "/").replace(/\/+$/, ""); const relativePath = normalizedPath.replace(/^\/+/, ""); const candidates = [ normalizedPath, From 76dc32ad475561350d2717148a85cc9f67f6bc55 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:50:56 +0100 Subject: [PATCH 25/36] Update Path.js --- src/utils/Path.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/utils/Path.js b/src/utils/Path.js index dd5d9f1264..dd6b2cd373 100644 --- a/src/utils/Path.js +++ b/src/utils/Path.js @@ -92,8 +92,7 @@ export default { * @param {string} path */ normalize(path) { - path = path.replace(/\.\/+/g, "./"); - path = path.replace(/\/+/g, "/"); + path = path.replace(/\/\/+/g, "/"); const resolved = []; const pathAr = path.split("/"); From 2e06c7ce52a53e5723c5d74f7f48780fffa25fed Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:52:00 +0100 Subject: [PATCH 26/36] Update Uri.js --- src/utils/Uri.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/Uri.js b/src/utils/Uri.js index 36a9a124e3..9d6807b254 100644 --- a/src/utils/Uri.js +++ b/src/utils/Uri.js @@ -194,7 +194,7 @@ export default { const { name } = storage; const [base, paths] = url.split("::"); url = base + "/" + paths.split("/").slice(1).join("/"); - return url.replace(regex, name).replace(/\/+/g, "/"); + return url.replace(regex, name).replace(/\/\/+/g, "/"); } return url; From e2f540a9dabd0cde8b431484100a37acfc29bc53 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:53:25 +0100 Subject: [PATCH 27/36] Update Url.js --- src/utils/Url.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/Url.js b/src/utils/Url.js index f79e69be00..2f27d041fb 100644 --- a/src/utils/Url.js +++ b/src/utils/Url.js @@ -302,7 +302,7 @@ export default { const uuid = "uuid" + Math.floor(Math.random() + Date.now() * 1000000); if (/#/.test(url)) { - url = url.replace(/#/g, uuid); + url = url.replaceAll("#", uuid); } let { username, password, hostname, pathname, port, query } = URLParse( From 500b2e829f1f142ea1c88fa84c8f55f1224c6347 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:58:16 +0100 Subject: [PATCH 28/36] fix lint --- hooks/post-process.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/hooks/post-process.js b/hooks/post-process.js index 97a5d77af2..582408c011 100644 --- a/hooks/post-process.js +++ b/hooks/post-process.js @@ -200,7 +200,7 @@ function enableStaticContext() { const mainActivityPath = path.join( prefix, 'platforms/android/app/src/main/java', - packageName.replaceAll(".", "/"), + packageName.replaceAll('.', '/'), 'MainActivity.java' ); @@ -262,7 +262,7 @@ function disableSplashFadeOnRealmeAndroid13() { const mainActivityPath = path.join( prefix, 'platforms/android/app/src/main/java', - packageName.replaceAll(".", "/"), + packageName.replaceAll('.', '/'), 'MainActivity.java' ); @@ -335,7 +335,7 @@ function removeLegacyKeyboardWorkaround() { const mainActivityPath = path.join( prefix, 'platforms/android/app/src/main/java', - packageName.replaceAll(".", "/"), + packageName.replaceAll('.', '/'), 'MainActivity.java' ); From a158df15883ad48da527822c29cfb3462fe4cc4a Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:59:44 +0100 Subject: [PATCH 29/36] Update commandRegistry.js --- src/cm/commandRegistry.js | 2106 ++++++++++++++++++++++++++++++------- 1 file changed, 1740 insertions(+), 366 deletions(-) diff --git a/src/cm/commandRegistry.js b/src/cm/commandRegistry.js index 44e9159372..bdf544e867 100644 --- a/src/cm/commandRegistry.js +++ b/src/cm/commandRegistry.js @@ -1,463 +1,1837 @@ -import type { Extension } from "@codemirror/state"; +import fsOperation from "fileSystem"; +import * as cmCommands from "@codemirror/commands"; +import { + cursorCharLeft, + cursorCharRight, + cursorDocEnd, + cursorDocStart, + cursorGroupLeft, + cursorGroupRight, + cursorLineDown, + cursorLineEnd, + cursorLineStart, + cursorLineUp, + cursorMatchingBracket, + cursorPageDown, + cursorPageUp, + deleteCharBackward, + deleteCharForward, + deleteGroupBackward, + deleteGroupForward, + deleteLineBoundaryForward, + deleteToLineEnd, + deleteToLineStart, + indentLess, + indentMore, + indentSelection, + insertBlankLine, + insertNewlineAndIndent, + lineComment, + lineUncomment, + redo, + selectAll, + selectCharLeft, + selectCharRight, + selectDocEnd, + selectDocStart, + selectGroupLeft, + selectGroupRight, + selectLine, + selectLineDown, + selectLineEnd, + selectLineStart, + selectLineUp, + selectMatchingBracket, + selectPageDown, + selectPageUp, + simplifySelection, + toggleBlockComment, + toggleLineComment, + undo, +} from "@codemirror/commands"; +import { + foldCode, + indentUnit as indentUnitFacet, + unfoldCode, +} from "@codemirror/language"; +import { + closeLintPanel, + forceLinting, + nextDiagnostic, + openLintPanel, + previousDiagnostic, +} from "@codemirror/lint"; +import { + LSPPlugin, + formatDocument as lspFormatDocument, +} from "@codemirror/lsp-client"; +import { Compartment, EditorSelection } from "@codemirror/state"; +import { keymap } from "@codemirror/view"; +import { focusEditorIfEditable } from "cm/editorReadOnly"; +import { + copyLineDownFoldAware, + copyLineUpFoldAware, + deleteLineFoldAware, + moveLineDownFoldAware, + moveLineUpFoldAware, +} from "cm/foldAwareLineCommands"; +import { foldAllCodeBlocks, unfoldAllCodeBlocks } from "cm/foldingCommands"; +import { + canonicalizeKeyBinding, + keyBindingsConflict, + toCodeMirrorKey, +} from "cm/keyBindingUtils"; +import { + renameSymbol as acodeRenameSymbol, + clearDiagnosticsEffect, + clientManager, + jumpToDeclaration as lspJumpToDeclaration, + jumpToDefinition as lspJumpToDefinition, + jumpToImplementation as lspJumpToImplementation, + jumpToTypeDefinition as lspJumpToTypeDefinition, + nextSignature as lspNextSignature, + prevSignature as lspPrevSignature, + showSignatureHelp as lspShowSignatureHelp, +} from "cm/lsp"; +import { + closeReferencesPanel as acodeCloseReferencesPanel, + findAllReferences as acodeFindAllReferences, + findAllReferencesInTab as acodeFindAllReferencesInTab, +} from "cm/lsp/references"; +import { showDocumentSymbols } from "components/symbolsPanel"; +import toast from "components/toast"; +import prompt from "dialogs/prompt"; +import actions from "handlers/quickTools"; +import keyBindings, { + APP_KEY_BINDING_NAMES, + CODEMIRROR_COMMAND_NAMES, +} from "lib/keyBindings"; +import settings from "lib/settings"; +import Url from "utils/Url"; -export type LanguageExtensionProvider = () => Extension | Promise; +const commandKeymapCompartment = new Compartment(); -export interface AddModeOptions { - aliases?: string[]; - filenameMatchers?: RegExp[]; - /** Mode whose formatter (and Prettier parser) this mode reuses. */ - formatAs?: string; -} +/** + * @typedef {import("@codemirror/view").EditorView} EditorView + */ + +/** + * @typedef {{ + * name: string; + * description?: string; + * readOnly?: boolean; + * run: (view?: EditorView | null) => boolean | void; + * requiresView?: boolean; + * defaultDescription?: string; + * defaultKey?: string | null; + * key?: string | null; + * }} CommandEntry + */ + +/** @type {Map} */ +const commandMap = new Map(); + +/** @type {Record} */ +let resolvedKeyBindings = keyBindings; + +/** @type {Record} */ +let cachedResolvedKeyBindings = {}; + +/** @type {Record} */ +let cachedEffectiveKeyBindings = {}; + +/** @type {{key: string, command: string, shadowedBy: string}[]} */ +let cachedKeyBindingConflicts = []; + +let resolvedKeyBindingsVersion = 0; + +/** @type {import("@codemirror/view").KeyBinding[]} */ +let cachedKeymap = []; + +/** @type {Set} */ +const commandViews = new Set(); + +const CODEMIRROR_COMMAND_ENTRIES = Object.entries(cmCommands).filter( + ([name, value]) => + typeof value === "function" && CODEMIRROR_COMMAND_NAMES.has(name), +); + +const CODEMIRROR_COMMAND_MAP = new Map( + CODEMIRROR_COMMAND_ENTRIES.map(([name, fn]) => [name, fn]), +); + +registerCoreCommands(); +registerLspCommands(); +registerLintCommands(); +registerCommandsFromKeyBindings(); +rebuildKeymap(); + +function registerCoreCommands() { + addCommand({ + name: "focusEditor", + description: "Focus editor", + readOnly: true, + requiresView: false, + run(view) { + const resolvedView = resolveView(view); + if (resolvedView) focusEditorIfEditable(resolvedView); + return true; + }, + }); + addCommand({ + name: "findFile", + description: "Find file in workspace", + readOnly: true, + requiresView: false, + run() { + acode.exec("find-file"); + return true; + }, + }); + addCommand({ + name: "closeCurrentTab", + description: "Close current tab", + readOnly: false, + requiresView: false, + run() { + acode.exec("close-current-tab"); + return true; + }, + }); + addCommand({ + name: "newPane", + description: "Create new editor pane", + readOnly: true, + requiresView: false, + run() { + acode.exec("new-pane"); + return true; + }, + }); + addCommand({ + name: "moveTabToNewPane", + description: "Move current tab to new pane", + readOnly: true, + requiresView: false, + run() { + acode.exec("move-tab-to-new-pane"); + return true; + }, + }); + addCommand({ + name: "closePane", + description: "Close active editor pane", + readOnly: true, + requiresView: false, + run() { + acode.exec("close-pane"); + return true; + }, + }); + addCommand({ + name: "focusNextPane", + description: "Focus next editor pane", + readOnly: true, + requiresView: false, + run() { + acode.exec("focus-next-pane"); + return true; + }, + }); + addCommand({ + name: "focusPreviousPane", + description: "Focus previous editor pane", + readOnly: true, + requiresView: false, + run() { + acode.exec("focus-previous-pane"); + return true; + }, + }); + addCommand({ + name: "closeAllTabs", + description: "Close all tabs", + readOnly: false, + requiresView: false, + run() { + acode.exec("close-all-tabs"); + return true; + }, + }); + addCommand({ + name: "togglePinnedTab", + description: "Pin or unpin current tab", + readOnly: true, + requiresView: false, + run() { + acode.exec("toggle-pin-tab"); + return true; + }, + }); + addCommand({ + name: "newFile", + description: "Create new file", + readOnly: true, + requiresView: false, + run() { + acode.exec("new-file"); + return true; + }, + }); + addCommand({ + name: "openFile", + description: "Open a file", + readOnly: true, + requiresView: false, + run() { + acode.exec("open-file"); + return true; + }, + }); + addCommand({ + name: "openFolder", + description: "Open a folder", + readOnly: true, + requiresView: false, + run() { + acode.exec("open-folder"); + return true; + }, + }); + addCommand({ + name: "saveFile", + description: "Save current file", + readOnly: true, + requiresView: false, + run() { + acode.exec("save"); + return true; + }, + }); + addCommand({ + name: "saveFileAs", + description: "Save as current file", + readOnly: true, + requiresView: false, + run() { + acode.exec("save-as"); + return true; + }, + }); + addCommand({ + name: "saveAllChanges", + description: "Save all changes", + readOnly: true, + requiresView: false, + run() { + acode.exec("save-all-changes"); + return true; + }, + }); + addCommand({ + name: "nextFile", + description: "Open next file tab", + readOnly: true, + requiresView: false, + run() { + acode.exec("next-file"); + return true; + }, + }); + addCommand({ + name: "prevFile", + description: "Open previous file tab", + readOnly: true, + requiresView: false, + run() { + acode.exec("prev-file"); + return true; + }, + }); + addCommand({ + name: "nextFileHistory", + description: "Open next file tab from history", + readOnly: true, + requiresView: false, + run() { + acode.exec("next-file-history"); + return true; + }, + }); + addCommand({ + name: "prevFileHistory", + description: "Open previous file tab from history", + readOnly: true, + requiresView: false, + run() { + acode.exec("prev-file-history"); + return true; + }, + }); + addCommand({ + name: "showSettingsMenu", + description: "Show settings menu", + readOnly: true, + requiresView: false, + run() { + acode.exec("open", "settings"); + return true; + }, + }); + addCommand({ + name: "renameFile", + description: "Rename active file", + readOnly: true, + requiresView: false, + run() { + acode.exec("rename"); + return true; + }, + }); + addCommand({ + name: "run", + description: "Preview HTML and MarkDown", + readOnly: true, + requiresView: false, + run() { + acode.exec("run"); + return true; + }, + }); + addCommand({ + name: "openInAppBrowser", + description: "Open In-App Browser", + readOnly: true, + requiresView: false, + run: openInAppBrowserCommand, + }); + addCommand({ + name: "toggleFullscreen", + description: "Toggle full screen mode", + readOnly: true, + requiresView: false, + run() { + acode.exec("toggle-fullscreen"); + return true; + }, + }); + addCommand({ + name: "toggleSidebar", + description: "Toggle sidebar", + readOnly: true, + requiresView: false, + run() { + acode.exec("toggle-sidebar"); + return true; + }, + }); + addCommand({ + name: "toggleMenu", + description: "Toggle main menu", + readOnly: true, + requiresView: false, + run() { + acode.exec("toggle-menu"); + return true; + }, + }); + addCommand({ + name: "toggleEditMenu", + description: "Toggle edit menu", + readOnly: true, + requiresView: false, + run() { + acode.exec("toggle-editmenu"); + return true; + }, + }); + addCommand({ + name: "selectall", + description: "Select all", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return selectAll(resolvedView); + }, + }); + addCommand({ + name: "gotoline", + description: "Go to line...", + readOnly: true, + requiresView: false, + run() { + acode.exec("goto"); + return true; + }, + }); + addCommand({ + name: "find", + description: "Find", + readOnly: true, + requiresView: false, + run() { + acode.exec("find"); + return true; + }, + }); + addCommand({ + name: "copy", + description: "Copy", + readOnly: true, + requiresView: true, + run: copyCommand, + }); + addCommand({ + name: "cut", + description: "Cut", + readOnly: false, + requiresView: true, + run: cutCommand, + }); + addCommand({ + name: "paste", + description: "Paste", + readOnly: false, + requiresView: true, + run: pasteCommand, + }); + + addCommand({ + name: "share", + description: "Share", + readOnly: true, + requiresView: true, + run: shareCommand, + }); + addCommand({ + name: "problems", + description: "Show errors and warnings", + readOnly: true, + requiresView: false, + run() { + acode.exec("open", "problems"); + return true; + }, + }); + addCommand({ + name: "replace", + description: "Replace", + readOnly: true, + requiresView: false, + run() { + acode.exec("replace"); + return true; + }, + }); + addCommand({ + name: "openCommandPalette", + description: "Open command palette", + readOnly: true, + requiresView: false, + run() { + acode.exec("command-palette"); + return true; + }, + }); + addCommand({ + name: "modeSelect", + description: "Change language mode...", + readOnly: true, + requiresView: false, + run() { + acode.exec("syntax"); + return true; + }, + }); + addCommand({ + name: "toggleQuickTools", + description: "Toggle quick tools", + readOnly: true, + requiresView: false, + run() { + actions("toggle"); + return true; + }, + }); + addCommand({ + name: "selectWord", + description: "Select current word", + readOnly: false, + requiresView: true, + run: selectWordCommand, + }); + addCommand({ + name: "openLogFile", + description: "Open Log File", + readOnly: true, + requiresView: false, + run() { + acode.exec("open-log-file"); + return true; + }, + }); + addCommand({ + name: "increaseUiZoom", + description: "Increase UI zoom", + readOnly: true, + requiresView: false, + run: () => adjustUiZoom(10), + }); + addCommand({ + name: "decreaseUiZoom", + description: "Decrease UI zoom", + readOnly: true, + requiresView: false, + run: () => adjustUiZoom(-10), + }); + addCommand({ + name: "increaseFontSize", + description: "Increase editor font size", + readOnly: true, + requiresView: false, + run: () => adjustFontSize(1), + }); + addCommand({ + name: "decreaseFontSize", + description: "Decrease editor font size", + readOnly: true, + requiresView: false, + run: () => adjustFontSize(-1), + }); + addCommand({ + name: "openPluginsPage", + description: "Open Plugins Page", + readOnly: true, + requiresView: false, + run() { + acode.exec("open", "plugins"); + return true; + }, + }); + addCommand({ + name: "openFileExplorer", + description: "File Explorer", + readOnly: true, + requiresView: false, + run() { + acode.exec("open", "file_browser"); + return true; + }, + }); + addCommand({ + name: "copyDeviceInfo", + description: "Copy Device info", + readOnly: true, + requiresView: false, + run() { + acode.exec("copy-device-info"); + return true; + }, + }); + addCommand({ + name: "changeAppTheme", + description: "Change App Theme", + readOnly: true, + requiresView: false, + run() { + acode.exec("change-app-theme"); + return true; + }, + }); + addCommand({ + name: "changeEditorTheme", + description: "Change Editor Theme", + readOnly: true, + requiresView: false, + run() { + acode.exec("change-editor-theme"); + return true; + }, + }); + addCommand({ + name: "openTerminal", + description: "Open Terminal", + readOnly: true, + requiresView: false, + run() { + acode.exec("new-terminal"); + return true; + }, + }); + addCommand({ + name: "acode:showWelcome", + description: "Show Welcome", + readOnly: true, + requiresView: false, + run() { + acode.exec("welcome"); + return true; + }, + }); + addCommand({ + name: "run-tests", + description: "Run Tests", + key: "Ctrl-Shift-T", + readOnly: true, + requiresView: false, + run() { + acode.exec("run-tests"); + return true; + }, + }); + addCommand({ + name: "dev:openInspector", + description: "Open Inspector", + run() { + acode.exec("open-inspector"); + return true; + }, + readOnly: true, + requiresView: false, + }); + addCommand({ + name: "dev:toggleDevTools", + description: "Toggle Developer Tools", + run() { + acode.exec("toggle-inspector"); + return true; + }, + readOnly: true, + requiresView: false, + key: "Ctrl-Shift-I", + }); -export interface ModesByName { - [name: string]: Mode; + // Additional editor-centric helpers mapped to CodeMirror primitives that have existing key bindings in defaults. + addCommand({ + name: "duplicateSelection", + description: "Duplicate selection", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return copyLineDownFoldAware(resolvedView); + }, + }); + addCommand({ + name: "copylinesdown", + description: "Copy lines down", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return copyLineDownFoldAware(resolvedView); + }, + }); + addCommand({ + name: "copylinesup", + description: "Copy lines up", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return copyLineUpFoldAware(resolvedView); + }, + }); + addCommand({ + name: "movelinesdown", + description: "Move lines down", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return moveLineDownFoldAware(resolvedView); + }, + }); + addCommand({ + name: "movelinesup", + description: "Move lines up", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return moveLineUpFoldAware(resolvedView); + }, + }); + addCommand({ + name: "removeline", + description: "Remove line", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return deleteLineFoldAware(resolvedView); + }, + }); + addCommand({ + name: "insertlineafter", + description: "Insert line after", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return insertBlankLine(resolvedView); + }, + }); + addCommand({ + name: "selectline", + description: "Select line", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return selectLine(resolvedView); + }, + }); + addCommand({ + name: "selectlinesdown", + description: "Select line down", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return selectLineDown(resolvedView); + }, + }); + addCommand({ + name: "selectlinesup", + description: "Select line up", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return selectLineUp(resolvedView); + }, + }); + addCommand({ + name: "selectlinestart", + description: "Select line start", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return selectLineStart(resolvedView); + }, + }); + addCommand({ + name: "selectlineend", + description: "Select line end", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return selectLineEnd(resolvedView); + }, + }); + addCommand({ + name: "indent", + description: "Indent", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + const { state } = resolvedView; + const hasSelection = state.selection.ranges.some((range) => !range.empty); + if (hasSelection) { + return indentMore(resolvedView); + } + const indentString = + state.facet(indentUnitFacet) || + (settings?.value?.softTab + ? " ".repeat(Math.max(1, Number(settings?.value?.tabSize) || 2)) + : "\t"); + const insert = indentString && indentString.length ? indentString : "\t"; + resolvedView.dispatch( + state.changeByRange((range) => ({ + changes: { from: range.from, to: range.to, insert }, + range: EditorSelection.cursor(range.from + insert.length), + })), + ); + return true; + }, + }); + addCommand({ + name: "outdent", + description: "Outdent", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return indentLess(resolvedView); + }, + }); + addCommand({ + name: "indentselection", + description: "Indent selection", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return indentSelection(resolvedView); + }, + }); + addCommand({ + name: "newline", + description: "Insert newline", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return insertNewlineAndIndent(resolvedView); + }, + }); + addCommand({ + name: "joinlines", + description: "Join lines", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return deleteLineBoundaryForward(resolvedView); + }, + }); + addCommand({ + name: "deletetolinestart", + description: "Delete to line start", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return deleteToLineStart(resolvedView); + }, + }); + addCommand({ + name: "deletetolineend", + description: "Delete to line end", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return deleteToLineEnd(resolvedView); + }, + }); + addCommand({ + name: "togglecomment", + description: "Toggle comment", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return toggleLineComment(resolvedView); + }, + }); + addCommand({ + name: "comment", + description: "Add line comment", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return lineComment(resolvedView); + }, + }); + addCommand({ + name: "uncomment", + description: "Remove line comment", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return lineUncomment(resolvedView); + }, + }); + addCommand({ + name: "toggleBlockComment", + description: "Toggle block comment", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return toggleBlockComment(resolvedView); + }, + }); + addCommand({ + name: "undo", + description: "Undo", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return undo(resolvedView); + }, + }); + addCommand({ + name: "redo", + description: "Redo", + readOnly: false, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return redo(resolvedView); + }, + }); + addCommand({ + name: "simplifySelection", + description: "Simplify selection", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return simplifySelection(resolvedView); + }, + }); + addCommand({ + name: "foldCode", + description: "Fold the Lines that are selected (if possible)", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return foldCode(resolvedView); + }, + }); + addCommand({ + name: "unfoldCode", + description: "Unfold folded ranges on selected lines.", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return unfoldCode(resolvedView); + }, + }); + addCommand({ + name: "foldAll", + description: + "Fold all - top-level ranges usually depends on the syntax tree. It may not work reliably if the document isn't fully parsed (e.g., just initialized or too large to parse completely)", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return foldAllCodeBlocks(resolvedView); + }, + }); + addCommand({ + name: "unfoldAll", + description: "Unfold all folded code.", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return unfoldAllCodeBlocks(resolvedView); + }, + }); } -const modesByName: ModesByName = {}; -const modes: Mode[] = []; +function registerLspCommands() { + addCommand({ + name: "formatDocument", + description: "Format document (Language Server)", + readOnly: false, + requiresView: true, + run: runLspCommand(lspFormatDocument), + }); + addCommand({ + name: "renameSymbol", + description: "Rename symbol (Language Server)", + readOnly: false, + requiresView: true, + run: runLspCommand(acodeRenameSymbol), + }); + addCommand({ + name: "showSignatureHelp", + description: "Show signature help", + readOnly: true, + requiresView: true, + run: runLspCommand(lspShowSignatureHelp), + }); + addCommand({ + name: "nextSignature", + description: "Next signature", + readOnly: true, + requiresView: true, + run: runLspCommand(lspNextSignature, { silentOnMissing: true }), + }); + addCommand({ + name: "prevSignature", + description: "Previous signature", + readOnly: true, + requiresView: true, + run: runLspCommand(lspPrevSignature, { silentOnMissing: true }), + }); + addCommand({ + name: "jumpToDefinition", + description: "Go to definition (Language Server)", + readOnly: true, + requiresView: true, + run: runLspCommand(lspJumpToDefinition), + }); + addCommand({ + name: "jumpToDeclaration", + description: "Go to declaration (Language Server)", + readOnly: true, + requiresView: true, + run: runLspCommand(lspJumpToDeclaration), + }); + addCommand({ + name: "jumpToTypeDefinition", + description: "Go to type definition (Language Server)", + readOnly: true, + requiresView: true, + run: runLspCommand(lspJumpToTypeDefinition), + }); + addCommand({ + name: "jumpToImplementation", + description: "Go to implementation (Language Server)", + readOnly: true, + requiresView: true, + run: runLspCommand(lspJumpToImplementation), + }); + addCommand({ + name: "findReferences", + description: "Find all references (Language Server)", + readOnly: true, + requiresView: true, + async run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + const plugin = LSPPlugin.get(resolvedView); + if (!plugin) { + notifyLspUnavailable(); + return false; + } + return acodeFindAllReferences(resolvedView); + }, + }); + addCommand({ + name: "closeReferencePanel", + description: "Close references panel", + readOnly: true, + requiresView: false, + run() { + return acodeCloseReferencesPanel(); + }, + }); + addCommand({ + name: "findReferencesInTab", + description: "Find all references in new tab (Language Server)", + readOnly: true, + requiresView: true, + async run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + const plugin = LSPPlugin.get(resolvedView); + if (!plugin) { + notifyLspUnavailable(); + return false; + } + return acodeFindAllReferencesInTab(resolvedView); + }, + }); + addCommand({ + name: "restartAllLspServers", + description: "Restart all running LSP servers", + readOnly: true, + requiresView: false, + async run() { + const activeClients = clientManager.getActiveClients(); + if (!activeClients.length) { + toast("No LSP servers are currently running"); + return true; + } + const count = activeClients.length; + toast(`Restarting ${count} LSP server${count > 1 ? "s" : ""}...`); + + // Dispose all clients (also clears diagnostics) + await clientManager.dispose(); -const FILE_NAME_CACHE_LIMIT = 2000; + // Trigger reconnect for active file + editorManager?.restartLsp?.(); + return true; + }, + }); + addCommand({ + name: "stopAllLspServers", + description: "Stop all running LSP servers", + readOnly: true, + requiresView: false, + async run() { + const activeClients = clientManager.getActiveClients(); + if (!activeClients.length) { + toast("No LSP servers are currently running"); + return true; + } + const count = activeClients.length; -interface NamedCheck { - mode: Mode; - exactName?: string; - matcher?: RegExp; + // Dispose all clients + await clientManager.dispose(); + toast(`Stopped ${count} LSP server${count > 1 ? "s" : ""}`); + return true; + }, + }); + addCommand({ + name: "documentSymbols", + description: "Go to Symbol in Document...", + readOnly: true, + requiresView: true, + async run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return showDocumentSymbols(resolvedView); + }, + }); } -interface ModeIndex { - sorted: Mode[]; - namedChecks: NamedCheck[]; - extensions: Map; - rankByMode: Map; +function registerLintCommands() { + addCommand({ + name: "openLintPanel", + description: "Open lint panel", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return openLintPanel(resolvedView); + }, + }); + addCommand({ + name: "closeLintPanel", + description: "Close lint panel", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return closeLintPanel(resolvedView); + }, + }); + addCommand({ + name: "nextDiagnostic", + description: "Go to next diagnostic", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return nextDiagnostic(resolvedView); + }, + }); + addCommand({ + name: "previousDiagnostic", + description: "Go to previous diagnostic", + readOnly: true, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return previousDiagnostic(resolvedView); + }, + }); } -let modeIndex: ModeIndex | null = null; -const resolvedByFileName = new Map(); +function registerCommandsFromKeyBindings() { + Object.entries(keyBindings).forEach(([name, binding]) => { + if (commandMap.has(name)) return; + const description = binding?.description || humanizeCommandName(name); + const readOnly = binding?.readOnly ?? false; + const requiresView = !!binding?.editorOnly; + const commandFn = CODEMIRROR_COMMAND_MAP.get(name); -function normalizeModeKey(value: string): string { - return String(value ?? "") - .trim() - .toLowerCase(); + if (binding?.action) { + addCommand({ + name, + description, + readOnly, + requiresView, + run(view) { + try { + if (requiresView) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + } + acode.exec(binding.action); + return true; + } catch (error) { + console.error(`Failed to execute action ${binding.action}`, error); + return false; + } + }, + }); + return; + } + + if (commandFn) { + addCommand({ + name, + description, + readOnly, + requiresView: true, + run(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + return commandFn(resolvedView); + }, + }); + } + }); } -function normalizeAliases(aliases: string[] = [], name: string): string[] { - const normalized = new Set(); - for (const alias of aliases) { - const key = normalizeModeKey(alias); - if (!key || key === name) continue; - normalized.add(key); - } - return [...normalized]; +function addCommand(entry) { + const command = { + ...entry, + defaultDescription: entry.description || entry.name, + defaultKey: entry.key ?? null, + key: entry.key ?? null, + }; + commandMap.set(entry.name, command); } -function escapeRegExp(value: string): string { - return String(value ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +function resolveView(view) { + return view || editorManager?.editor || null; } -function fileNameFromPath(path: string): string { - const value = String(path ?? ""); - const slash = value.lastIndexOf("/"); - const backslash = value.lastIndexOf("\\"); - const sep = slash > backslash ? slash : backslash; - return sep === -1 ? value : value.slice(sep + 1); +function notifyLspUnavailable() { + toast?.("Language server not available"); } -function invalidateModeIndex(): void { - modeIndex = null; - resolvedByFileName.clear(); +function runLspCommand(commandFn, options = {}) { + return (view) => { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + const plugin = LSPPlugin.get(resolvedView); + if (!plugin) { + if (!options?.silentOnMissing) { + notifyLspUnavailable(); + } + return false; + } + const result = commandFn(resolvedView); + return result !== false; + }; } -/** - * Initialize CodeMirror mode list functionality - */ -export function initModes(): void { - // CodeMirror modes don't need the same ace.define wrapper - // but we maintain the same API structure for compatibility +function humanizeCommandName(name) { + return name + .replace(/[a-z0-9](?=[A-Z])/g, "$& ") + .replaceAll("_", " ") + .replace(/^./, (char) => char.toUpperCase()); } -/** - * Add language mode to CodeMirror editor - */ -export function addMode( - name: string, - extensions: string | string[], - caption?: string, - languageExtension: LanguageExtensionProvider | null = null, - options: AddModeOptions = {}, -): void { - const filename = normalizeModeKey(name); - const mode = new Mode( - filename, - caption, - extensions, - languageExtension, - options, - ); - modesByName[filename] = mode; - mode.aliases.forEach((alias) => { - if (!modesByName[alias]) { - modesByName[alias] = mode; +function copyCommand(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + const { state } = resolvedView; + const texts = state.selection.ranges.map((range) => { + if (range.empty) { + const line = state.doc.lineAt(range.head); + return state.doc.sliceString(line.from, line.to); } + return state.doc.sliceString(range.from, range.to); }); - modes.push(mode); - invalidateModeIndex(); + const textToCopy = texts.join("\n"); + cordova.plugins.clipboard.copy(textToCopy); + return true; } -/** - * Remove language mode from CodeMirror editor - */ -export function removeMode(name: string): void { - const filename = normalizeModeKey(name); - const mode = modesByName[filename]; - if (!mode) return; - - delete modesByName[mode.name]; - mode.aliases.forEach((alias) => { - if (modesByName[alias] === mode) { - delete modesByName[alias]; +function cutCommand(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + const { state } = resolvedView; + const ranges = state.selection.ranges; + const segments = []; + let changes = []; + ranges.forEach((range) => { + if (range.empty) { + const line = state.doc.lineAt(range.head); + segments.push(state.doc.sliceString(line.from, line.to)); + changes.push({ from: line.from, to: line.to, insert: "" }); + return; } + segments.push(state.doc.sliceString(range.from, range.to)); + changes.push({ from: range.from, to: range.to, insert: "" }); + }); + cordova.plugins.clipboard.copy(segments.join("\n")); + resolvedView.dispatch({ + changes, + selection: EditorSelection.single( + changes[0]?.from ?? state.selection.main.from, + ), }); + return true; +} - const modeIndexInList = modes.findIndex( - (registeredMode) => registeredMode === mode, - ); - if (modeIndexInList >= 0) { - modes.splice(modeIndexInList, 1); - } - invalidateModeIndex(); +function pasteCommand(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + cordova.plugins.clipboard.paste((text = "") => { + // replaceSelection measures the inserted text after line-ending + // normalization, so CRLF clipboard text can't push the cursor past + // the end of the document. + resolvedView.dispatch(resolvedView.state.replaceSelection(String(text)), { + userEvent: "input.paste", + }); + }); + return true; } -/** - * Calculates a specificity score for a mode. - * Higher score means more specific. - * - Anchored patterns (e.g., "^Dockerfile") get a base score of 1000. - * - Non-anchored patterns (extensions) are scored by length. - */ -function getModeSpecificityScore(modeInstance: Mode): number { - if (modeInstance.name.toLowerCase() === "text") { - return 0; - } +function shareCommand(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; - const extensionsStr = modeInstance.extensions; - let maxScore = 0; - - if (extensionsStr) { - const patterns = extensionsStr.split("|"); - for (const pattern of patterns) { - let currentScore = 0; - if (pattern.startsWith("^")) { - // Exact filename match or anchored pattern - currentScore = 1000 + (pattern.length - 1); // Subtract 1 for '^' - } else { - // Extension match - currentScore = pattern.length; - } - if (currentScore > maxScore) { - maxScore = currentScore; - } - } - } + const { state } = resolvedView; + const ranges = state.selection.ranges; + const segments = []; - for (const matcher of modeInstance.filenameMatchers) { - const score = 1000 + matcher.source.length; - if (score > maxScore) { - maxScore = score; + ranges.forEach((range) => { + if (range.empty) { + const line = state.doc.lineAt(range.head); + segments.push(state.doc.sliceString(line.from, line.to)); + return; } - } - return maxScore; -} + segments.push(state.doc.sliceString(range.from, range.to)); + }); -function exactNameFromRegex(matcher: RegExp): string | null { - const otherFlags = matcher.flags.replaceAll("i", ""); - if (otherFlags) return null; + const textToShare = segments.join("\n"); - const source = matcher.source; - if ( - source.length < 2 || - source[0] !== "^" || - source[source.length - 1] !== "$" - ) { - return null; - } + system.shareText(textToShare, console.log, console.error); - const inner = source.slice(1, -1); - let name = ""; - for (let i = 0; i < inner.length; i++) { - const ch = inner[i]; - if (ch === "\\") { - const next = inner[i + 1]; - if (!next) return null; - name += next; - i++; - continue; - } - if ("^$|.*+?()[]{}".includes(ch)) return null; - name += ch; - } + return true; +} - return name ? name.toLowerCase() : null; +function selectWordCommand(view) { + const resolvedView = resolveView(view); + if (!resolvedView) return false; + const { state } = resolvedView; + const ranges = state.selection.ranges.map((range) => { + const word = state.wordAt(range.head); + if (word) return EditorSelection.range(word.from, word.to); + const line = state.doc.lineAt(range.head); + return EditorSelection.range(line.from, line.to); + }); + resolvedView.dispatch({ + selection: EditorSelection.create(ranges, state.selection.mainIndex), + }); + return true; } -function rememberFirst(map: Map, key: string, mode: Mode): void { - if (key && !map.has(key)) { - map.set(key, mode); - } +async function openInAppBrowserCommand() { + const url = await prompt("Enter url", "", "url", { + placeholder: "http://", + match: /^https?:\/\/.+/, + }); + if (url) acode.exec("open-inapp-browser", url); + return true; } -function getModeIndex(): ModeIndex { - if (modeIndex) return modeIndex; +function adjustFontSize(delta) { + const current = settings?.value?.fontSize || "12px"; + const numeric = Number.parseInt(current, 10) || 12; + const next = Math.min(72, Math.max(6, numeric + delta)); + settings.value.fontSize = `${next}px`; + settings.update(false); + return true; +} - const ranked = modes.map((mode, index) => ({ - mode, - score: getModeSpecificityScore(mode), - index, - })); - ranked.sort((a, b) => { - const scoreDiff = b.score - a.score; - return scoreDiff !== 0 ? scoreDiff : b.index - a.index; - }); +function adjustUiZoom(delta) { + const current = Number(settings?.value?.uiZoom) || 100; + const next = Math.min(160, Math.max(70, current + delta)); + settings.value.uiZoom = next; + settings.update(false); + return true; +} - const sorted = ranked.map((entry) => entry.mode); - const rankByMode = new Map(); - const namedChecks: NamedCheck[] = []; - const extensions = new Map(); +function parseKeyString(keyString) { + if (!keyString) return []; + return String(keyString) + .split("|") + .map((combo) => combo.trim()) + .filter(Boolean); +} - for (let rank = 0; rank < sorted.length; rank++) { - rankByMode.set(sorted[rank], rank); - } +function hasOwnBindingOverride(name) { + return Object.prototype.hasOwnProperty.call(resolvedKeyBindings ?? {}, name); +} - for (const { mode } of ranked) { - if (mode.extensions) { - for (const raw of mode.extensions.split("|")) { - const pattern = raw.trim(); - if (!pattern) continue; - if (pattern.startsWith("^")) { - namedChecks.push({ - mode, - exactName: pattern.slice(1).toLowerCase(), - }); - } else { - rememberFirst(extensions, pattern.toLowerCase(), mode); - } - } - } +function resolveBindingInfo(name) { + const baseBinding = keyBindings[name] ?? null; + if (!hasOwnBindingOverride(name)) return baseBinding; - for (const matcher of mode.filenameMatchers) { - const exactName = exactNameFromRegex(matcher); - if (exactName) { - namedChecks.push({ mode, exactName }); - continue; - } - namedChecks.push({ mode, matcher }); - } + const override = resolvedKeyBindings?.[name]; + if (override === null) { + return baseBinding ? { ...baseBinding, key: null } : { key: null }; } - modeIndex = { sorted, namedChecks, extensions, rankByMode }; - return modeIndex; -} - -function findModeByExtension( - fileNameLower: string, - extensions: Map, - rankByMode: Map, -): Mode | undefined { - let best: Mode | undefined; - let bestRank = Number.POSITIVE_INFINITY; - let dot = fileNameLower.indexOf("."); - while (dot >= 0 && dot < fileNameLower.length - 1) { - const mode = extensions.get(fileNameLower.slice(dot + 1)); - if (mode) { - const rank = rankByMode.get(mode) ?? Number.POSITIVE_INFINITY; - if (rank < bestRank) { - best = mode; - bestRank = rank; - } - } - dot = fileNameLower.indexOf(".", dot + 1); + if (!override || typeof override !== "object") { + return baseBinding; } - return best; + + return baseBinding ? { ...baseBinding, ...override } : override; } -function resolveModeForPath(fileName: string): Mode { - const fallback = modesByName.text; - const index = getModeIndex(); - const fileNameLower = fileName.toLowerCase(); +function buildResolvedKeyBindingsSnapshot() { + const bindingNames = new Set([ + ...Object.keys(keyBindings), + ...Object.keys(resolvedKeyBindings ?? {}), + ]); - for (const check of index.namedChecks) { - if (check.exactName) { - if ( - check.exactName === fileNameLower && - check.mode.supportsFile?.(fileName) - ) { - return check.mode; + return Object.fromEntries( + Array.from(bindingNames, (name) => [name, resolveBindingInfo(name)]).filter( + ([, binding]) => binding, + ), + ); +} + +function rebuildKeymap() { + cachedResolvedKeyBindings = buildResolvedKeyBindingsSnapshot(); + const candidates = []; + let order = 0; + commandMap.forEach((command, name) => { + const bindingInfo = resolveBindingInfo(name); + command.description = + bindingInfo?.description || command.defaultDescription; + const keySource = + bindingInfo && Object.prototype.hasOwnProperty.call(bindingInfo, "key") + ? bindingInfo.key + : (command.defaultKey ?? null); + command.key = keySource; + const combos = parseKeyString(keySource); + combos.forEach((combo) => { + const cmKey = toCodeMirrorKey(combo); + if (!cmKey) return; + candidates.push({ + name, + key: cmKey, + rawKey: combo, + order: order++, + priority: getBindingPriority(name), + }); + }); + }); + + candidates.sort( + (left, right) => right.priority - left.priority || left.order - right.order, + ); + + const bindings = []; + const claimedKeys = new Map(); + const effectiveKeys = new Map(); + const conflicts = []; + for (const candidate of candidates) { + const canonicalKey = canonicalizeKeyBinding(candidate.key); + const claimed = Array.from(claimedKeys.entries()).find(([key]) => + keyBindingsConflict(key, canonicalKey), + ); + if (claimed) { + const [claimedKey, owner] = claimed; + const appCommandShadowsCodeMirrorDefault = + APP_KEY_BINDING_NAMES.has(owner) && + CODEMIRROR_COMMAND_NAMES.has(candidate.name) && + candidate.priority === 10; + const repeatedKeyForSameCommand = + owner === candidate.name && claimedKey === canonicalKey; + if (!repeatedKeyForSameCommand && !appCommandShadowsCodeMirrorDefault) { + conflicts.push({ + key: candidate.key, + command: candidate.name, + shadowedBy: owner, + }); } continue; } - const matcher = check.matcher; - if (!matcher) continue; - matcher.lastIndex = 0; - if (matcher.test(fileName) && check.mode.supportsFile?.(fileName)) { - return check.mode; + claimedKeys.set(canonicalKey, candidate.name); + if (!effectiveKeys.has(candidate.name)) { + effectiveKeys.set(candidate.name, []); } + effectiveKeys.get(candidate.name).push(candidate.rawKey); + bindings.push({ + key: candidate.key, + run: (view) => executeCommand(candidate.name, view), + preventDefault: true, + }); } - const byExtension = findModeByExtension( - fileNameLower, - index.extensions, - index.rankByMode, + cachedEffectiveKeyBindings = Object.fromEntries( + Object.entries(cachedResolvedKeyBindings).map(([name, binding]) => [ + name, + { + ...binding, + key: effectiveKeys.get(name)?.join("|") || null, + }, + ]), ); - if (byExtension?.supportsFile?.(fileName)) return byExtension; + cachedKeyBindingConflicts = conflicts; + cachedKeymap = bindings; + resolvedKeyBindingsVersion += 1; + return bindings; +} - for (const mode of index.sorted) { - if (mode.supportsFile?.(fileName)) return mode; +function getBindingPriority(name) { + if (APP_KEY_BINDING_NAMES.has(name)) return 40; + if (!Object.prototype.hasOwnProperty.call(keyBindings, name)) return 30; + + const override = resolvedKeyBindings?.[name]; + if ( + override && + typeof override === "object" && + Object.prototype.hasOwnProperty.call(override, "key") && + override.key !== keyBindings[name]?.key + ) { + return 20; } - return fallback; + return 10; +} + +function resolveCommand(name) { + return commandMap.get(name) || null; +} + +function commandRunsInReadOnly(command, view) { + if (!view) return command.readOnly; + return view.state?.readOnly ? !!command.readOnly : true; } -function cacheResolvedMode(fileNameLower: string, mode: Mode): Mode { - if (resolvedByFileName.size >= FILE_NAME_CACHE_LIMIT) { - resolvedByFileName.clear(); +export function executeCommand(name, view, args) { + const command = resolveCommand(name); + if (!command) return false; + const targetView = command.requiresView + ? resolveView(view) + : resolveView(view) || null; + if (command.requiresView && !targetView) return false; + if (!commandRunsInReadOnly(command, targetView)) return false; + try { + const result = command.run(targetView, args); + return result !== false; + } catch (error) { + console.error(`Failed to execute command ${name}`, error); + return false; } - resolvedByFileName.set(fileNameLower, mode); - return mode; } -/** - * Get mode for file path - */ -export function getModeForPath(path: string): Mode { - const fileName = fileNameFromPath(path); - const cached = resolvedByFileName.get(fileName); - if (cached) return cached; +export function getRegisteredCommands() { + return Array.from(commandMap.values()).map((command) => ({ + name: command.name, + description: command.description || command.defaultDescription, + key: command.key || null, + })); +} - return cacheResolvedMode(fileName, resolveModeForPath(fileName)); +export function getResolvedKeyBindings() { + return cachedResolvedKeyBindings; } -/** - * Get all modes by name - */ -export function getModesByName(): ModesByName { - return modesByName; +export function getEffectiveKeyBindings() { + return cachedEffectiveKeyBindings; } -/** - * Get all modes array - */ -export function getModes(): Mode[] { - return modes; +export function getKeyBindingConflicts() { + return cachedKeyBindingConflicts.map((conflict) => ({ ...conflict })); } -export function getMode(name: string): Mode | null { - return modesByName[normalizeModeKey(name)] || null; +export function getResolvedKeyBindingsVersion() { + return resolvedKeyBindingsVersion; } -/** - * Name of the mode that `name` formats as, with aliases resolved, or `null`. - */ -export function getFormatAsMode(name: string): string | null { - const formatAs = getMode(name)?.formatAs; - if (!formatAs) return null; - return getMode(formatAs)?.name ?? formatAs; -} - -export class Mode { - extensions: string; - caption: string; - name: string; - mode: string; - aliases: string[]; - extRe: RegExp | null; - filenameMatchers: RegExp[]; - formatAs: string | null; - languageExtension: LanguageExtensionProvider | null; - - constructor( - name: string, - caption: string | undefined, - extensions: string | string[], - languageExtension: LanguageExtensionProvider | null = null, - options: AddModeOptions = {}, - ) { - if (Array.isArray(extensions)) { - extensions = extensions.join("|"); - } +export function getCommandKeymapExtension() { + return commandKeymapCompartment.of(keymap.of(cachedKeymap)); +} - this.name = name; - this.mode = name; // CodeMirror uses different mode naming - this.extensions = extensions; - this.caption = caption || this.name.replaceAll("_", " "); - // Plugins may pass anything here; ignore what isn't the expected shape - const { aliases, filenameMatchers, formatAs } = - options && typeof options === "object" ? options : {}; - this.aliases = Array.isArray(aliases) - ? normalizeAliases(aliases, this.name) - : []; - this.filenameMatchers = Array.isArray(filenameMatchers) - ? filenameMatchers.filter((matcher) => matcher instanceof RegExp) - : []; - this.formatAs = - typeof formatAs === "string" && normalizeModeKey(formatAs) - ? normalizeModeKey(formatAs) - : null; - this.languageExtension = languageExtension; - let re = ""; - - if (!extensions) { - this.extRe = null; - return; +export async function setKeyBindings(view) { + await loadCustomKeyBindings(); + const bindings = rebuildKeymap(); + const resolvedView = resolveView(view); + if (resolvedView) commandViews.add(resolvedView); + for (const knownView of commandViews) { + if (!knownView.dom?.isConnected) { + commandViews.delete(knownView); + continue; } + applyCommandKeymap(knownView, bindings); + } + return getKeyBindingConflicts(); +} - const patterns = extensions - .split("|") - .map((pattern) => pattern.trim()) - .filter(Boolean); - const filenamePatterns = patterns - .filter((pattern) => pattern.startsWith("^")) - .map((pattern) => `^${escapeRegExp(pattern.slice(1))}$`); - const extensionPatterns = patterns - .filter((pattern) => !pattern.startsWith("^")) - .map((pattern) => escapeRegExp(pattern)); - const regexParts: string[] = []; - - if (extensionPatterns.length) { - regexParts.push(`^.*?\\.(${extensionPatterns.join("|")})$`); - } +async function loadCustomKeyBindings() { + try { + const bindingsFile = fsOperation(KEYBINDING_FILE); + if (await bindingsFile.exists()) { + const bindings = await bindingsFile.readFile("json"); + if ( + !bindings || + typeof bindings !== "object" || + Array.isArray(bindings) + ) { + throw new TypeError("Key bindings must be a JSON object"); + } - regexParts.push(...filenamePatterns); + let updated = false; + Object.keys(keyBindings).forEach((key) => { + if (!(key in bindings)) { + bindings[key] = keyBindings[key]; + updated = true; + } + }); + resolvedKeyBindings = bindings; + if (updated) { + bindingsFile + .writeFile(JSON.stringify(bindings, undefined, 2)) + .catch((error) => { + window.log?.("error", "Failed to back-fill new key bindings!"); + window.log?.("error", error); + }); + } + } else { + throw new Error("Key binding file not found"); + } + } catch (error) { + await resetKeyBindings(); + resolvedKeyBindings = keyBindings; + } +} - if (!regexParts.length) { - this.extRe = null; +export async function resetKeyBindings() { + try { + const fs = fsOperation(KEYBINDING_FILE); + const fileName = Url.basename(KEYBINDING_FILE); + const content = JSON.stringify(keyBindings, undefined, 2); + if (!(await fs.exists())) { + await fsOperation(DATA_STORAGE).createFile(fileName, content); return; } - - re = - regexParts.length === 1 ? regexParts[0] : `(?:${regexParts.join("|")})`; - this.extRe = new RegExp(re, "i"); + await fs.writeFile(content); + } catch (error) { + window.log?.("error", "Reset Keybinding failed!"); + window.log?.("error", error); } +} - supportsFile(filename: string): boolean { - if (this.extRe?.test(filename)) return true; +export { commandKeymapCompartment }; - return this.filenameMatchers.some((matcher) => { - matcher.lastIndex = 0; - return matcher.test(filename); - }); +export function registerExternalCommand(descriptor = {}) { + const normalized = normalizeExternalCommand(descriptor); + if (!normalized) return null; + + const { name } = normalized; + if (commandMap.has(name)) { + commandMap.delete(name); + } + + addCommand(normalized); + const stored = commandMap.get(name); + if (stored) { + stored.key = normalized.key ?? stored.key; } - /** - * Get the CodeMirror language extension - */ - getExtension(): LanguageExtensionProvider | null { - return this.languageExtension; + rebuildKeymap(); + return stored; +} + +export function removeExternalCommand(name) { + if (!name) return false; + const exists = commandMap.has(name); + if (!exists) return false; + commandMap.delete(name); + rebuildKeymap(); + return true; +} + +export function refreshCommandKeymap(view) { + const resolvedView = resolveView(view); + applyCommandKeymap(resolvedView); +} + +function normalizeExternalCommand(descriptor) { + const name = + typeof descriptor?.name === "string" ? descriptor.name.trim() : ""; + if (!name) { + console.warn("Command registration skipped: missing name", descriptor); + return null; + } + const exec = typeof descriptor?.exec === "function" ? descriptor.exec : null; + if (!exec) { + console.warn( + `Command registration skipped for "${name}": exec must be a function.`, + ); + return null; } - /** - * Check if the language extension is available (loaded) - */ - isAvailable(): boolean { - return this.languageExtension !== null; + const requiresView = descriptor?.requiresView ?? true; + const key = normalizeExternalKey(descriptor?.bindKey); + + return { + name, + description: descriptor?.description || humanizeCommandName(name), + readOnly: descriptor?.readOnly ?? true, + requiresView, + key, + run(view, args) { + try { + const resolvedView = resolveView(view); + if (requiresView && !resolvedView) return false; + const result = exec(resolvedView || null, args); + return result !== false; + } catch (error) { + console.error(`Command \"${name}\" failed`, error); + return false; + } + }, + }; +} + +function normalizeExternalKey(bindKey) { + if (!bindKey) return null; + if (typeof bindKey === "string") return bindKey; + const combos = []; + if (typeof bindKey === "object") { + const pushCombo = (combo) => { + if (typeof combo === "string" && combo.trim()) combos.push(combo.trim()); + }; + pushCombo(bindKey.win); + pushCombo(bindKey.linux); + pushCombo(bindKey.mac); } + return combos.length ? combos.join("|") : null; +} + +function applyCommandKeymap(view, bindings = cachedKeymap) { + if (!view) return; + commandViews.add(view); + view.dispatch({ + effects: commandKeymapCompartment.reconfigure( + keymap.of(bindings ?? cachedKeymap), + ), + }); } From 253cfb848738901a93f580c31b445e72e496a362 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:02:56 +0100 Subject: [PATCH 30/36] Update fonts.js --- src/lib/fonts.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/fonts.js b/src/lib/fonts.js index 82fe22fed9..7d505ed4f7 100644 --- a/src/lib/fonts.js +++ b/src/lib/fonts.js @@ -280,7 +280,7 @@ async function loadFont(name) { } // Get all URL font references - const urls = [...css.matchAll(/\burl\(([^)]*)\)/g)].map((match) => match[1]); + const urls = [...css.matchAll(/\burl\((.*?)\)/g)].map((match) => match[1]); // Download and replace URLs for (const url of urls) { From 19ee17e23531729541424b4aafb6885d79420e82 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:14:21 +0100 Subject: [PATCH 31/36] fix lint --- src/sidebarApps/searchInFiles/worker.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/sidebarApps/searchInFiles/worker.js b/src/sidebarApps/searchInFiles/worker.js index 0e2740cd56..063451c84c 100644 --- a/src/sidebarApps/searchInFiles/worker.js +++ b/src/sidebarApps/searchInFiles/worker.js @@ -203,7 +203,10 @@ function getSurrounding(content, word, start, end) { if (left > 0 && !/[\r\n]/.test(content[left - 1])) line = `...${line}`; if (right < content.length && !/[\r\n]/.test(content[right])) line += "..."; return [line, word.slice(0, max)].map((text) => - text.replaceAll("\r\n", " ⏎ ").replaceAll("\n", " ⏎ ").replaceAll("\r", " ⏎ "), + text + .replaceAll("\r\n",·"·⏎·") + .replaceAll("\n",·"·⏎·") + .replaceAll("\r",·"·⏎·"), ); } From 69117f5ed95ba5e645f3a7b7b57e6a463a4f2b7a Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:17:18 +0100 Subject: [PATCH 32/36] Update fonts.js --- src/lib/fonts.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/fonts.js b/src/lib/fonts.js index 7d505ed4f7..af2aec1ad1 100644 --- a/src/lib/fonts.js +++ b/src/lib/fonts.js @@ -280,7 +280,7 @@ async function loadFont(name) { } // Get all URL font references - const urls = [...css.matchAll(/\burl\((.*?)\)/g)].map((match) => match[1]); + const urls = [...css.matchAll(/url\((.*?)\)/g)].map((match) => match[1]); // Download and replace URLs for (const url of urls) { From 9733d6a52157826651d90054468cfeed5cbf9106 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:25:15 +0100 Subject: [PATCH 33/36] fix lint --- src/pages/customTheme/customTheme.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/pages/customTheme/customTheme.js b/src/pages/customTheme/customTheme.js index c0f2440b18..286f2c7170 100644 --- a/src/pages/customTheme/customTheme.js +++ b/src/pages/customTheme/customTheme.js @@ -81,8 +81,7 @@ export default function CustomThemeInclude() { } function render() { - const pascalToNormal = (str) => - str.replace(/[A-Z]/g, " $&").toLowerCase(); + const·pascalToNormal·=·(str)·=>·str.replace(/[A-Z]/g,·"·$&").toLowerCase(); const customTheme = themes.get("custom"); $page.body = ( From 99bdf6c0e1c92e7d1fd1c20310de3d4a02254b28 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:29:05 +0100 Subject: [PATCH 34/36] final lint fix --- src/sidebarApps/searchInFiles/worker.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/sidebarApps/searchInFiles/worker.js b/src/sidebarApps/searchInFiles/worker.js index 063451c84c..41f4104e00 100644 --- a/src/sidebarApps/searchInFiles/worker.js +++ b/src/sidebarApps/searchInFiles/worker.js @@ -204,9 +204,9 @@ function getSurrounding(content, word, start, end) { if (right < content.length && !/[\r\n]/.test(content[right])) line += "..."; return [line, word.slice(0, max)].map((text) => text - .replaceAll("\r\n",·"·⏎·") - .replaceAll("\n",·"·⏎·") - .replaceAll("\r",·"·⏎·"), + .replaceAll("\r\n", " ⏎ ") + .replaceAll("\n", " ⏎ ") + .replaceAll("\r", " ⏎ "), ); } From bd6d943a66802bf1bd16800d41841d509018f7eb Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:32:01 +0100 Subject: [PATCH 35/36] true final lint fix --- src/pages/customTheme/customTheme.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/customTheme/customTheme.js b/src/pages/customTheme/customTheme.js index 286f2c7170..f8e024a29c 100644 --- a/src/pages/customTheme/customTheme.js +++ b/src/pages/customTheme/customTheme.js @@ -81,7 +81,7 @@ export default function CustomThemeInclude() { } function render() { - const·pascalToNormal·=·(str)·=>·str.replace(/[A-Z]/g,·"·$&").toLowerCase(); + const pascalToNormal = (str) => str.replace(/[A-Z]/g, " $&").toLowerCase(); const customTheme = themes.get("custom"); $page.body = ( From f934baec35d41e62f11425bc60e6f3f605ca89e2 Mon Sep 17 00:00:00 2001 From: Palloxin <75091899+Palloxin@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:02:24 +0100 Subject: [PATCH 36/36] tiny fix --- src/lib/console.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/console.js b/src/lib/console.js index 402d61b529..d6ab251a90 100644 --- a/src/lib/console.js +++ b/src/lib/console.js @@ -625,7 +625,7 @@ import ConsoleExecutor, { } catch (error) { return data .toString() - .replace(/{.*}/, "{...}") + .replace(/\{.*\}/, "{...}") .replace(/^function\s+[\w_$\d]+\s*/, "") .replace(/\s+/g, ""); }