define("vs/editor.api-BhD7pWdi", ["exports"], (function(exports) { "use strict"; var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$2, _aa, _ba, _ca, _da, _ea, _fa, _ga, _ha, _ia, _ja, _ka, _la, _ma, _na, _oa, _pa, _qa, _ra, _sa, _ta, _ua, _va, _wa, _xa, _ya, _za, _Aa, _Ba, _Ca, _Da, _Ea, _Fa, _Ga, _Ha, _Ia, _Ja, _Ka, _La, _Ma, _Na, _Oa, _Pa, _Qa, _Ra, _Sa; function getNLSMessages() { return globalThis._VSCODE_NLS_MESSAGES; } function getNLSLanguage() { return globalThis._VSCODE_NLS_LANGUAGE; } const isPseudo = getNLSLanguage() === "pseudo" || typeof document !== "undefined" && document.location && typeof document.location.hash === "string" && document.location.hash.indexOf("pseudo=true") >= 0; function _format$1(message, args) { let result; if (args.length === 0) { result = message; } else { result = message.replace(/\{(\d+)\}/g, (match2, rest) => { const index = rest[0]; const arg = args[index]; let result2 = match2; if (typeof arg === "string") { result2 = arg; } else if (typeof arg === "number" || typeof arg === "boolean" || arg === void 0 || arg === null) { result2 = String(arg); } return result2; }); } if (isPseudo) { result = "[" + result.replace(/[aouei]/g, "$&$&") + "]"; } return result; } function localize(data, message, ...args) { if (typeof data === "number") { return _format$1(lookupMessage(data, message), args); } return _format$1(message, args); } function lookupMessage(index, fallback2) { const message = getNLSMessages()?.[index]; if (typeof message !== "string") { if (typeof fallback2 === "string") { return fallback2; } throw new Error(`!!! NLS MISSING: ${index} !!!`); } return message; } function localize2(data, originalMessage, ...args) { let message; if (typeof data === "number") { message = lookupMessage(data, originalMessage); } else { message = originalMessage; } const value = _format$1(message, args); return { value, original: originalMessage === message ? value : _format$1(originalMessage, args) }; } function ensureCodeWindow(targetWindow, fallbackWindowId) { const codeWindow = targetWindow; if (typeof codeWindow.vscodeWindowId !== "number") { Object.defineProperty(codeWindow, "vscodeWindowId", { get: () => fallbackWindowId }); } } const mainWindow = window; const _WindowManager = class _WindowManager { constructor() { this.mapWindowIdToZoomFactor = /* @__PURE__ */ new Map(); } getZoomFactor(targetWindow) { return this.mapWindowIdToZoomFactor.get(this.getWindowId(targetWindow)) ?? 1; } getWindowId(targetWindow) { return targetWindow.vscodeWindowId; } }; _WindowManager.INSTANCE = new _WindowManager(); let WindowManager = _WindowManager; function addMatchMediaChangeListener(targetWindow, query, callback) { if (typeof query === "string") { query = targetWindow.matchMedia(query); } query.addEventListener("change", callback); } function getZoomFactor(targetWindow) { return WindowManager.INSTANCE.getZoomFactor(targetWindow); } const userAgent$1 = navigator.userAgent; const isFirefox$1 = userAgent$1.indexOf("Firefox") >= 0; const isWebKit = userAgent$1.indexOf("AppleWebKit") >= 0; const isChrome$1 = userAgent$1.indexOf("Chrome") >= 0; const isSafari$1 = !isChrome$1 && userAgent$1.indexOf("Safari") >= 0; const isWebkitWebView = !isChrome$1 && !isSafari$1 && isWebKit; userAgent$1.indexOf("Electron/") >= 0; const isAndroid$1 = userAgent$1.indexOf("Android") >= 0; let standalone = false; if (typeof mainWindow.matchMedia === "function") { const standaloneMatchMedia = mainWindow.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"); const fullScreenMatchMedia = mainWindow.matchMedia("(display-mode: fullscreen)"); standalone = standaloneMatchMedia.matches; addMatchMediaChangeListener(mainWindow, standaloneMatchMedia, ({ matches }) => { if (standalone && fullScreenMatchMedia.matches) { return; } standalone = matches; }); } class ErrorHandler { constructor() { this.listeners = []; this.unexpectedErrorHandler = function(e) { setTimeout(() => { if (e.stack) { if (ErrorNoTelemetry.isErrorNoTelemetry(e)) { throw new ErrorNoTelemetry(e.message + "\n\n" + e.stack); } throw new Error(e.message + "\n\n" + e.stack); } throw e; }, 0); }; } emit(e) { this.listeners.forEach((listener) => { listener(e); }); } onUnexpectedError(e) { this.unexpectedErrorHandler(e); this.emit(e); } // For external errors, we don't want the listeners to be called onUnexpectedExternalError(e) { this.unexpectedErrorHandler(e); } } const errorHandler = new ErrorHandler(); function onBugIndicatingError(e) { errorHandler.onUnexpectedError(e); return void 0; } function onUnexpectedError(e) { if (!isCancellationError(e)) { errorHandler.onUnexpectedError(e); } return void 0; } function onUnexpectedExternalError(e) { if (!isCancellationError(e)) { errorHandler.onUnexpectedExternalError(e); } return void 0; } function transformErrorForSerialization(error) { if (error instanceof Error) { const { name, message, cause } = error; const stack = error.stacktrace || error.stack; return { $isError: true, name, message, stack, noTelemetry: ErrorNoTelemetry.isErrorNoTelemetry(error), cause: cause ? transformErrorForSerialization(cause) : void 0, code: error.code }; } return error; } const canceledName = "Canceled"; function isCancellationError(error) { if (error instanceof CancellationError) { return true; } return error instanceof Error && error.name === canceledName && error.message === canceledName; } class CancellationError extends Error { constructor() { super(canceledName); this.name = this.message; } } function canceled() { const error = new Error(canceledName); error.name = error.message; return error; } function illegalArgument(name) { if (name) { return new Error(`Illegal argument: ${name}`); } else { return new Error("Illegal argument"); } } function illegalState(name) { if (name) { return new Error(`Illegal state: ${name}`); } else { return new Error("Illegal state"); } } class NotSupportedError extends Error { constructor(message) { super("NotSupported"); if (message) { this.message = message; } } } class ErrorNoTelemetry extends Error { constructor(msg) { super(msg); this.name = "CodeExpectedError"; } static fromError(err) { if (err instanceof ErrorNoTelemetry) { return err; } const result = new ErrorNoTelemetry(); result.message = err.message; result.stack = err.stack; return result; } static isErrorNoTelemetry(err) { return err.name === "CodeExpectedError"; } } class BugIndicatingError extends Error { constructor(message) { super(message || "An unexpected bug occurred."); Object.setPrototypeOf(this, BugIndicatingError.prototype); } } function ok(value, message) { if (!value) { throw new Error(message ? `Assertion failed (${message})` : "Assertion Failed"); } } function assertNever(value, message = "Unreachable") { throw new Error(message); } function assert(condition, messageOrError = "unexpected state") { if (!condition) { const errorToThrow = typeof messageOrError === "string" ? new BugIndicatingError(`Assertion Failed: ${messageOrError}`) : messageOrError; throw errorToThrow; } } function softAssert(condition, message = "Soft Assertion Failed") { if (!condition) { onUnexpectedError(new BugIndicatingError(message)); } } function assertFn(condition) { if (!condition()) { debugger; condition(); onUnexpectedError(new BugIndicatingError("Assertion Failed")); } } function checkAdjacentItems(items, predicate) { let i2 = 0; while (i2 < items.length - 1) { const a = items[i2]; const b = items[i2 + 1]; if (!predicate(a, b)) { return false; } i2++; } return true; } function isString$1(str) { return typeof str === "string"; } function isObject(obj) { return typeof obj === "object" && obj !== null && !Array.isArray(obj) && !(obj instanceof RegExp) && !(obj instanceof Date); } function isTypedArray(obj) { const TypedArray = Object.getPrototypeOf(Uint8Array); return typeof obj === "object" && obj instanceof TypedArray; } function isNumber$1(obj) { return typeof obj === "number" && !isNaN(obj); } function isIterable(obj) { return !!obj && typeof obj[Symbol.iterator] === "function"; } function isBoolean(obj) { return obj === true || obj === false; } function isUndefined(obj) { return typeof obj === "undefined"; } function isDefined(arg) { return !isUndefinedOrNull(arg); } function isUndefinedOrNull(obj) { return isUndefined(obj) || obj === null; } function assertType(condition, type) { if (!condition) { throw new Error(type ? `Unexpected type, expected '${type}'` : "Unexpected type"); } } function assertReturnsDefined(arg) { assert(arg !== null && arg !== void 0, "Argument is `undefined` or `null`."); return arg; } function isFunction(obj) { return typeof obj === "function"; } function validateConstraints(args, constraints) { const len = Math.min(args.length, constraints.length); for (let i2 = 0; i2 < len; i2++) { validateConstraint(args[i2], constraints[i2]); } } function validateConstraint(arg, constraint) { if (isString$1(constraint)) { if (typeof arg !== constraint) { throw new Error(`argument does not match constraint: typeof ${constraint}`); } } else if (isFunction(constraint)) { try { if (arg instanceof constraint) { return; } } catch { } if (!isUndefinedOrNull(arg) && arg.constructor === constraint) { return; } if (constraint.length === 1 && constraint.call(void 0, arg) === true) { return; } throw new Error(`argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true`); } } function upcast(x) { return x; } const LANGUAGE_DEFAULT = "en"; let _isWindows = false; let _isMacintosh = false; let _isLinux = false; let _isNative = false; let _isWeb = false; let _isIOS = false; let _isMobile = false; let _locale = void 0; let _language = LANGUAGE_DEFAULT; let _platformLocale = LANGUAGE_DEFAULT; let _translationsConfigFile = void 0; let _userAgent = void 0; const $globalThis = globalThis; let nodeProcess = void 0; if (typeof $globalThis.vscode !== "undefined" && typeof $globalThis.vscode.process !== "undefined") { nodeProcess = $globalThis.vscode.process; } else if (typeof process !== "undefined" && typeof process?.versions?.node === "string") { nodeProcess = process; } const isElectronProcess = typeof nodeProcess?.versions?.electron === "string"; const isElectronRenderer = isElectronProcess && nodeProcess?.type === "renderer"; if (typeof nodeProcess === "object") { _isWindows = nodeProcess.platform === "win32"; _isMacintosh = nodeProcess.platform === "darwin"; _isLinux = nodeProcess.platform === "linux"; _isLinux && !!nodeProcess.env["SNAP"] && !!nodeProcess.env["SNAP_REVISION"]; !!nodeProcess.env["CI"] || !!nodeProcess.env["BUILD_ARTIFACTSTAGINGDIRECTORY"] || !!nodeProcess.env["GITHUB_WORKSPACE"]; _locale = LANGUAGE_DEFAULT; _language = LANGUAGE_DEFAULT; const rawNlsConfig = nodeProcess.env["VSCODE_NLS_CONFIG"]; if (rawNlsConfig) { try { const nlsConfig = JSON.parse(rawNlsConfig); _locale = nlsConfig.userLocale; _platformLocale = nlsConfig.osLocale; _language = nlsConfig.resolvedLanguage || LANGUAGE_DEFAULT; _translationsConfigFile = nlsConfig.languagePack?.translationsConfigFile; } catch (e) { } } _isNative = true; } else if (typeof navigator === "object" && !isElectronRenderer) { _userAgent = navigator.userAgent; _isWindows = _userAgent.indexOf("Windows") >= 0; _isMacintosh = _userAgent.indexOf("Macintosh") >= 0; _isIOS = (_userAgent.indexOf("Macintosh") >= 0 || _userAgent.indexOf("iPad") >= 0 || _userAgent.indexOf("iPhone") >= 0) && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0; _isLinux = _userAgent.indexOf("Linux") >= 0; _isMobile = _userAgent?.indexOf("Mobi") >= 0; _isWeb = true; _language = getNLSLanguage() || LANGUAGE_DEFAULT; _locale = navigator.language.toLowerCase(); _platformLocale = _locale; } else { console.error("Unable to resolve platform."); } let _platform = 0; if (_isMacintosh) { _platform = 1; } else if (_isWindows) { _platform = 3; } else if (_isLinux) { _platform = 2; } const isWindows = _isWindows; const isMacintosh = _isMacintosh; const isLinux = _isLinux; const isNative = _isNative; const isWeb = _isWeb; const isWebWorker = _isWeb && typeof $globalThis.importScripts === "function"; const webWorkerOrigin = isWebWorker ? $globalThis.origin : void 0; const isIOS = _isIOS; const isMobile = _isMobile; const platform$1 = _platform; const userAgent = _userAgent; const language = _language; const setTimeout0IsFaster = typeof $globalThis.postMessage === "function" && !$globalThis.importScripts; const setTimeout0 = (() => { if (setTimeout0IsFaster) { const pending = []; $globalThis.addEventListener("message", (e) => { if (e.data && e.data.vscodeScheduleAsyncWork) { for (let i2 = 0, len = pending.length; i2 < len; i2++) { const candidate = pending[i2]; if (candidate.id === e.data.vscodeScheduleAsyncWork) { pending.splice(i2, 1); candidate.callback(); return; } } } }); let lastId = 0; return (callback) => { const myId = ++lastId; pending.push({ id: myId, callback }); $globalThis.postMessage({ vscodeScheduleAsyncWork: myId }, "*"); }; } return (callback) => setTimeout(callback); })(); const OS = _isMacintosh || _isIOS ? 2 : _isWindows ? 1 : 3; let _isLittleEndian = true; let _isLittleEndianComputed = false; function isLittleEndian() { if (!_isLittleEndianComputed) { _isLittleEndianComputed = true; const test = new Uint8Array(2); test[0] = 1; test[1] = 2; const view = new Uint16Array(test.buffer); _isLittleEndian = view[0] === (2 << 8) + 1; } return _isLittleEndian; } const isChrome = !!(userAgent && userAgent.indexOf("Chrome") >= 0); const isFirefox = !!(userAgent && userAgent.indexOf("Firefox") >= 0); const isSafari = !!(!isChrome && (userAgent && userAgent.indexOf("Safari") >= 0)); const isEdge = !!(userAgent && userAgent.indexOf("Edg/") >= 0); const isAndroid = !!(userAgent && userAgent.indexOf("Android") >= 0); const BrowserFeatures = { clipboard: { writeText: isNative || document.queryCommandSupported && document.queryCommandSupported("copy") || !!(navigator && navigator.clipboard && navigator.clipboard.writeText), readText: isNative || !!(navigator && navigator.clipboard && navigator.clipboard.readText) }, pointerEvents: mainWindow.PointerEvent && ("ontouchstart" in mainWindow || navigator.maxTouchPoints > 0) }; class KeyCodeStrMap { constructor() { this._keyCodeToStr = []; this._strToKeyCode = /* @__PURE__ */ Object.create(null); } define(keyCode, str) { this._keyCodeToStr[keyCode] = str; this._strToKeyCode[str.toLowerCase()] = keyCode; } keyCodeToStr(keyCode) { return this._keyCodeToStr[keyCode]; } strToKeyCode(str) { return this._strToKeyCode[str.toLowerCase()] || 0; } } const uiMap = new KeyCodeStrMap(); const userSettingsUSMap = new KeyCodeStrMap(); const userSettingsGeneralMap = new KeyCodeStrMap(); const EVENT_KEY_CODE_MAP = new Array(230); const scanCodeStrToInt = /* @__PURE__ */ Object.create(null); const scanCodeLowerCaseStrToInt = /* @__PURE__ */ Object.create(null); const IMMUTABLE_CODE_TO_KEY_CODE = []; for (let i2 = 0; i2 <= 193; i2++) { IMMUTABLE_CODE_TO_KEY_CODE[i2] = -1; } (function() { const empty2 = ""; const mappings = [ // immutable, scanCode, scanCodeStr, keyCode, keyCodeStr, eventKeyCode, vkey, usUserSettingsLabel, generalUserSettingsLabel [1, 0, "None", 0, "unknown", 0, "VK_UNKNOWN", empty2, empty2], [1, 1, "Hyper", 0, empty2, 0, empty2, empty2, empty2], [1, 2, "Super", 0, empty2, 0, empty2, empty2, empty2], [1, 3, "Fn", 0, empty2, 0, empty2, empty2, empty2], [1, 4, "FnLock", 0, empty2, 0, empty2, empty2, empty2], [1, 5, "Suspend", 0, empty2, 0, empty2, empty2, empty2], [1, 6, "Resume", 0, empty2, 0, empty2, empty2, empty2], [1, 7, "Turbo", 0, empty2, 0, empty2, empty2, empty2], [1, 8, "Sleep", 0, empty2, 0, "VK_SLEEP", empty2, empty2], [1, 9, "WakeUp", 0, empty2, 0, empty2, empty2, empty2], [0, 10, "KeyA", 31, "A", 65, "VK_A", empty2, empty2], [0, 11, "KeyB", 32, "B", 66, "VK_B", empty2, empty2], [0, 12, "KeyC", 33, "C", 67, "VK_C", empty2, empty2], [0, 13, "KeyD", 34, "D", 68, "VK_D", empty2, empty2], [0, 14, "KeyE", 35, "E", 69, "VK_E", empty2, empty2], [0, 15, "KeyF", 36, "F", 70, "VK_F", empty2, empty2], [0, 16, "KeyG", 37, "G", 71, "VK_G", empty2, empty2], [0, 17, "KeyH", 38, "H", 72, "VK_H", empty2, empty2], [0, 18, "KeyI", 39, "I", 73, "VK_I", empty2, empty2], [0, 19, "KeyJ", 40, "J", 74, "VK_J", empty2, empty2], [0, 20, "KeyK", 41, "K", 75, "VK_K", empty2, empty2], [0, 21, "KeyL", 42, "L", 76, "VK_L", empty2, empty2], [0, 22, "KeyM", 43, "M", 77, "VK_M", empty2, empty2], [0, 23, "KeyN", 44, "N", 78, "VK_N", empty2, empty2], [0, 24, "KeyO", 45, "O", 79, "VK_O", empty2, empty2], [0, 25, "KeyP", 46, "P", 80, "VK_P", empty2, empty2], [0, 26, "KeyQ", 47, "Q", 81, "VK_Q", empty2, empty2], [0, 27, "KeyR", 48, "R", 82, "VK_R", empty2, empty2], [0, 28, "KeyS", 49, "S", 83, "VK_S", empty2, empty2], [0, 29, "KeyT", 50, "T", 84, "VK_T", empty2, empty2], [0, 30, "KeyU", 51, "U", 85, "VK_U", empty2, empty2], [0, 31, "KeyV", 52, "V", 86, "VK_V", empty2, empty2], [0, 32, "KeyW", 53, "W", 87, "VK_W", empty2, empty2], [0, 33, "KeyX", 54, "X", 88, "VK_X", empty2, empty2], [0, 34, "KeyY", 55, "Y", 89, "VK_Y", empty2, empty2], [0, 35, "KeyZ", 56, "Z", 90, "VK_Z", empty2, empty2], [0, 36, "Digit1", 22, "1", 49, "VK_1", empty2, empty2], [0, 37, "Digit2", 23, "2", 50, "VK_2", empty2, empty2], [0, 38, "Digit3", 24, "3", 51, "VK_3", empty2, empty2], [0, 39, "Digit4", 25, "4", 52, "VK_4", empty2, empty2], [0, 40, "Digit5", 26, "5", 53, "VK_5", empty2, empty2], [0, 41, "Digit6", 27, "6", 54, "VK_6", empty2, empty2], [0, 42, "Digit7", 28, "7", 55, "VK_7", empty2, empty2], [0, 43, "Digit8", 29, "8", 56, "VK_8", empty2, empty2], [0, 44, "Digit9", 30, "9", 57, "VK_9", empty2, empty2], [0, 45, "Digit0", 21, "0", 48, "VK_0", empty2, empty2], [1, 46, "Enter", 3, "Enter", 13, "VK_RETURN", empty2, empty2], [1, 47, "Escape", 9, "Escape", 27, "VK_ESCAPE", empty2, empty2], [1, 48, "Backspace", 1, "Backspace", 8, "VK_BACK", empty2, empty2], [1, 49, "Tab", 2, "Tab", 9, "VK_TAB", empty2, empty2], [1, 50, "Space", 10, "Space", 32, "VK_SPACE", empty2, empty2], [0, 51, "Minus", 88, "-", 189, "VK_OEM_MINUS", "-", "OEM_MINUS"], [0, 52, "Equal", 86, "=", 187, "VK_OEM_PLUS", "=", "OEM_PLUS"], [0, 53, "BracketLeft", 92, "[", 219, "VK_OEM_4", "[", "OEM_4"], [0, 54, "BracketRight", 94, "]", 221, "VK_OEM_6", "]", "OEM_6"], [0, 55, "Backslash", 93, "\\", 220, "VK_OEM_5", "\\", "OEM_5"], [0, 56, "IntlHash", 0, empty2, 0, empty2, empty2, empty2], // has been dropped from the w3c spec [0, 57, "Semicolon", 85, ";", 186, "VK_OEM_1", ";", "OEM_1"], [0, 58, "Quote", 95, "'", 222, "VK_OEM_7", "'", "OEM_7"], [0, 59, "Backquote", 91, "`", 192, "VK_OEM_3", "`", "OEM_3"], [0, 60, "Comma", 87, ",", 188, "VK_OEM_COMMA", ",", "OEM_COMMA"], [0, 61, "Period", 89, ".", 190, "VK_OEM_PERIOD", ".", "OEM_PERIOD"], [0, 62, "Slash", 90, "/", 191, "VK_OEM_2", "/", "OEM_2"], [1, 63, "CapsLock", 8, "CapsLock", 20, "VK_CAPITAL", empty2, empty2], [1, 64, "F1", 59, "F1", 112, "VK_F1", empty2, empty2], [1, 65, "F2", 60, "F2", 113, "VK_F2", empty2, empty2], [1, 66, "F3", 61, "F3", 114, "VK_F3", empty2, empty2], [1, 67, "F4", 62, "F4", 115, "VK_F4", empty2, empty2], [1, 68, "F5", 63, "F5", 116, "VK_F5", empty2, empty2], [1, 69, "F6", 64, "F6", 117, "VK_F6", empty2, empty2], [1, 70, "F7", 65, "F7", 118, "VK_F7", empty2, empty2], [1, 71, "F8", 66, "F8", 119, "VK_F8", empty2, empty2], [1, 72, "F9", 67, "F9", 120, "VK_F9", empty2, empty2], [1, 73, "F10", 68, "F10", 121, "VK_F10", empty2, empty2], [1, 74, "F11", 69, "F11", 122, "VK_F11", empty2, empty2], [1, 75, "F12", 70, "F12", 123, "VK_F12", empty2, empty2], [1, 76, "PrintScreen", 0, empty2, 0, empty2, empty2, empty2], [1, 77, "ScrollLock", 84, "ScrollLock", 145, "VK_SCROLL", empty2, empty2], [1, 78, "Pause", 7, "PauseBreak", 19, "VK_PAUSE", empty2, empty2], [1, 79, "Insert", 19, "Insert", 45, "VK_INSERT", empty2, empty2], [1, 80, "Home", 14, "Home", 36, "VK_HOME", empty2, empty2], [1, 81, "PageUp", 11, "PageUp", 33, "VK_PRIOR", empty2, empty2], [1, 82, "Delete", 20, "Delete", 46, "VK_DELETE", empty2, empty2], [1, 83, "End", 13, "End", 35, "VK_END", empty2, empty2], [1, 84, "PageDown", 12, "PageDown", 34, "VK_NEXT", empty2, empty2], [1, 85, "ArrowRight", 17, "RightArrow", 39, "VK_RIGHT", "Right", empty2], [1, 86, "ArrowLeft", 15, "LeftArrow", 37, "VK_LEFT", "Left", empty2], [1, 87, "ArrowDown", 18, "DownArrow", 40, "VK_DOWN", "Down", empty2], [1, 88, "ArrowUp", 16, "UpArrow", 38, "VK_UP", "Up", empty2], [1, 89, "NumLock", 83, "NumLock", 144, "VK_NUMLOCK", empty2, empty2], [1, 90, "NumpadDivide", 113, "NumPad_Divide", 111, "VK_DIVIDE", empty2, empty2], [1, 91, "NumpadMultiply", 108, "NumPad_Multiply", 106, "VK_MULTIPLY", empty2, empty2], [1, 92, "NumpadSubtract", 111, "NumPad_Subtract", 109, "VK_SUBTRACT", empty2, empty2], [1, 93, "NumpadAdd", 109, "NumPad_Add", 107, "VK_ADD", empty2, empty2], [1, 94, "NumpadEnter", 3, empty2, 0, empty2, empty2, empty2], [1, 95, "Numpad1", 99, "NumPad1", 97, "VK_NUMPAD1", empty2, empty2], [1, 96, "Numpad2", 100, "NumPad2", 98, "VK_NUMPAD2", empty2, empty2], [1, 97, "Numpad3", 101, "NumPad3", 99, "VK_NUMPAD3", empty2, empty2], [1, 98, "Numpad4", 102, "NumPad4", 100, "VK_NUMPAD4", empty2, empty2], [1, 99, "Numpad5", 103, "NumPad5", 101, "VK_NUMPAD5", empty2, empty2], [1, 100, "Numpad6", 104, "NumPad6", 102, "VK_NUMPAD6", empty2, empty2], [1, 101, "Numpad7", 105, "NumPad7", 103, "VK_NUMPAD7", empty2, empty2], [1, 102, "Numpad8", 106, "NumPad8", 104, "VK_NUMPAD8", empty2, empty2], [1, 103, "Numpad9", 107, "NumPad9", 105, "VK_NUMPAD9", empty2, empty2], [1, 104, "Numpad0", 98, "NumPad0", 96, "VK_NUMPAD0", empty2, empty2], [1, 105, "NumpadDecimal", 112, "NumPad_Decimal", 110, "VK_DECIMAL", empty2, empty2], [0, 106, "IntlBackslash", 97, "OEM_102", 226, "VK_OEM_102", empty2, empty2], [1, 107, "ContextMenu", 58, "ContextMenu", 93, empty2, empty2, empty2], [1, 108, "Power", 0, empty2, 0, empty2, empty2, empty2], [1, 109, "NumpadEqual", 0, empty2, 0, empty2, empty2, empty2], [1, 110, "F13", 71, "F13", 124, "VK_F13", empty2, empty2], [1, 111, "F14", 72, "F14", 125, "VK_F14", empty2, empty2], [1, 112, "F15", 73, "F15", 126, "VK_F15", empty2, empty2], [1, 113, "F16", 74, "F16", 127, "VK_F16", empty2, empty2], [1, 114, "F17", 75, "F17", 128, "VK_F17", empty2, empty2], [1, 115, "F18", 76, "F18", 129, "VK_F18", empty2, empty2], [1, 116, "F19", 77, "F19", 130, "VK_F19", empty2, empty2], [1, 117, "F20", 78, "F20", 131, "VK_F20", empty2, empty2], [1, 118, "F21", 79, "F21", 132, "VK_F21", empty2, empty2], [1, 119, "F22", 80, "F22", 133, "VK_F22", empty2, empty2], [1, 120, "F23", 81, "F23", 134, "VK_F23", empty2, empty2], [1, 121, "F24", 82, "F24", 135, "VK_F24", empty2, empty2], [1, 122, "Open", 0, empty2, 0, empty2, empty2, empty2], [1, 123, "Help", 0, empty2, 0, empty2, empty2, empty2], [1, 124, "Select", 0, empty2, 0, empty2, empty2, empty2], [1, 125, "Again", 0, empty2, 0, empty2, empty2, empty2], [1, 126, "Undo", 0, empty2, 0, empty2, empty2, empty2], [1, 127, "Cut", 0, empty2, 0, empty2, empty2, empty2], [1, 128, "Copy", 0, empty2, 0, empty2, empty2, empty2], [1, 129, "Paste", 0, empty2, 0, empty2, empty2, empty2], [1, 130, "Find", 0, empty2, 0, empty2, empty2, empty2], [1, 131, "AudioVolumeMute", 117, "AudioVolumeMute", 173, "VK_VOLUME_MUTE", empty2, empty2], [1, 132, "AudioVolumeUp", 118, "AudioVolumeUp", 175, "VK_VOLUME_UP", empty2, empty2], [1, 133, "AudioVolumeDown", 119, "AudioVolumeDown", 174, "VK_VOLUME_DOWN", empty2, empty2], [1, 134, "NumpadComma", 110, "NumPad_Separator", 108, "VK_SEPARATOR", empty2, empty2], [0, 135, "IntlRo", 115, "ABNT_C1", 193, "VK_ABNT_C1", empty2, empty2], [1, 136, "KanaMode", 0, empty2, 0, empty2, empty2, empty2], [0, 137, "IntlYen", 0, empty2, 0, empty2, empty2, empty2], [1, 138, "Convert", 0, empty2, 0, empty2, empty2, empty2], [1, 139, "NonConvert", 0, empty2, 0, empty2, empty2, empty2], [1, 140, "Lang1", 0, empty2, 0, empty2, empty2, empty2], [1, 141, "Lang2", 0, empty2, 0, empty2, empty2, empty2], [1, 142, "Lang3", 0, empty2, 0, empty2, empty2, empty2], [1, 143, "Lang4", 0, empty2, 0, empty2, empty2, empty2], [1, 144, "Lang5", 0, empty2, 0, empty2, empty2, empty2], [1, 145, "Abort", 0, empty2, 0, empty2, empty2, empty2], [1, 146, "Props", 0, empty2, 0, empty2, empty2, empty2], [1, 147, "NumpadParenLeft", 0, empty2, 0, empty2, empty2, empty2], [1, 148, "NumpadParenRight", 0, empty2, 0, empty2, empty2, empty2], [1, 149, "NumpadBackspace", 0, empty2, 0, empty2, empty2, empty2], [1, 150, "NumpadMemoryStore", 0, empty2, 0, empty2, empty2, empty2], [1, 151, "NumpadMemoryRecall", 0, empty2, 0, empty2, empty2, empty2], [1, 152, "NumpadMemoryClear", 0, empty2, 0, empty2, empty2, empty2], [1, 153, "NumpadMemoryAdd", 0, empty2, 0, empty2, empty2, empty2], [1, 154, "NumpadMemorySubtract", 0, empty2, 0, empty2, empty2, empty2], [1, 155, "NumpadClear", 131, "Clear", 12, "VK_CLEAR", empty2, empty2], [1, 156, "NumpadClearEntry", 0, empty2, 0, empty2, empty2, empty2], [1, 0, empty2, 5, "Ctrl", 17, "VK_CONTROL", empty2, empty2], [1, 0, empty2, 4, "Shift", 16, "VK_SHIFT", empty2, empty2], [1, 0, empty2, 6, "Alt", 18, "VK_MENU", empty2, empty2], [1, 0, empty2, 57, "Meta", 91, "VK_COMMAND", empty2, empty2], [1, 157, "ControlLeft", 5, empty2, 0, "VK_LCONTROL", empty2, empty2], [1, 158, "ShiftLeft", 4, empty2, 0, "VK_LSHIFT", empty2, empty2], [1, 159, "AltLeft", 6, empty2, 0, "VK_LMENU", empty2, empty2], [1, 160, "MetaLeft", 57, empty2, 0, "VK_LWIN", empty2, empty2], [1, 161, "ControlRight", 5, empty2, 0, "VK_RCONTROL", empty2, empty2], [1, 162, "ShiftRight", 4, empty2, 0, "VK_RSHIFT", empty2, empty2], [1, 163, "AltRight", 6, empty2, 0, "VK_RMENU", empty2, empty2], [1, 164, "MetaRight", 57, empty2, 0, "VK_RWIN", empty2, empty2], [1, 165, "BrightnessUp", 0, empty2, 0, empty2, empty2, empty2], [1, 166, "BrightnessDown", 0, empty2, 0, empty2, empty2, empty2], [1, 167, "MediaPlay", 0, empty2, 0, empty2, empty2, empty2], [1, 168, "MediaRecord", 0, empty2, 0, empty2, empty2, empty2], [1, 169, "MediaFastForward", 0, empty2, 0, empty2, empty2, empty2], [1, 170, "MediaRewind", 0, empty2, 0, empty2, empty2, empty2], [1, 171, "MediaTrackNext", 124, "MediaTrackNext", 176, "VK_MEDIA_NEXT_TRACK", empty2, empty2], [1, 172, "MediaTrackPrevious", 125, "MediaTrackPrevious", 177, "VK_MEDIA_PREV_TRACK", empty2, empty2], [1, 173, "MediaStop", 126, "MediaStop", 178, "VK_MEDIA_STOP", empty2, empty2], [1, 174, "Eject", 0, empty2, 0, empty2, empty2, empty2], [1, 175, "MediaPlayPause", 127, "MediaPlayPause", 179, "VK_MEDIA_PLAY_PAUSE", empty2, empty2], [1, 176, "MediaSelect", 128, "LaunchMediaPlayer", 181, "VK_MEDIA_LAUNCH_MEDIA_SELECT", empty2, empty2], [1, 177, "LaunchMail", 129, "LaunchMail", 180, "VK_MEDIA_LAUNCH_MAIL", empty2, empty2], [1, 178, "LaunchApp2", 130, "LaunchApp2", 183, "VK_MEDIA_LAUNCH_APP2", empty2, empty2], [1, 179, "LaunchApp1", 0, empty2, 0, "VK_MEDIA_LAUNCH_APP1", empty2, empty2], [1, 180, "SelectTask", 0, empty2, 0, empty2, empty2, empty2], [1, 181, "LaunchScreenSaver", 0, empty2, 0, empty2, empty2, empty2], [1, 182, "BrowserSearch", 120, "BrowserSearch", 170, "VK_BROWSER_SEARCH", empty2, empty2], [1, 183, "BrowserHome", 121, "BrowserHome", 172, "VK_BROWSER_HOME", empty2, empty2], [1, 184, "BrowserBack", 122, "BrowserBack", 166, "VK_BROWSER_BACK", empty2, empty2], [1, 185, "BrowserForward", 123, "BrowserForward", 167, "VK_BROWSER_FORWARD", empty2, empty2], [1, 186, "BrowserStop", 0, empty2, 0, "VK_BROWSER_STOP", empty2, empty2], [1, 187, "BrowserRefresh", 0, empty2, 0, "VK_BROWSER_REFRESH", empty2, empty2], [1, 188, "BrowserFavorites", 0, empty2, 0, "VK_BROWSER_FAVORITES", empty2, empty2], [1, 189, "ZoomToggle", 0, empty2, 0, empty2, empty2, empty2], [1, 190, "MailReply", 0, empty2, 0, empty2, empty2, empty2], [1, 191, "MailForward", 0, empty2, 0, empty2, empty2, empty2], [1, 192, "MailSend", 0, empty2, 0, empty2, empty2, empty2], // See https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html // If an Input Method Editor is processing key input and the event is keydown, return 229. [1, 0, empty2, 114, "KeyInComposition", 229, empty2, empty2, empty2], [1, 0, empty2, 116, "ABNT_C2", 194, "VK_ABNT_C2", empty2, empty2], [1, 0, empty2, 96, "OEM_8", 223, "VK_OEM_8", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_KANA", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_HANGUL", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_JUNJA", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_FINAL", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_HANJA", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_KANJI", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_CONVERT", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_NONCONVERT", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_ACCEPT", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_MODECHANGE", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_SELECT", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_PRINT", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_EXECUTE", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_SNAPSHOT", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_HELP", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_APPS", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_PROCESSKEY", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_PACKET", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_DBE_SBCSCHAR", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_DBE_DBCSCHAR", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_ATTN", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_CRSEL", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_EXSEL", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_EREOF", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_PLAY", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_ZOOM", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_NONAME", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_PA1", empty2, empty2], [1, 0, empty2, 0, empty2, 0, "VK_OEM_CLEAR", empty2, empty2] ]; const seenKeyCode = []; const seenScanCode = []; for (const mapping of mappings) { const [immutable, scanCode, scanCodeStr, keyCode, keyCodeStr, eventKeyCode, vkey, usUserSettingsLabel, generalUserSettingsLabel] = mapping; if (!seenScanCode[scanCode]) { seenScanCode[scanCode] = true; scanCodeStrToInt[scanCodeStr] = scanCode; scanCodeLowerCaseStrToInt[scanCodeStr.toLowerCase()] = scanCode; if (immutable) { IMMUTABLE_CODE_TO_KEY_CODE[scanCode] = keyCode; } } if (!seenKeyCode[keyCode]) { seenKeyCode[keyCode] = true; if (!keyCodeStr) { throw new Error(`String representation missing for key code ${keyCode} around scan code ${scanCodeStr}`); } uiMap.define(keyCode, keyCodeStr); userSettingsUSMap.define(keyCode, usUserSettingsLabel || keyCodeStr); userSettingsGeneralMap.define(keyCode, generalUserSettingsLabel || usUserSettingsLabel || keyCodeStr); } if (eventKeyCode) { EVENT_KEY_CODE_MAP[eventKeyCode] = keyCode; } } })(); var KeyCodeUtils; (function(KeyCodeUtils2) { function toString(keyCode) { return uiMap.keyCodeToStr(keyCode); } KeyCodeUtils2.toString = toString; function fromString(key) { return uiMap.strToKeyCode(key); } KeyCodeUtils2.fromString = fromString; function toUserSettingsUS(keyCode) { return userSettingsUSMap.keyCodeToStr(keyCode); } KeyCodeUtils2.toUserSettingsUS = toUserSettingsUS; function toUserSettingsGeneral(keyCode) { return userSettingsGeneralMap.keyCodeToStr(keyCode); } KeyCodeUtils2.toUserSettingsGeneral = toUserSettingsGeneral; function fromUserSettings(key) { return userSettingsUSMap.strToKeyCode(key) || userSettingsGeneralMap.strToKeyCode(key); } KeyCodeUtils2.fromUserSettings = fromUserSettings; function toElectronAccelerator(keyCode) { if (keyCode >= 98 && keyCode <= 113) { return null; } switch (keyCode) { case 16: return "Up"; case 18: return "Down"; case 15: return "Left"; case 17: return "Right"; } return uiMap.keyCodeToStr(keyCode); } KeyCodeUtils2.toElectronAccelerator = toElectronAccelerator; })(KeyCodeUtils || (KeyCodeUtils = {})); function KeyChord(firstPart, secondPart) { const chordPart = (secondPart & 65535) << 16 >>> 0; return (firstPart | chordPart) >>> 0; } function decodeKeybinding(keybinding, OS2) { if (typeof keybinding === "number") { if (keybinding === 0) { return null; } const firstChord = (keybinding & 65535) >>> 0; const secondChord = (keybinding & 4294901760) >>> 16; if (secondChord !== 0) { return new Keybinding([ createSimpleKeybinding(firstChord, OS2), createSimpleKeybinding(secondChord, OS2) ]); } return new Keybinding([createSimpleKeybinding(firstChord, OS2)]); } else { const chords = []; for (let i2 = 0; i2 < keybinding.length; i2++) { chords.push(createSimpleKeybinding(keybinding[i2], OS2)); } return new Keybinding(chords); } } function createSimpleKeybinding(keybinding, OS2) { const ctrlCmd = keybinding & 2048 ? true : false; const winCtrl = keybinding & 256 ? true : false; const ctrlKey = OS2 === 2 ? winCtrl : ctrlCmd; const shiftKey = keybinding & 1024 ? true : false; const altKey = keybinding & 512 ? true : false; const metaKey = OS2 === 2 ? ctrlCmd : winCtrl; const keyCode = keybinding & 255; return new KeyCodeChord(ctrlKey, shiftKey, altKey, metaKey, keyCode); } class KeyCodeChord { constructor(ctrlKey, shiftKey, altKey, metaKey, keyCode) { this.ctrlKey = ctrlKey; this.shiftKey = shiftKey; this.altKey = altKey; this.metaKey = metaKey; this.keyCode = keyCode; } equals(other) { return other instanceof KeyCodeChord && this.ctrlKey === other.ctrlKey && this.shiftKey === other.shiftKey && this.altKey === other.altKey && this.metaKey === other.metaKey && this.keyCode === other.keyCode; } isModifierKey() { return this.keyCode === 0 || this.keyCode === 5 || this.keyCode === 57 || this.keyCode === 6 || this.keyCode === 4; } /** * Does this keybinding refer to the key code of a modifier and it also has the modifier flag? */ isDuplicateModifierCase() { return this.ctrlKey && this.keyCode === 5 || this.shiftKey && this.keyCode === 4 || this.altKey && this.keyCode === 6 || this.metaKey && this.keyCode === 57; } } class Keybinding { constructor(chords) { if (chords.length === 0) { throw illegalArgument(`chords`); } this.chords = chords; } } class ResolvedChord { constructor(ctrlKey, shiftKey, altKey, metaKey, keyLabel, keyAriaLabel) { this.ctrlKey = ctrlKey; this.shiftKey = shiftKey; this.altKey = altKey; this.metaKey = metaKey; this.keyLabel = keyLabel; this.keyAriaLabel = keyAriaLabel; } } class ResolvedKeybinding { } function extractKeyCode(e) { if (e.charCode) { const char = String.fromCharCode(e.charCode).toUpperCase(); return KeyCodeUtils.fromString(char); } const keyCode = e.keyCode; if (keyCode === 3) { return 7; } else if (isFirefox$1) { switch (keyCode) { case 59: return 85; case 60: if (isLinux) { return 97; } break; case 61: return 86; // based on: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#numpad_keys case 107: return 109; case 109: return 111; case 173: return 88; case 224: if (isMacintosh) { return 57; } break; } } else if (isWebKit) { if (isMacintosh && keyCode === 93) { return 57; } else if (!isMacintosh && keyCode === 92) { return 57; } } return EVENT_KEY_CODE_MAP[keyCode] || 0; } const ctrlKeyMod$2 = isMacintosh ? 256 : 2048; const altKeyMod = 512; const shiftKeyMod = 1024; const metaKeyMod = isMacintosh ? 2048 : 256; class StandardKeyboardEvent { constructor(source) { this._standardKeyboardEventBrand = true; const e = source; this.browserEvent = e; this.target = e.target; this.ctrlKey = e.ctrlKey; this.shiftKey = e.shiftKey; this.altKey = e.altKey; this.metaKey = e.metaKey; this.altGraphKey = e.getModifierState?.("AltGraph"); this.keyCode = extractKeyCode(e); this.code = e.code; this.ctrlKey = this.ctrlKey || this.keyCode === 5; this.altKey = this.altKey || this.keyCode === 6; this.shiftKey = this.shiftKey || this.keyCode === 4; this.metaKey = this.metaKey || this.keyCode === 57; this._asKeybinding = this._computeKeybinding(); this._asKeyCodeChord = this._computeKeyCodeChord(); } preventDefault() { if (this.browserEvent && this.browserEvent.preventDefault) { this.browserEvent.preventDefault(); } } stopPropagation() { if (this.browserEvent && this.browserEvent.stopPropagation) { this.browserEvent.stopPropagation(); } } toKeyCodeChord() { return this._asKeyCodeChord; } equals(other) { return this._asKeybinding === other; } _computeKeybinding() { let key = 0; if (this.keyCode !== 5 && this.keyCode !== 4 && this.keyCode !== 6 && this.keyCode !== 57) { key = this.keyCode; } let result = 0; if (this.ctrlKey) { result |= ctrlKeyMod$2; } if (this.altKey) { result |= altKeyMod; } if (this.shiftKey) { result |= shiftKeyMod; } if (this.metaKey) { result |= metaKeyMod; } result |= key; return result; } _computeKeyCodeChord() { let key = 0; if (this.keyCode !== 5 && this.keyCode !== 4 && this.keyCode !== 6 && this.keyCode !== 57) { key = this.keyCode; } return new KeyCodeChord(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key); } } const sameOriginWindowChainCache = /* @__PURE__ */ new WeakMap(); function getParentWindowIfSameOrigin(w) { if (!w.parent || w.parent === w) { return null; } try { const location = w.location; const parentLocation = w.parent.location; if (location.origin !== "null" && parentLocation.origin !== "null" && location.origin !== parentLocation.origin) { return null; } } catch (e) { return null; } return w.parent; } class IframeUtils { /** * Returns a chain of embedded windows with the same origin (which can be accessed programmatically). * Having a chain of length 1 might mean that the current execution environment is running outside of an iframe or inside an iframe embedded in a window with a different origin. */ static getSameOriginWindowChain(targetWindow) { let windowChainCache = sameOriginWindowChainCache.get(targetWindow); if (!windowChainCache) { windowChainCache = []; sameOriginWindowChainCache.set(targetWindow, windowChainCache); let w = targetWindow; let parent; do { parent = getParentWindowIfSameOrigin(w); if (parent) { windowChainCache.push({ window: new WeakRef(w), iframeElement: w.frameElement || null }); } else { windowChainCache.push({ window: new WeakRef(w), iframeElement: null }); } w = parent; } while (w); } return windowChainCache.slice(0); } /** * Returns the position of `childWindow` relative to `ancestorWindow` */ static getPositionOfChildWindowRelativeToAncestorWindow(childWindow, ancestorWindow) { if (!ancestorWindow || childWindow === ancestorWindow) { return { top: 0, left: 0 }; } let top = 0, left = 0; const windowChain = this.getSameOriginWindowChain(childWindow); for (const windowChainEl of windowChain) { const windowInChain = windowChainEl.window.deref(); top += windowInChain?.scrollY ?? 0; left += windowInChain?.scrollX ?? 0; if (windowInChain === ancestorWindow) { break; } if (!windowChainEl.iframeElement) { break; } const boundingRect = windowChainEl.iframeElement.getBoundingClientRect(); top += boundingRect.top; left += boundingRect.left; } return { top, left }; } } class StandardMouseEvent { constructor(targetWindow, e) { this.timestamp = Date.now(); this.browserEvent = e; this.leftButton = e.button === 0; this.middleButton = e.button === 1; this.rightButton = e.button === 2; this.buttons = e.buttons; this.defaultPrevented = e.defaultPrevented; this.target = e.target; this.detail = e.detail || 1; if (e.type === "dblclick") { this.detail = 2; } this.ctrlKey = e.ctrlKey; this.shiftKey = e.shiftKey; this.altKey = e.altKey; this.metaKey = e.metaKey; if (typeof e.pageX === "number") { this.posx = e.pageX; this.posy = e.pageY; } else { this.posx = e.clientX + this.target.ownerDocument.body.scrollLeft + this.target.ownerDocument.documentElement.scrollLeft; this.posy = e.clientY + this.target.ownerDocument.body.scrollTop + this.target.ownerDocument.documentElement.scrollTop; } const iframeOffsets = IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(targetWindow, e.view); this.posx -= iframeOffsets.left; this.posy -= iframeOffsets.top; } preventDefault() { this.browserEvent.preventDefault(); } stopPropagation() { this.browserEvent.stopPropagation(); } } class StandardWheelEvent { constructor(e, deltaX = 0, deltaY = 0) { this.browserEvent = e || null; this.target = e ? e.target || e.targetNode || e.srcElement : null; this.deltaY = deltaY; this.deltaX = deltaX; let shouldFactorDPR = false; if (isChrome$1) { const chromeVersionMatch = navigator.userAgent.match(/Chrome\/(\d+)/); const chromeMajorVersion = chromeVersionMatch ? parseInt(chromeVersionMatch[1]) : 123; shouldFactorDPR = chromeMajorVersion <= 122; } if (e) { const e1 = e; const e2 = e; const devicePixelRatio = e.view?.devicePixelRatio || 1; if (typeof e1.wheelDeltaY !== "undefined") { if (shouldFactorDPR) { this.deltaY = e1.wheelDeltaY / (120 * devicePixelRatio); } else { this.deltaY = e1.wheelDeltaY / 120; } } else if (typeof e2.VERTICAL_AXIS !== "undefined" && e2.axis === e2.VERTICAL_AXIS) { this.deltaY = -e2.detail / 3; } else if (e.type === "wheel") { const ev = e; if (ev.deltaMode === ev.DOM_DELTA_LINE) { if (isFirefox$1 && !isMacintosh) { this.deltaY = -e.deltaY / 3; } else { this.deltaY = -e.deltaY; } } else { this.deltaY = -e.deltaY / 40; } } if (typeof e1.wheelDeltaX !== "undefined") { if (isSafari$1 && isWindows) { this.deltaX = -(e1.wheelDeltaX / 120); } else if (shouldFactorDPR) { this.deltaX = e1.wheelDeltaX / (120 * devicePixelRatio); } else { this.deltaX = e1.wheelDeltaX / 120; } } else if (typeof e2.HORIZONTAL_AXIS !== "undefined" && e2.axis === e2.HORIZONTAL_AXIS) { this.deltaX = -e.detail / 3; } else if (e.type === "wheel") { const ev = e; if (ev.deltaMode === ev.DOM_DELTA_LINE) { if (isFirefox$1 && !isMacintosh) { this.deltaX = -e.deltaX / 3; } else { this.deltaX = -e.deltaX; } } else { this.deltaX = -e.deltaX / 40; } } if (this.deltaY === 0 && this.deltaX === 0 && e.wheelDelta) { if (shouldFactorDPR) { this.deltaY = e.wheelDelta / (120 * devicePixelRatio); } else { this.deltaY = e.wheelDelta / 120; } } } } preventDefault() { this.browserEvent?.preventDefault(); } stopPropagation() { this.browserEvent?.stopPropagation(); } } function createSingleCallFunction(fn, fnDidRunCallback) { const _this = this; let didCall = false; let result; return function() { if (didCall) { return result; } didCall = true; { result = fn.apply(_this, arguments); } return result; }; } var Iterable; (function(Iterable2) { function is(thing) { return !!thing && typeof thing === "object" && typeof thing[Symbol.iterator] === "function"; } Iterable2.is = is; const _empty2 = Object.freeze([]); function empty2() { return _empty2; } Iterable2.empty = empty2; function* single(element) { yield element; } Iterable2.single = single; function wrap(iterableOrElement) { if (is(iterableOrElement)) { return iterableOrElement; } else { return single(iterableOrElement); } } Iterable2.wrap = wrap; function from(iterable) { return iterable || _empty2; } Iterable2.from = from; function* reverse(array2) { for (let i2 = array2.length - 1; i2 >= 0; i2--) { yield array2[i2]; } } Iterable2.reverse = reverse; function isEmpty(iterable) { return !iterable || iterable[Symbol.iterator]().next().done === true; } Iterable2.isEmpty = isEmpty; function first2(iterable) { return iterable[Symbol.iterator]().next().value; } Iterable2.first = first2; function some(iterable, predicate) { let i2 = 0; for (const element of iterable) { if (predicate(element, i2++)) { return true; } } return false; } Iterable2.some = some; function every(iterable, predicate) { let i2 = 0; for (const element of iterable) { if (!predicate(element, i2++)) { return false; } } return true; } Iterable2.every = every; function find(iterable, predicate) { for (const element of iterable) { if (predicate(element)) { return element; } } return void 0; } Iterable2.find = find; function* filter(iterable, predicate) { for (const element of iterable) { if (predicate(element)) { yield element; } } } Iterable2.filter = filter; function* map(iterable, fn) { let index = 0; for (const element of iterable) { yield fn(element, index++); } } Iterable2.map = map; function* flatMap(iterable, fn) { let index = 0; for (const element of iterable) { yield* fn(element, index++); } } Iterable2.flatMap = flatMap; function* concat2(...iterables) { for (const item of iterables) { if (isIterable(item)) { yield* item; } else { yield item; } } } Iterable2.concat = concat2; function reduce(iterable, reducer, initialValue) { let value = initialValue; for (const element of iterable) { value = reducer(value, element); } return value; } Iterable2.reduce = reduce; function length(iterable) { let count = 0; for (const _ of iterable) { count++; } return count; } Iterable2.length = length; function* slice(arr, from2, to = arr.length) { if (from2 < -arr.length) { from2 = 0; } if (from2 < 0) { from2 += arr.length; } if (to < 0) { to += arr.length; } else if (to > arr.length) { to = arr.length; } for (; from2 < to; from2++) { yield arr[from2]; } } Iterable2.slice = slice; function consume(iterable, atMost = Number.POSITIVE_INFINITY) { const consumed = []; if (atMost === 0) { return [consumed, iterable]; } const iterator = iterable[Symbol.iterator](); for (let i2 = 0; i2 < atMost; i2++) { const next = iterator.next(); if (next.done) { return [consumed, Iterable2.empty()]; } consumed.push(next.value); } return [consumed, { [Symbol.iterator]() { return iterator; } }]; } Iterable2.consume = consume; async function asyncToArray(iterable) { const result = []; for await (const item of iterable) { result.push(item); } return result; } Iterable2.asyncToArray = asyncToArray; async function asyncToArrayFlat(iterable) { let result = []; for await (const item of iterable) { result = result.concat(item); } return result; } Iterable2.asyncToArrayFlat = asyncToArrayFlat; })(Iterable || (Iterable = {})); function setParentOfDisposable(child, parent) { } function markAsSingleton(singleton) { return singleton; } function isDisposable(thing) { return typeof thing === "object" && thing !== null && typeof thing.dispose === "function" && thing.dispose.length === 0; } function dispose(arg) { if (Iterable.is(arg)) { const errors = []; for (const d of arg) { if (d) { try { d.dispose(); } catch (e) { errors.push(e); } } } if (errors.length === 1) { throw errors[0]; } else if (errors.length > 1) { throw new AggregateError(errors, "Encountered errors while disposing of store"); } return Array.isArray(arg) ? [] : arg; } else if (arg) { arg.dispose(); return arg; } } function combinedDisposable(...disposables) { const parent = toDisposable(() => dispose(disposables)); return parent; } class FunctionDisposable { constructor(fn) { this._isDisposed = false; this._fn = fn; } dispose() { if (this._isDisposed) { return; } if (!this._fn) { throw new Error(`Unbound disposable context: Need to use an arrow function to preserve the value of this`); } this._isDisposed = true; this._fn(); } } function toDisposable(fn) { return new FunctionDisposable(fn); } const _DisposableStore = class _DisposableStore { constructor() { this._toDispose = /* @__PURE__ */ new Set(); this._isDisposed = false; } /** * Dispose of all registered disposables and mark this object as disposed. * * Any future disposables added to this object will be disposed of on `add`. */ dispose() { if (this._isDisposed) { return; } this._isDisposed = true; this.clear(); } /** * @return `true` if this object has been disposed of. */ get isDisposed() { return this._isDisposed; } /** * Dispose of all registered disposables but do not mark this object as disposed. */ clear() { if (this._toDispose.size === 0) { return; } try { dispose(this._toDispose); } finally { this._toDispose.clear(); } } /** * Add a new {@link IDisposable disposable} to the collection. */ add(o) { if (!o || o === Disposable.None) { return o; } if (o === this) { throw new Error("Cannot register a disposable on itself!"); } if (this._isDisposed) { if (!_DisposableStore.DISABLE_DISPOSED_WARNING) { console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack); } } else { this._toDispose.add(o); } return o; } /** * Deletes a disposable from store and disposes of it. This will not throw or warn and proceed to dispose the * disposable even when the disposable is not part in the store. */ delete(o) { if (!o) { return; } if (o === this) { throw new Error("Cannot dispose a disposable on itself!"); } this._toDispose.delete(o); o.dispose(); } }; _DisposableStore.DISABLE_DISPOSED_WARNING = false; let DisposableStore = _DisposableStore; const _Disposable = class _Disposable { constructor() { this._store = new DisposableStore(); setParentOfDisposable(this._store); } dispose() { this._store.dispose(); } /** * Adds `o` to the collection of disposables managed by this object. */ _register(o) { if (o === this) { throw new Error("Cannot register a disposable on itself!"); } return this._store.add(o); } }; _Disposable.None = Object.freeze({ dispose() { } }); let Disposable = _Disposable; class MutableDisposable { constructor() { this._isDisposed = false; } get value() { return this._isDisposed ? void 0 : this._value; } set value(value) { if (this._isDisposed || value === this._value) { return; } this._value?.dispose(); this._value = value; } /** * Resets the stored value and disposed of the previously stored value. */ clear() { this.value = void 0; } dispose() { this._isDisposed = true; this._value?.dispose(); this._value = void 0; } } class RefCountedDisposable { constructor(_disposable) { this._disposable = _disposable; this._counter = 1; } acquire() { this._counter++; return this; } release() { if (--this._counter === 0) { this._disposable.dispose(); } return this; } } class ImmortalReference { constructor(object) { this.object = object; } dispose() { } } class DisposableMap { constructor() { this._store = /* @__PURE__ */ new Map(); this._isDisposed = false; } /** * Disposes of all stored values and mark this object as disposed. * * Trying to use this object after it has been disposed of is an error. */ dispose() { this._isDisposed = true; this.clearAndDisposeAll(); } /** * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed. */ clearAndDisposeAll() { if (!this._store.size) { return; } try { dispose(this._store.values()); } finally { this._store.clear(); } } get(key) { return this._store.get(key); } set(key, value, skipDisposeOnOverwrite = false) { if (this._isDisposed) { console.warn(new Error("Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!").stack); } if (!skipDisposeOnOverwrite) { this._store.get(key)?.dispose(); } this._store.set(key, value); } /** * Delete the value stored for `key` from this map and also dispose of it. */ deleteAndDispose(key) { this._store.get(key)?.dispose(); this._store.delete(key); } values() { return this._store.values(); } [Symbol.iterator]() { return this._store[Symbol.iterator](); } } let Node$2 = (_a2 = class { constructor(element) { this.element = element; this.next = _a2.Undefined; this.prev = _a2.Undefined; } }, _a2.Undefined = new _a2(void 0), _a2); class LinkedList { constructor() { this._first = Node$2.Undefined; this._last = Node$2.Undefined; this._size = 0; } get size() { return this._size; } isEmpty() { return this._first === Node$2.Undefined; } clear() { let node = this._first; while (node !== Node$2.Undefined) { const next = node.next; node.prev = Node$2.Undefined; node.next = Node$2.Undefined; node = next; } this._first = Node$2.Undefined; this._last = Node$2.Undefined; this._size = 0; } unshift(element) { return this._insert(element, false); } push(element) { return this._insert(element, true); } _insert(element, atTheEnd) { const newNode = new Node$2(element); if (this._first === Node$2.Undefined) { this._first = newNode; this._last = newNode; } else if (atTheEnd) { const oldLast = this._last; this._last = newNode; newNode.prev = oldLast; oldLast.next = newNode; } else { const oldFirst = this._first; this._first = newNode; newNode.next = oldFirst; oldFirst.prev = newNode; } this._size += 1; let didRemove = false; return () => { if (!didRemove) { didRemove = true; this._remove(newNode); } }; } shift() { if (this._first === Node$2.Undefined) { return void 0; } else { const res = this._first.element; this._remove(this._first); return res; } } pop() { if (this._last === Node$2.Undefined) { return void 0; } else { const res = this._last.element; this._remove(this._last); return res; } } _remove(node) { if (node.prev !== Node$2.Undefined && node.next !== Node$2.Undefined) { const anchor = node.prev; anchor.next = node.next; node.next.prev = anchor; } else if (node.prev === Node$2.Undefined && node.next === Node$2.Undefined) { this._first = Node$2.Undefined; this._last = Node$2.Undefined; } else if (node.next === Node$2.Undefined) { this._last = this._last.prev; this._last.next = Node$2.Undefined; } else if (node.prev === Node$2.Undefined) { this._first = this._first.next; this._first.prev = Node$2.Undefined; } this._size -= 1; } *[Symbol.iterator]() { let node = this._first; while (node !== Node$2.Undefined) { yield node.element; node = node.next; } } } const performanceNow = globalThis.performance.now.bind(globalThis.performance); class StopWatch { static create(highResolution) { return new StopWatch(highResolution); } constructor(highResolution) { this._now = highResolution === false ? Date.now : performanceNow; this._startTime = this._now(); this._stopTime = -1; } stop() { this._stopTime = this._now(); } reset() { this._startTime = this._now(); this._stopTime = -1; } elapsed() { if (this._stopTime !== -1) { return this._stopTime - this._startTime; } return this._now() - this._startTime; } } var Event; (function(Event2) { Event2.None = () => Disposable.None; function defer(event, disposable) { return debounce(event, () => void 0, 0, void 0, true, void 0, disposable); } Event2.defer = defer; function once(event) { return (listener, thisArgs = null, disposables) => { let didFire = false; let result = void 0; result = event((e) => { if (didFire) { return; } else if (result) { result.dispose(); } else { didFire = true; } return listener.call(thisArgs, e); }, null, disposables); if (didFire) { result.dispose(); } return result; }; } Event2.once = once; function onceIf(event, condition) { return Event2.once(Event2.filter(event, condition)); } Event2.onceIf = onceIf; function map(event, map2, disposable) { return snapshot((listener, thisArgs = null, disposables) => event((i2) => listener.call(thisArgs, map2(i2)), null, disposables), disposable); } Event2.map = map; function forEach(event, each, disposable) { return snapshot((listener, thisArgs = null, disposables) => event((i2) => { each(i2); listener.call(thisArgs, i2); }, null, disposables), disposable); } Event2.forEach = forEach; function filter(event, filter2, disposable) { return snapshot((listener, thisArgs = null, disposables) => event((e) => filter2(e) && listener.call(thisArgs, e), null, disposables), disposable); } Event2.filter = filter; function signal(event) { return event; } Event2.signal = signal; function any(...events) { return (listener, thisArgs = null, disposables) => { const disposable = combinedDisposable(...events.map((event) => event((e) => listener.call(thisArgs, e)))); return addAndReturnDisposable(disposable, disposables); }; } Event2.any = any; function reduce(event, merge, initial, disposable) { let output = initial; return map(event, (e) => { output = merge(output, e); return output; }, disposable); } Event2.reduce = reduce; function snapshot(event, disposable) { let listener; const options = { onWillAddFirstListener() { listener = event(emitter.fire, emitter); }, onDidRemoveLastListener() { listener?.dispose(); } }; const emitter = new Emitter$1(options); disposable?.add(emitter); return emitter.event; } function addAndReturnDisposable(d, store) { if (store instanceof Array) { store.push(d); } else if (store) { store.add(d); } return d; } function debounce(event, merge, delay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold, disposable) { let subscription; let output = void 0; let handle = void 0; let numDebouncedCalls = 0; let doFire; const options = { leakWarningThreshold, onWillAddFirstListener() { subscription = event((cur) => { numDebouncedCalls++; output = merge(output, cur); if (leading && !handle) { emitter.fire(output); output = void 0; } doFire = () => { const _output = output; output = void 0; handle = void 0; if (!leading || numDebouncedCalls > 1) { emitter.fire(_output); } numDebouncedCalls = 0; }; if (typeof delay === "number") { if (handle) { clearTimeout(handle); } handle = setTimeout(doFire, delay); } else { if (handle === void 0) { handle = null; queueMicrotask(doFire); } } }); }, onWillRemoveListener() { if (flushOnListenerRemove && numDebouncedCalls > 0) { doFire?.(); } }, onDidRemoveLastListener() { doFire = void 0; subscription.dispose(); } }; const emitter = new Emitter$1(options); disposable?.add(emitter); return emitter.event; } Event2.debounce = debounce; function accumulate(event, delay = 0, disposable) { return Event2.debounce(event, (last, e) => { if (!last) { return [e]; } last.push(e); return last; }, delay, void 0, true, void 0, disposable); } Event2.accumulate = accumulate; function latch(event, equals2 = (a, b) => a === b, disposable) { let firstCall = true; let cache; return filter(event, (value) => { const shouldEmit = firstCall || !equals2(value, cache); firstCall = false; cache = value; return shouldEmit; }, disposable); } Event2.latch = latch; function split(event, isT, disposable) { return [ Event2.filter(event, isT, disposable), Event2.filter(event, (e) => !isT(e), disposable) ]; } Event2.split = split; function buffer(event, flushAfterTimeout = false, _buffer = [], disposable) { let buffer2 = _buffer.slice(); let listener = event((e) => { if (buffer2) { buffer2.push(e); } else { emitter.fire(e); } }); if (disposable) { disposable.add(listener); } const flush = () => { buffer2?.forEach((e) => emitter.fire(e)); buffer2 = null; }; const emitter = new Emitter$1({ onWillAddFirstListener() { if (!listener) { listener = event((e) => emitter.fire(e)); if (disposable) { disposable.add(listener); } } }, onDidAddFirstListener() { if (buffer2) { if (flushAfterTimeout) { setTimeout(flush); } else { flush(); } } }, onDidRemoveLastListener() { if (listener) { listener.dispose(); } listener = null; } }); if (disposable) { disposable.add(emitter); } return emitter.event; } Event2.buffer = buffer; function chain(event, sythensize) { const fn = (listener, thisArgs, disposables) => { const cs = sythensize(new ChainableSynthesis()); return event(function(value) { const result = cs.evaluate(value); if (result !== HaltChainable) { listener.call(thisArgs, result); } }, void 0, disposables); }; return fn; } Event2.chain = chain; const HaltChainable = Symbol("HaltChainable"); class ChainableSynthesis { constructor() { this.steps = []; } map(fn) { this.steps.push(fn); return this; } forEach(fn) { this.steps.push((v) => { fn(v); return v; }); return this; } filter(fn) { this.steps.push((v) => fn(v) ? v : HaltChainable); return this; } reduce(merge, initial) { let last = initial; this.steps.push((v) => { last = merge(last, v); return last; }); return this; } latch(equals2 = (a, b) => a === b) { let firstCall = true; let cache; this.steps.push((value) => { const shouldEmit = firstCall || !equals2(value, cache); firstCall = false; cache = value; return shouldEmit ? value : HaltChainable; }); return this; } evaluate(value) { for (const step of this.steps) { value = step(value); if (value === HaltChainable) { break; } } return value; } } function fromNodeEventEmitter(emitter, eventName, map2 = (id) => id) { const fn = (...args) => result.fire(map2(...args)); const onFirstListenerAdd = () => emitter.on(eventName, fn); const onLastListenerRemove = () => emitter.removeListener(eventName, fn); const result = new Emitter$1({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove }); return result.event; } Event2.fromNodeEventEmitter = fromNodeEventEmitter; function fromDOMEventEmitter(emitter, eventName, map2 = (id) => id) { const fn = (...args) => result.fire(map2(...args)); const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn); const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn); const result = new Emitter$1({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove }); return result.event; } Event2.fromDOMEventEmitter = fromDOMEventEmitter; function toPromise(event, disposables) { let cancelRef; const promise = new Promise((resolve2, reject) => { const listener = once(event)(resolve2, null, disposables); cancelRef = () => listener.dispose(); }); promise.cancel = cancelRef; return promise; } Event2.toPromise = toPromise; function forward(from, to) { return from((e) => to.fire(e)); } Event2.forward = forward; function runAndSubscribe(event, handler, initial) { handler(initial); return event((e) => handler(e)); } Event2.runAndSubscribe = runAndSubscribe; class EmitterObserver { constructor(_observable, store) { this._observable = _observable; this._counter = 0; this._hasChanged = false; const options = { onWillAddFirstListener: () => { _observable.addObserver(this); this._observable.reportChanges(); }, onDidRemoveLastListener: () => { _observable.removeObserver(this); } }; this.emitter = new Emitter$1(options); if (store) { store.add(this.emitter); } } beginUpdate(_observable) { this._counter++; } handlePossibleChange(_observable) { } handleChange(_observable, _change) { this._hasChanged = true; } endUpdate(_observable) { this._counter--; if (this._counter === 0) { this._observable.reportChanges(); if (this._hasChanged) { this._hasChanged = false; this.emitter.fire(this._observable.get()); } } } } function fromObservable(obs, store) { const observer = new EmitterObserver(obs, store); return observer.emitter.event; } Event2.fromObservable = fromObservable; function fromObservableLight(observable) { return (listener, thisArgs, disposables) => { let count = 0; let didChange = false; const observer = { beginUpdate() { count++; }, endUpdate() { count--; if (count === 0) { observable.reportChanges(); if (didChange) { didChange = false; listener.call(thisArgs); } } }, handlePossibleChange() { }, handleChange() { didChange = true; } }; observable.addObserver(observer); observable.reportChanges(); const disposable = { dispose() { observable.removeObserver(observer); } }; if (disposables instanceof DisposableStore) { disposables.add(disposable); } else if (Array.isArray(disposables)) { disposables.push(disposable); } return disposable; }; } Event2.fromObservableLight = fromObservableLight; })(Event || (Event = {})); const _EventProfiling = class _EventProfiling { constructor(name) { this.listenerCount = 0; this.invocationCount = 0; this.elapsedOverall = 0; this.durations = []; this.name = `${name}_${_EventProfiling._idPool++}`; _EventProfiling.all.add(this); } start(listenerCount) { this._stopWatch = new StopWatch(); this.listenerCount = listenerCount; } stop() { if (this._stopWatch) { const elapsed = this._stopWatch.elapsed(); this.durations.push(elapsed); this.elapsedOverall += elapsed; this.invocationCount += 1; this._stopWatch = void 0; } } }; _EventProfiling.all = /* @__PURE__ */ new Set(); _EventProfiling._idPool = 0; let EventProfiling = _EventProfiling; let _globalLeakWarningThreshold = -1; const _LeakageMonitor = class _LeakageMonitor { constructor(_errorHandler, threshold, name = (_LeakageMonitor._idPool++).toString(16).padStart(3, "0")) { this._errorHandler = _errorHandler; this.threshold = threshold; this.name = name; this._warnCountdown = 0; } dispose() { this._stacks?.clear(); } check(stack, listenerCount) { const threshold = this.threshold; if (threshold <= 0 || listenerCount < threshold) { return void 0; } if (!this._stacks) { this._stacks = /* @__PURE__ */ new Map(); } const count = this._stacks.get(stack.value) || 0; this._stacks.set(stack.value, count + 1); this._warnCountdown -= 1; if (this._warnCountdown <= 0) { this._warnCountdown = threshold * 0.5; const [topStack, topCount] = this.getMostFrequentStack(); const message = `[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`; console.warn(message); console.warn(topStack); const error = new ListenerLeakError(message, topStack); this._errorHandler(error); } return () => { const count2 = this._stacks.get(stack.value) || 0; this._stacks.set(stack.value, count2 - 1); }; } getMostFrequentStack() { if (!this._stacks) { return void 0; } let topStack; let topCount = 0; for (const [stack, count] of this._stacks) { if (!topStack || topCount < count) { topStack = [stack, count]; topCount = count; } } return topStack; } }; _LeakageMonitor._idPool = 1; let LeakageMonitor = _LeakageMonitor; class Stacktrace { static create() { const err = new Error(); return new Stacktrace(err.stack ?? ""); } constructor(value) { this.value = value; } print() { console.warn(this.value.split("\n").slice(2).join("\n")); } } class ListenerLeakError extends Error { constructor(message, stack) { super(message); this.name = "ListenerLeakError"; this.stack = stack; } } class ListenerRefusalError extends Error { constructor(message, stack) { super(message); this.name = "ListenerRefusalError"; this.stack = stack; } } class UniqueContainer { constructor(value) { this.value = value; } } const compactionThreshold = 2; let Emitter$1 = class Emitter { constructor(options) { this._size = 0; this._options = options; this._leakageMon = this._options?.leakWarningThreshold ? new LeakageMonitor(options?.onListenerError ?? onUnexpectedError, this._options?.leakWarningThreshold ?? _globalLeakWarningThreshold) : void 0; this._perfMon = this._options?._profName ? new EventProfiling(this._options._profName) : void 0; this._deliveryQueue = this._options?.deliveryQueue; } dispose() { if (!this._disposed) { this._disposed = true; if (this._deliveryQueue?.current === this) { this._deliveryQueue.reset(); } if (this._listeners) { this._listeners = void 0; this._size = 0; } this._options?.onDidRemoveLastListener?.(); this._leakageMon?.dispose(); } } /** * For the public to allow to subscribe * to events from this Emitter */ get event() { this._event ??= (callback, thisArgs, disposables) => { if (this._leakageMon && this._size > this._leakageMon.threshold ** 2) { const message = `[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`; console.warn(message); const tuple = this._leakageMon.getMostFrequentStack() ?? ["UNKNOWN stack", -1]; const error = new ListenerRefusalError(`${message}. HINT: Stack shows most frequent listener (${tuple[1]}-times)`, tuple[0]); const errorHandler2 = this._options?.onListenerError || onUnexpectedError; errorHandler2(error); return Disposable.None; } if (this._disposed) { return Disposable.None; } if (thisArgs) { callback = callback.bind(thisArgs); } const contained = new UniqueContainer(callback); let removeMonitor; if (this._leakageMon && this._size >= Math.ceil(this._leakageMon.threshold * 0.2)) { contained.stack = Stacktrace.create(); removeMonitor = this._leakageMon.check(contained.stack, this._size + 1); } if (!this._listeners) { this._options?.onWillAddFirstListener?.(this); this._listeners = contained; this._options?.onDidAddFirstListener?.(this); } else if (this._listeners instanceof UniqueContainer) { this._deliveryQueue ??= new EventDeliveryQueuePrivate(); this._listeners = [this._listeners, contained]; } else { this._listeners.push(contained); } this._options?.onDidAddListener?.(this); this._size++; const result = toDisposable(() => { removeMonitor?.(); this._removeListener(contained); }); if (disposables instanceof DisposableStore) { disposables.add(result); } else if (Array.isArray(disposables)) { disposables.push(result); } return result; }; return this._event; } _removeListener(listener) { this._options?.onWillRemoveListener?.(this); if (!this._listeners) { return; } if (this._size === 1) { this._listeners = void 0; this._options?.onDidRemoveLastListener?.(this); this._size = 0; return; } const listeners = this._listeners; const index = listeners.indexOf(listener); if (index === -1) { console.log("disposed?", this._disposed); console.log("size?", this._size); console.log("arr?", JSON.stringify(this._listeners)); throw new Error("Attempted to dispose unknown listener"); } this._size--; listeners[index] = void 0; const adjustDeliveryQueue = this._deliveryQueue.current === this; if (this._size * compactionThreshold <= listeners.length) { let n2 = 0; for (let i2 = 0; i2 < listeners.length; i2++) { if (listeners[i2]) { listeners[n2++] = listeners[i2]; } else if (adjustDeliveryQueue && n2 < this._deliveryQueue.end) { this._deliveryQueue.end--; if (n2 < this._deliveryQueue.i) { this._deliveryQueue.i--; } } } listeners.length = n2; } } _deliver(listener, value) { if (!listener) { return; } const errorHandler2 = this._options?.onListenerError || onUnexpectedError; if (!errorHandler2) { listener.value(value); return; } try { listener.value(value); } catch (e) { errorHandler2(e); } } /** Delivers items in the queue. Assumes the queue is ready to go. */ _deliverQueue(dq) { const listeners = dq.current._listeners; while (dq.i < dq.end) { this._deliver(listeners[dq.i++], dq.value); } dq.reset(); } /** * To be kept private to fire an event to * subscribers */ fire(event) { if (this._deliveryQueue?.current) { this._deliverQueue(this._deliveryQueue); this._perfMon?.stop(); } this._perfMon?.start(this._size); if (!this._listeners) ; else if (this._listeners instanceof UniqueContainer) { this._deliver(this._listeners, event); } else { const dq = this._deliveryQueue; dq.enqueue(this, event, this._listeners.length); this._deliverQueue(dq); } this._perfMon?.stop(); } hasListeners() { return this._size > 0; } }; const createEventDeliveryQueue = () => new EventDeliveryQueuePrivate(); class EventDeliveryQueuePrivate { constructor() { this.i = -1; this.end = 0; } enqueue(emitter, value, end) { this.i = 0; this.end = end; this.current = emitter; this.value = value; } reset() { this.i = this.end; this.current = void 0; this.value = void 0; } } class PauseableEmitter extends Emitter$1 { constructor(options) { super(options); this._isPaused = 0; this._eventQueue = new LinkedList(); this._mergeFn = options?.merge; } pause() { this._isPaused++; } resume() { if (this._isPaused !== 0 && --this._isPaused === 0) { if (this._mergeFn) { if (this._eventQueue.size > 0) { const events = Array.from(this._eventQueue); this._eventQueue.clear(); super.fire(this._mergeFn(events)); } } else { while (!this._isPaused && this._eventQueue.size !== 0) { super.fire(this._eventQueue.shift()); } } } } fire(event) { if (this._size) { if (this._isPaused !== 0) { this._eventQueue.push(event); } else { super.fire(event); } } } } class DebounceEmitter extends PauseableEmitter { constructor(options) { super(options); this._delay = options.delay ?? 100; } fire(event) { if (!this._handle) { this.pause(); this._handle = setTimeout(() => { this._handle = void 0; this.resume(); }, this._delay); } super.fire(event); } } class MicrotaskEmitter extends Emitter$1 { constructor(options) { super(options); this._queuedEvents = []; this._mergeFn = options?.merge; } fire(event) { if (!this.hasListeners()) { return; } this._queuedEvents.push(event); if (this._queuedEvents.length === 1) { queueMicrotask(() => { if (this._mergeFn) { super.fire(this._mergeFn(this._queuedEvents)); } else { this._queuedEvents.forEach((e) => super.fire(e)); } this._queuedEvents = []; }); } } } class EventMultiplexer { constructor() { this.hasListeners = false; this.events = []; this.emitter = new Emitter$1({ onWillAddFirstListener: () => this.onFirstListenerAdd(), onDidRemoveLastListener: () => this.onLastListenerRemove() }); } get event() { return this.emitter.event; } add(event) { const e = { event, listener: null }; this.events.push(e); if (this.hasListeners) { this.hook(e); } const dispose2 = () => { if (this.hasListeners) { this.unhook(e); } const idx = this.events.indexOf(e); this.events.splice(idx, 1); }; return toDisposable(createSingleCallFunction(dispose2)); } onFirstListenerAdd() { this.hasListeners = true; this.events.forEach((e) => this.hook(e)); } onLastListenerRemove() { this.hasListeners = false; this.events.forEach((e) => this.unhook(e)); } hook(e) { e.listener = e.event((r) => this.emitter.fire(r)); } unhook(e) { e.listener?.dispose(); e.listener = null; } dispose() { this.emitter.dispose(); for (const e of this.events) { e.listener?.dispose(); } this.events = []; } } class EventBufferer { constructor() { this.data = []; } wrapEvent(event, reduce, initial) { return (listener, thisArgs, disposables) => { return event((i2) => { const data = this.data[this.data.length - 1]; if (!reduce) { if (data) { data.buffers.push(() => listener.call(thisArgs, i2)); } else { listener.call(thisArgs, i2); } return; } const reduceData = data; if (!reduceData) { listener.call(thisArgs, reduce(initial, i2)); return; } reduceData.items ??= []; reduceData.items.push(i2); if (reduceData.buffers.length === 0) { data.buffers.push(() => { reduceData.reducedResult ??= initial ? reduceData.items.reduce(reduce, initial) : reduceData.items.reduce(reduce); listener.call(thisArgs, reduceData.reducedResult); }); } }, void 0, disposables); }; } bufferEvents(fn) { const data = { buffers: new Array() }; this.data.push(data); const r = fn(); this.data.pop(); data.buffers.forEach((flush) => flush()); return r; } } class Relay { constructor() { this.listening = false; this.inputEvent = Event.None; this.inputEventListener = Disposable.None; this.emitter = new Emitter$1({ onDidAddFirstListener: () => { this.listening = true; this.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter); }, onDidRemoveLastListener: () => { this.listening = false; this.inputEventListener.dispose(); } }); this.event = this.emitter.event; } set input(event) { this.inputEvent = event; if (this.listening) { this.inputEventListener.dispose(); this.inputEventListener = event(this.emitter.fire, this.emitter); } } dispose() { this.inputEventListener.dispose(); this.emitter.dispose(); } } const shortcutEvent = Object.freeze(function(callback, context) { const handle = setTimeout(callback.bind(context), 0); return { dispose() { clearTimeout(handle); } }; }); var CancellationToken; (function(CancellationToken2) { function isCancellationToken(thing) { if (thing === CancellationToken2.None || thing === CancellationToken2.Cancelled) { return true; } if (thing instanceof MutableToken) { return true; } if (!thing || typeof thing !== "object") { return false; } return typeof thing.isCancellationRequested === "boolean" && typeof thing.onCancellationRequested === "function"; } CancellationToken2.isCancellationToken = isCancellationToken; CancellationToken2.None = Object.freeze({ isCancellationRequested: false, onCancellationRequested: Event.None }); CancellationToken2.Cancelled = Object.freeze({ isCancellationRequested: true, onCancellationRequested: shortcutEvent }); })(CancellationToken || (CancellationToken = {})); class MutableToken { constructor() { this._isCancelled = false; this._emitter = null; } cancel() { if (!this._isCancelled) { this._isCancelled = true; if (this._emitter) { this._emitter.fire(void 0); this.dispose(); } } } get isCancellationRequested() { return this._isCancelled; } get onCancellationRequested() { if (this._isCancelled) { return shortcutEvent; } if (!this._emitter) { this._emitter = new Emitter$1(); } return this._emitter.event; } dispose() { if (this._emitter) { this._emitter.dispose(); this._emitter = null; } } } let CancellationTokenSource$1 = class CancellationTokenSource { constructor(parent) { this._token = void 0; this._parentListener = void 0; this._parentListener = parent && parent.onCancellationRequested(this.cancel, this); } get token() { if (!this._token) { this._token = new MutableToken(); } return this._token; } cancel() { if (!this._token) { this._token = CancellationToken.Cancelled; } else if (this._token instanceof MutableToken) { this._token.cancel(); } } dispose(cancel = false) { if (cancel) { this.cancel(); } this._parentListener?.dispose(); if (!this._token) { this._token = CancellationToken.None; } else if (this._token instanceof MutableToken) { this._token.dispose(); } } }; function cancelOnDispose(store) { const source = new CancellationTokenSource$1(); store.add({ dispose() { source.cancel(); } }); return source.token; } const MicrotaskDelay = Symbol("MicrotaskDelay"); function isThenable$1(obj) { return !!obj && typeof obj.then === "function"; } function createCancelablePromise(callback) { const source = new CancellationTokenSource$1(); const thenable = callback(source.token); let isCancelled = false; const promise = new Promise((resolve2, reject) => { const subscription = source.token.onCancellationRequested(() => { isCancelled = true; subscription.dispose(); reject(new CancellationError()); }); Promise.resolve(thenable).then((value) => { subscription.dispose(); source.dispose(); if (!isCancelled) { resolve2(value); } else if (isDisposable(value)) { value.dispose(); } }, (err) => { subscription.dispose(); source.dispose(); reject(err); }); }); return new class { cancel() { source.cancel(); source.dispose(); } then(resolve2, reject) { return promise.then(resolve2, reject); } catch(reject) { return this.then(void 0, reject); } finally(onfinally) { return promise.finally(onfinally); } }(); } function raceCancellation(promise, token, defaultValue) { return new Promise((resolve2, reject) => { const ref = token.onCancellationRequested(() => { ref.dispose(); resolve2(defaultValue); }); promise.then(resolve2, reject).finally(() => ref.dispose()); }); } function raceCancellationError(promise, token) { return new Promise((resolve2, reject) => { const ref = token.onCancellationRequested(() => { ref.dispose(); reject(new CancellationError()); }); promise.then(resolve2, reject).finally(() => ref.dispose()); }); } let Throttler$1 = class Throttler { constructor() { this.isDisposed = false; this.activePromise = null; this.queuedPromise = null; this.queuedPromiseFactory = null; } queue(promiseFactory) { if (this.isDisposed) { return Promise.reject(new Error("Throttler is disposed")); } if (this.activePromise) { this.queuedPromiseFactory = promiseFactory; if (!this.queuedPromise) { const onComplete = () => { this.queuedPromise = null; if (this.isDisposed) { return; } const result = this.queue(this.queuedPromiseFactory); this.queuedPromiseFactory = null; return result; }; this.queuedPromise = new Promise((resolve2) => { this.activePromise.then(onComplete, onComplete).then(resolve2); }); } return new Promise((resolve2, reject) => { this.queuedPromise.then(resolve2, reject); }); } this.activePromise = promiseFactory(); return new Promise((resolve2, reject) => { this.activePromise.then((result) => { this.activePromise = null; resolve2(result); }, (err) => { this.activePromise = null; reject(err); }); }); } dispose() { this.isDisposed = true; } }; const timeoutDeferred = (timeout2, fn) => { let scheduled = true; const handle = setTimeout(() => { scheduled = false; fn(); }, timeout2); return { isTriggered: () => scheduled, dispose: () => { clearTimeout(handle); scheduled = false; } }; }; const microtaskDeferred = (fn) => { let scheduled = true; queueMicrotask(() => { if (scheduled) { scheduled = false; fn(); } }); return { isTriggered: () => scheduled, dispose: () => { scheduled = false; } }; }; class Delayer { constructor(defaultDelay) { this.defaultDelay = defaultDelay; this.deferred = null; this.completionPromise = null; this.doResolve = null; this.doReject = null; this.task = null; } trigger(task, delay = this.defaultDelay) { this.task = task; this.cancelTimeout(); if (!this.completionPromise) { this.completionPromise = new Promise((resolve2, reject) => { this.doResolve = resolve2; this.doReject = reject; }).then(() => { this.completionPromise = null; this.doResolve = null; if (this.task) { const task2 = this.task; this.task = null; return task2(); } return void 0; }); } const fn = () => { this.deferred = null; this.doResolve?.(null); }; this.deferred = delay === MicrotaskDelay ? microtaskDeferred(fn) : timeoutDeferred(delay, fn); return this.completionPromise; } isTriggered() { return !!this.deferred?.isTriggered(); } cancel() { this.cancelTimeout(); if (this.completionPromise) { this.doReject?.(new CancellationError()); this.completionPromise = null; } } cancelTimeout() { this.deferred?.dispose(); this.deferred = null; } dispose() { this.cancel(); } } class ThrottledDelayer { constructor(defaultDelay) { this.delayer = new Delayer(defaultDelay); this.throttler = new Throttler$1(); } trigger(promiseFactory, delay) { return this.delayer.trigger(() => this.throttler.queue(promiseFactory), delay); } cancel() { this.delayer.cancel(); } dispose() { this.delayer.dispose(); this.throttler.dispose(); } } function timeout(millis, token) { if (!token) { return createCancelablePromise((token2) => timeout(millis, token2)); } return new Promise((resolve2, reject) => { const handle = setTimeout(() => { disposable.dispose(); resolve2(); }, millis); const disposable = token.onCancellationRequested(() => { clearTimeout(handle); disposable.dispose(); reject(new CancellationError()); }); }); } function disposableTimeout(handler, timeout2 = 0, store) { const timer = setTimeout(() => { handler(); if (store) { disposable.dispose(); } }, timeout2); const disposable = toDisposable(() => { clearTimeout(timer); store?.delete(disposable); }); store?.add(disposable); return disposable; } function first(promiseFactories, shouldStop = (t) => !!t, defaultValue = null) { let index = 0; const len = promiseFactories.length; const loop = () => { if (index >= len) { return Promise.resolve(defaultValue); } const factory = promiseFactories[index++]; const promise = Promise.resolve(factory()); return promise.then((result) => { if (shouldStop(result)) { return Promise.resolve(result); } return loop(); }); }; return loop(); } let TaskQueue$1 = class TaskQueue { constructor() { this._runningTask = void 0; this._pendingTasks = []; } /** * Waits for the current and pending tasks to finish, then runs and awaits the given task. * If the task is skipped because of clearPending, the promise is rejected with a CancellationError. */ schedule(task) { const deferred = new DeferredPromise(); this._pendingTasks.push({ task, deferred, setUndefinedWhenCleared: false }); this._runIfNotRunning(); return deferred.p; } _runIfNotRunning() { if (this._runningTask === void 0) { this._processQueue(); } } async _processQueue() { if (this._pendingTasks.length === 0) { return; } const next = this._pendingTasks.shift(); if (!next) { return; } if (this._runningTask) { throw new BugIndicatingError(); } this._runningTask = next.task; try { const result = await next.task(); next.deferred.complete(result); } catch (e) { next.deferred.error(e); } finally { this._runningTask = void 0; this._processQueue(); } } /** * Clears all pending tasks. Does not cancel the currently running task. */ clearPending() { const tasks = this._pendingTasks; this._pendingTasks = []; for (const task of tasks) { if (task.setUndefinedWhenCleared) { task.deferred.complete(void 0); } else { task.deferred.error(new CancellationError()); } } } }; class TimeoutTimer { constructor(runner, timeout2) { this._isDisposed = false; this._token = void 0; if (typeof runner === "function" && typeof timeout2 === "number") { this.setIfNotSet(runner, timeout2); } } dispose() { this.cancel(); this._isDisposed = true; } cancel() { if (this._token !== void 0) { clearTimeout(this._token); this._token = void 0; } } cancelAndSet(runner, timeout2) { if (this._isDisposed) { throw new BugIndicatingError(`Calling 'cancelAndSet' on a disposed TimeoutTimer`); } this.cancel(); this._token = setTimeout(() => { this._token = void 0; runner(); }, timeout2); } setIfNotSet(runner, timeout2) { if (this._isDisposed) { throw new BugIndicatingError(`Calling 'setIfNotSet' on a disposed TimeoutTimer`); } if (this._token !== void 0) { return; } this._token = setTimeout(() => { this._token = void 0; runner(); }, timeout2); } } class IntervalTimer { constructor() { this.disposable = void 0; this.isDisposed = false; } cancel() { this.disposable?.dispose(); this.disposable = void 0; } cancelAndSet(runner, interval, context = globalThis) { if (this.isDisposed) { throw new BugIndicatingError(`Calling 'cancelAndSet' on a disposed IntervalTimer`); } this.cancel(); const handle = context.setInterval(() => { runner(); }, interval); this.disposable = toDisposable(() => { context.clearInterval(handle); this.disposable = void 0; }); } dispose() { this.cancel(); this.isDisposed = true; } } class RunOnceScheduler { constructor(runner, delay) { this.timeoutToken = void 0; this.runner = runner; this.timeout = delay; this.timeoutHandler = this.onTimeout.bind(this); } /** * Dispose RunOnceScheduler */ dispose() { this.cancel(); this.runner = null; } /** * Cancel current scheduled runner (if any). */ cancel() { if (this.isScheduled()) { clearTimeout(this.timeoutToken); this.timeoutToken = void 0; } } /** * Cancel previous runner (if any) & schedule a new runner. */ schedule(delay = this.timeout) { this.cancel(); this.timeoutToken = setTimeout(this.timeoutHandler, delay); } get delay() { return this.timeout; } set delay(value) { this.timeout = value; } /** * Returns true if scheduled. */ isScheduled() { return this.timeoutToken !== void 0; } onTimeout() { this.timeoutToken = void 0; if (this.runner) { this.doRun(); } } doRun() { this.runner?.(); } } let runWhenGlobalIdle; let _runWhenIdle; (function() { const safeGlobal = globalThis; if (typeof safeGlobal.requestIdleCallback !== "function" || typeof safeGlobal.cancelIdleCallback !== "function") { _runWhenIdle = (_targetWindow, runner, timeout2) => { setTimeout0(() => { if (disposed) { return; } const end = Date.now() + 15; const deadline = { didTimeout: true, timeRemaining() { return Math.max(0, end - Date.now()); } }; runner(Object.freeze(deadline)); }); let disposed = false; return { dispose() { if (disposed) { return; } disposed = true; } }; }; } else { _runWhenIdle = (targetWindow, runner, timeout2) => { const handle = targetWindow.requestIdleCallback(runner, typeof timeout2 === "number" ? { timeout: timeout2 } : void 0); let disposed = false; return { dispose() { if (disposed) { return; } disposed = true; targetWindow.cancelIdleCallback(handle); } }; }; } runWhenGlobalIdle = (runner, timeout2) => _runWhenIdle(globalThis, runner, timeout2); })(); class AbstractIdleValue { constructor(targetWindow, executor) { this._didRun = false; this._executor = () => { try { this._value = executor(); } catch (err) { this._error = err; } finally { this._didRun = true; } }; this._handle = _runWhenIdle(targetWindow, () => this._executor()); } dispose() { this._handle.dispose(); } get value() { if (!this._didRun) { this._handle.dispose(); this._executor(); } if (this._error) { throw this._error; } return this._value; } get isInitialized() { return this._didRun; } } class GlobalIdleValue extends AbstractIdleValue { constructor(executor) { super(globalThis, executor); } } class DeferredPromise { get isRejected() { return this.outcome?.outcome === 1; } get isSettled() { return !!this.outcome; } constructor() { this.p = new Promise((c, e) => { this.completeCallback = c; this.errorCallback = e; }); } complete(value) { if (this.isSettled) { return Promise.resolve(); } return new Promise((resolve2) => { this.completeCallback(value); this.outcome = { outcome: 0, value }; resolve2(); }); } error(err) { if (this.isSettled) { return Promise.resolve(); } return new Promise((resolve2) => { this.errorCallback(err); this.outcome = { outcome: 1, value: err }; resolve2(); }); } cancel() { return this.error(new CancellationError()); } } var Promises; (function(Promises2) { async function settled(promises) { let firstError = void 0; const result = await Promise.all(promises.map((promise) => promise.then((value) => value, (error) => { if (!firstError) { firstError = error; } return void 0; }))); if (typeof firstError !== "undefined") { throw firstError; } return result; } Promises2.settled = settled; function withAsyncBody(bodyFn) { return new Promise(async (resolve2, reject) => { try { await bodyFn(resolve2, reject); } catch (error) { reject(error); } }); } Promises2.withAsyncBody = withAsyncBody; })(Promises || (Promises = {})); function createCancelableAsyncIterableProducer(callback) { const source = new CancellationTokenSource$1(); const innerIterable = callback(source.token); return new CancelableAsyncIterableProducer(source, async (emitter) => { const subscription = source.token.onCancellationRequested(() => { subscription.dispose(); source.dispose(); emitter.reject(new CancellationError()); }); try { for await (const item of innerIterable) { if (source.token.isCancellationRequested) { return; } emitter.emitOne(item); } subscription.dispose(); source.dispose(); } catch (err) { subscription.dispose(); source.dispose(); emitter.reject(err); } }); } class ProducerConsumer { constructor() { this._unsatisfiedConsumers = []; this._unconsumedValues = []; } get hasFinalValue() { return !!this._finalValue; } produce(value) { this._ensureNoFinalValue(); if (this._unsatisfiedConsumers.length > 0) { const deferred = this._unsatisfiedConsumers.shift(); this._resolveOrRejectDeferred(deferred, value); } else { this._unconsumedValues.push(value); } } produceFinal(value) { this._ensureNoFinalValue(); this._finalValue = value; for (const deferred of this._unsatisfiedConsumers) { this._resolveOrRejectDeferred(deferred, value); } this._unsatisfiedConsumers.length = 0; } _ensureNoFinalValue() { if (this._finalValue) { throw new BugIndicatingError("ProducerConsumer: cannot produce after final value has been set"); } } _resolveOrRejectDeferred(deferred, value) { if (value.ok) { deferred.complete(value.value); } else { deferred.error(value.error); } } consume() { if (this._unconsumedValues.length > 0 || this._finalValue) { const value = this._unconsumedValues.length > 0 ? this._unconsumedValues.shift() : this._finalValue; if (value.ok) { return Promise.resolve(value.value); } else { return Promise.reject(value.error); } } else { const deferred = new DeferredPromise(); this._unsatisfiedConsumers.push(deferred); return deferred.p; } } } const _AsyncIterableProducer = class _AsyncIterableProducer { constructor(executor, _onReturn) { this._onReturn = _onReturn; this._producerConsumer = new ProducerConsumer(); this._iterator = { next: () => this._producerConsumer.consume(), return: () => { this._onReturn?.(); return Promise.resolve({ done: true, value: void 0 }); }, throw: async (e) => { this._finishError(e); return { done: true, value: void 0 }; } }; queueMicrotask(async () => { const p = executor({ emitOne: (value) => this._producerConsumer.produce({ ok: true, value: { done: false, value } }), emitMany: (values) => { for (const value of values) { this._producerConsumer.produce({ ok: true, value: { done: false, value } }); } }, reject: (error) => this._finishError(error) }); if (!this._producerConsumer.hasFinalValue) { try { await p; this._finishOk(); } catch (error) { this._finishError(error); } } }); } static fromArray(items) { return new _AsyncIterableProducer((writer) => { writer.emitMany(items); }); } static fromPromise(promise) { return new _AsyncIterableProducer(async (emitter) => { emitter.emitMany(await promise); }); } static fromPromisesResolveOrder(promises) { return new _AsyncIterableProducer(async (emitter) => { await Promise.all(promises.map(async (p) => emitter.emitOne(await p))); }); } static merge(iterables) { return new _AsyncIterableProducer(async (emitter) => { await Promise.all(iterables.map(async (iterable) => { for await (const item of iterable) { emitter.emitOne(item); } })); }); } static map(iterable, mapFn) { return new _AsyncIterableProducer(async (emitter) => { for await (const item of iterable) { emitter.emitOne(mapFn(item)); } }); } map(mapFn) { return _AsyncIterableProducer.map(this, mapFn); } static coalesce(iterable) { return _AsyncIterableProducer.filter(iterable, (item) => !!item); } coalesce() { return _AsyncIterableProducer.coalesce(this); } static filter(iterable, filterFn) { return new _AsyncIterableProducer(async (emitter) => { for await (const item of iterable) { if (filterFn(item)) { emitter.emitOne(item); } } }); } filter(filterFn) { return _AsyncIterableProducer.filter(this, filterFn); } _finishOk() { if (!this._producerConsumer.hasFinalValue) { this._producerConsumer.produceFinal({ ok: true, value: { done: true, value: void 0 } }); } } _finishError(error) { if (!this._producerConsumer.hasFinalValue) { this._producerConsumer.produceFinal({ ok: false, error }); } } [Symbol.asyncIterator]() { return this._iterator; } }; _AsyncIterableProducer.EMPTY = _AsyncIterableProducer.fromArray([]); let AsyncIterableProducer = _AsyncIterableProducer; class CancelableAsyncIterableProducer extends AsyncIterableProducer { constructor(_source, executor) { super(executor); this._source = _source; } cancel() { this._source.cancel(); } } function identity(t) { return t; } class LRUCachedFunction { constructor(arg1, arg2) { this.lastCache = void 0; this.lastArgKey = void 0; if (typeof arg1 === "function") { this._fn = arg1; this._computeKey = identity; } else { this._fn = arg2; this._computeKey = arg1.getCacheKey; } } get(arg) { const key = this._computeKey(arg); if (this.lastArgKey !== key) { this.lastArgKey = key; this.lastCache = this._fn(arg); } return this.lastCache; } } class CachedFunction { get cachedValues() { return this._map; } constructor(arg1, arg2) { this._map = /* @__PURE__ */ new Map(); this._map2 = /* @__PURE__ */ new Map(); if (typeof arg1 === "function") { this._fn = arg1; this._computeKey = identity; } else { this._fn = arg2; this._computeKey = arg1.getCacheKey; } } get(arg) { const key = this._computeKey(arg); if (this._map2.has(key)) { return this._map2.get(key); } const value = this._fn(arg); this._map.set(arg, value); this._map2.set(key, value); return value; } } var LazyValueState; (function(LazyValueState2) { LazyValueState2[LazyValueState2["Uninitialized"] = 0] = "Uninitialized"; LazyValueState2[LazyValueState2["Running"] = 1] = "Running"; LazyValueState2[LazyValueState2["Completed"] = 2] = "Completed"; })(LazyValueState || (LazyValueState = {})); class Lazy { constructor(executor) { this.executor = executor; this._state = LazyValueState.Uninitialized; } /** * Get the wrapped value. * * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value */ get value() { if (this._state === LazyValueState.Uninitialized) { this._state = LazyValueState.Running; try { this._value = this.executor(); } catch (err) { this._error = err; } finally { this._state = LazyValueState.Completed; } } else if (this._state === LazyValueState.Running) { throw new Error("Cannot read the value of a lazy that is being initialized"); } if (this._error) { throw this._error; } return this._value; } /** * Get the wrapped value without forcing evaluation. */ get rawValue() { return this._value; } } function isFalsyOrWhitespace(str) { if (!str || typeof str !== "string") { return true; } return str.trim().length === 0; } const _formatRegexp = /{(\d+)}/g; function format(value, ...args) { if (args.length === 0) { return value; } return value.replace(_formatRegexp, function(match2, group) { const idx = parseInt(group, 10); return isNaN(idx) || idx < 0 || idx >= args.length ? match2 : args[idx]; }); } function htmlAttributeEncodeValue(value) { return value.replace(/[<>"'&]/g, (ch) => { switch (ch) { case "<": return "<"; case ">": return ">"; case '"': return """; case "'": return "'"; case "&": return "&"; } return ch; }); } function escape$2(html2) { return html2.replace(/[<>&]/g, function(match2) { switch (match2) { case "<": return "<"; case ">": return ">"; case "&": return "&"; default: return match2; } }); } function escapeRegExpCharacters(value) { return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, "\\$&"); } function trim(haystack, needle = " ") { const trimmed = ltrim(haystack, needle); return rtrim$1(trimmed, needle); } function ltrim(haystack, needle) { if (!haystack || !needle) { return haystack; } const needleLen = needle.length; if (needleLen === 0 || haystack.length === 0) { return haystack; } let offset = 0; while (haystack.indexOf(needle, offset) === offset) { offset = offset + needleLen; } return haystack.substring(offset); } function rtrim$1(haystack, needle) { if (!haystack || !needle) { return haystack; } const needleLen = needle.length, haystackLen = haystack.length; if (needleLen === 0 || haystackLen === 0) { return haystack; } let offset = haystackLen, idx = -1; while (true) { idx = haystack.lastIndexOf(needle, offset - 1); if (idx === -1 || idx + needleLen !== offset) { break; } if (idx === 0) { return ""; } offset = idx; } return haystack.substring(0, offset); } function convertSimple2RegExpPattern(pattern) { return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, "\\$&").replace(/[\*]/g, ".*"); } function createRegExp(searchString, isRegex, options = {}) { if (!searchString) { throw new Error("Cannot create regex from empty string"); } if (!isRegex) { searchString = escapeRegExpCharacters(searchString); } if (options.wholeWord) { if (!/\B/.test(searchString.charAt(0))) { searchString = "\\b" + searchString; } if (!/\B/.test(searchString.charAt(searchString.length - 1))) { searchString = searchString + "\\b"; } } let modifiers = ""; if (options.global) { modifiers += "g"; } if (!options.matchCase) { modifiers += "i"; } if (options.multiline) { modifiers += "m"; } if (options.unicode) { modifiers += "u"; } return new RegExp(searchString, modifiers); } function regExpLeadsToEndlessLoop(regexp) { if (regexp.source === "^" || regexp.source === "^$" || regexp.source === "$" || regexp.source === "^\\s*$") { return false; } const match2 = regexp.exec(""); return !!(match2 && regexp.lastIndex === 0); } function splitLines(str) { return str.split(/\r\n|\r|\n/); } function firstNonWhitespaceIndex(str) { for (let i2 = 0, len = str.length; i2 < len; i2++) { const chCode = str.charCodeAt(i2); if (chCode !== 32 && chCode !== 9) { return i2; } } return -1; } function getLeadingWhitespace(str, start = 0, end = str.length) { for (let i2 = start; i2 < end; i2++) { const chCode = str.charCodeAt(i2); if (chCode !== 32 && chCode !== 9) { return str.substring(start, i2); } } return str.substring(start, end); } function lastNonWhitespaceIndex(str, startIndex = str.length - 1) { for (let i2 = startIndex; i2 >= 0; i2--) { const chCode = str.charCodeAt(i2); if (chCode !== 32 && chCode !== 9) { return i2; } } return -1; } function compare(a, b) { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; } } function compareSubstring(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) { for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) { const codeA = a.charCodeAt(aStart); const codeB = b.charCodeAt(bStart); if (codeA < codeB) { return -1; } else if (codeA > codeB) { return 1; } } const aLen = aEnd - aStart; const bLen = bEnd - bStart; if (aLen < bLen) { return -1; } else if (aLen > bLen) { return 1; } return 0; } function compareIgnoreCase(a, b) { return compareSubstringIgnoreCase(a, b, 0, a.length, 0, b.length); } function compareSubstringIgnoreCase(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) { for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) { let codeA = a.charCodeAt(aStart); let codeB = b.charCodeAt(bStart); if (codeA === codeB) { continue; } if (codeA >= 128 || codeB >= 128) { return compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd); } if (isLowerAsciiLetter(codeA)) { codeA -= 32; } if (isLowerAsciiLetter(codeB)) { codeB -= 32; } const diff = codeA - codeB; if (diff === 0) { continue; } return diff; } const aLen = aEnd - aStart; const bLen = bEnd - bStart; if (aLen < bLen) { return -1; } else if (aLen > bLen) { return 1; } return 0; } function isAsciiDigit(code) { return code >= 48 && code <= 57; } function isLowerAsciiLetter(code) { return code >= 97 && code <= 122; } function isUpperAsciiLetter(code) { return code >= 65 && code <= 90; } function equalsIgnoreCase(a, b) { return a.length === b.length && compareSubstringIgnoreCase(a, b) === 0; } function startsWithIgnoreCase(str, candidate) { const candidateLength = candidate.length; if (candidate.length > str.length) { return false; } return compareSubstringIgnoreCase(str, candidate, 0, candidateLength) === 0; } function commonPrefixLength(a, b) { const len = Math.min(a.length, b.length); let i2; for (i2 = 0; i2 < len; i2++) { if (a.charCodeAt(i2) !== b.charCodeAt(i2)) { return i2; } } return len; } function commonSuffixLength(a, b) { const len = Math.min(a.length, b.length); let i2; const aLastIndex = a.length - 1; const bLastIndex = b.length - 1; for (i2 = 0; i2 < len; i2++) { if (a.charCodeAt(aLastIndex - i2) !== b.charCodeAt(bLastIndex - i2)) { return i2; } } return len; } function isHighSurrogate(charCode) { return 55296 <= charCode && charCode <= 56319; } function isLowSurrogate(charCode) { return 56320 <= charCode && charCode <= 57343; } function computeCodePoint(highSurrogate, lowSurrogate) { return (highSurrogate - 55296 << 10) + (lowSurrogate - 56320) + 65536; } function getNextCodePoint(str, len, offset) { const charCode = str.charCodeAt(offset); if (isHighSurrogate(charCode) && offset + 1 < len) { const nextCharCode = str.charCodeAt(offset + 1); if (isLowSurrogate(nextCharCode)) { return computeCodePoint(charCode, nextCharCode); } } return charCode; } function getPrevCodePoint(str, offset) { const charCode = str.charCodeAt(offset - 1); if (isLowSurrogate(charCode) && offset > 1) { const prevCharCode = str.charCodeAt(offset - 2); if (isHighSurrogate(prevCharCode)) { return computeCodePoint(prevCharCode, charCode); } } return charCode; } class CodePointIterator { get offset() { return this._offset; } constructor(str, offset = 0) { this._str = str; this._len = str.length; this._offset = offset; } setOffset(offset) { this._offset = offset; } prevCodePoint() { const codePoint = getPrevCodePoint(this._str, this._offset); this._offset -= codePoint >= 65536 ? 2 : 1; return codePoint; } nextCodePoint() { const codePoint = getNextCodePoint(this._str, this._len, this._offset); this._offset += codePoint >= 65536 ? 2 : 1; return codePoint; } eol() { return this._offset >= this._len; } } class GraphemeIterator { get offset() { return this._iterator.offset; } constructor(str, offset = 0) { this._iterator = new CodePointIterator(str, offset); } nextGraphemeLength() { const graphemeBreakTree = GraphemeBreakTree.getInstance(); const iterator = this._iterator; const initialOffset = iterator.offset; let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.nextCodePoint()); while (!iterator.eol()) { const offset = iterator.offset; const nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.nextCodePoint()); if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) { iterator.setOffset(offset); break; } graphemeBreakType = nextGraphemeBreakType; } return iterator.offset - initialOffset; } prevGraphemeLength() { const graphemeBreakTree = GraphemeBreakTree.getInstance(); const iterator = this._iterator; const initialOffset = iterator.offset; let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.prevCodePoint()); while (iterator.offset > 0) { const offset = iterator.offset; const prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator.prevCodePoint()); if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) { iterator.setOffset(offset); break; } graphemeBreakType = prevGraphemeBreakType; } return initialOffset - iterator.offset; } eol() { return this._iterator.eol(); } } function nextCharLength(str, initialOffset) { const iterator = new GraphemeIterator(str, initialOffset); return iterator.nextGraphemeLength(); } function prevCharLength(str, initialOffset) { const iterator = new GraphemeIterator(str, initialOffset); return iterator.prevGraphemeLength(); } function getCharContainingOffset(str, offset) { if (offset > 0 && isLowSurrogate(str.charCodeAt(offset))) { offset--; } const endOffset = offset + nextCharLength(str, offset); const startOffset = endOffset - prevCharLength(str, endOffset); return [startOffset, endOffset]; } let CONTAINS_RTL = void 0; function makeContainsRtl() { return /(?:[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u0710\u0712-\u072F\u074D-\u07A5\u07B1-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDC7\uFDF0-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE35\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDD23\uDE80-\uDEA9\uDEAD-\uDF45\uDF51-\uDF81\uDF86-\uDFF6]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD4B-\uDFFF]|\uD83B[\uDC00-\uDEBB])/; } function containsRTL(str) { if (!CONTAINS_RTL) { CONTAINS_RTL = makeContainsRtl(); } return CONTAINS_RTL.test(str); } const IS_BASIC_ASCII = /^[\t\n\r\x20-\x7E]*$/; function isBasicASCII(str) { return IS_BASIC_ASCII.test(str); } const UNUSUAL_LINE_TERMINATORS = /[\u2028\u2029]/; function containsUnusualLineTerminators(str) { return UNUSUAL_LINE_TERMINATORS.test(str); } function isFullWidthCharacter(charCode) { return charCode >= 11904 && charCode <= 55215 || charCode >= 63744 && charCode <= 64255 || charCode >= 65281 && charCode <= 65374; } function isEmojiImprecise(x) { return x >= 127462 && x <= 127487 || x === 8986 || x === 8987 || x === 9200 || x === 9203 || x >= 9728 && x <= 10175 || x === 11088 || x === 11093 || x >= 127744 && x <= 128591 || x >= 128640 && x <= 128764 || x >= 128992 && x <= 129008 || x >= 129280 && x <= 129535 || x >= 129648 && x <= 129782; } const UTF8_BOM_CHARACTER = String.fromCharCode( 65279 /* CharCode.UTF8_BOM */ ); function startsWithUTF8BOM(str) { return !!(str && str.length > 0 && str.charCodeAt(0) === 65279); } function containsUppercaseCharacter(target, ignoreEscapedChars = false) { if (!target) { return false; } if (ignoreEscapedChars) { target = target.replace(/\\./g, ""); } return target.toLowerCase() !== target; } function singleLetterHash(n2) { const LETTERS_CNT = 90 - 65 + 1; n2 = n2 % (2 * LETTERS_CNT); if (n2 < LETTERS_CNT) { return String.fromCharCode(97 + n2); } return String.fromCharCode(65 + n2 - LETTERS_CNT); } function breakBetweenGraphemeBreakType(breakTypeA, breakTypeB) { if (breakTypeA === 0) { return breakTypeB !== 5 && breakTypeB !== 7; } if (breakTypeA === 2) { if (breakTypeB === 3) { return false; } } if (breakTypeA === 4 || breakTypeA === 2 || breakTypeA === 3) { return true; } if (breakTypeB === 4 || breakTypeB === 2 || breakTypeB === 3) { return true; } if (breakTypeA === 8) { if (breakTypeB === 8 || breakTypeB === 9 || breakTypeB === 11 || breakTypeB === 12) { return false; } } if (breakTypeA === 11 || breakTypeA === 9) { if (breakTypeB === 9 || breakTypeB === 10) { return false; } } if (breakTypeA === 12 || breakTypeA === 10) { if (breakTypeB === 10) { return false; } } if (breakTypeB === 5 || breakTypeB === 13) { return false; } if (breakTypeB === 7) { return false; } if (breakTypeA === 1) { return false; } if (breakTypeA === 13 && breakTypeB === 14) { return false; } if (breakTypeA === 6 && breakTypeB === 6) { return false; } return true; } const _GraphemeBreakTree = class _GraphemeBreakTree { static getInstance() { if (!_GraphemeBreakTree._INSTANCE) { _GraphemeBreakTree._INSTANCE = new _GraphemeBreakTree(); } return _GraphemeBreakTree._INSTANCE; } constructor() { this._data = getGraphemeBreakRawData(); } getGraphemeBreakType(codePoint) { if (codePoint < 32) { if (codePoint === 10) { return 3; } if (codePoint === 13) { return 2; } return 4; } if (codePoint < 127) { return 0; } const data = this._data; const nodeCount = data.length / 3; let nodeIndex = 1; while (nodeIndex <= nodeCount) { if (codePoint < data[3 * nodeIndex]) { nodeIndex = 2 * nodeIndex; } else if (codePoint > data[3 * nodeIndex + 1]) { nodeIndex = 2 * nodeIndex + 1; } else { return data[3 * nodeIndex + 2]; } } return 0; } }; _GraphemeBreakTree._INSTANCE = null; let GraphemeBreakTree = _GraphemeBreakTree; function getGraphemeBreakRawData() { return JSON.parse("[0,0,0,51229,51255,12,44061,44087,12,127462,127487,6,7083,7085,5,47645,47671,12,54813,54839,12,128678,128678,14,3270,3270,5,9919,9923,14,45853,45879,12,49437,49463,12,53021,53047,12,71216,71218,7,128398,128399,14,129360,129374,14,2519,2519,5,4448,4519,9,9742,9742,14,12336,12336,14,44957,44983,12,46749,46775,12,48541,48567,12,50333,50359,12,52125,52151,12,53917,53943,12,69888,69890,5,73018,73018,5,127990,127990,14,128558,128559,14,128759,128760,14,129653,129655,14,2027,2035,5,2891,2892,7,3761,3761,5,6683,6683,5,8293,8293,4,9825,9826,14,9999,9999,14,43452,43453,5,44509,44535,12,45405,45431,12,46301,46327,12,47197,47223,12,48093,48119,12,48989,49015,12,49885,49911,12,50781,50807,12,51677,51703,12,52573,52599,12,53469,53495,12,54365,54391,12,65279,65279,4,70471,70472,7,72145,72147,7,119173,119179,5,127799,127818,14,128240,128244,14,128512,128512,14,128652,128652,14,128721,128722,14,129292,129292,14,129445,129450,14,129734,129743,14,1476,1477,5,2366,2368,7,2750,2752,7,3076,3076,5,3415,3415,5,4141,4144,5,6109,6109,5,6964,6964,5,7394,7400,5,9197,9198,14,9770,9770,14,9877,9877,14,9968,9969,14,10084,10084,14,43052,43052,5,43713,43713,5,44285,44311,12,44733,44759,12,45181,45207,12,45629,45655,12,46077,46103,12,46525,46551,12,46973,46999,12,47421,47447,12,47869,47895,12,48317,48343,12,48765,48791,12,49213,49239,12,49661,49687,12,50109,50135,12,50557,50583,12,51005,51031,12,51453,51479,12,51901,51927,12,52349,52375,12,52797,52823,12,53245,53271,12,53693,53719,12,54141,54167,12,54589,54615,12,55037,55063,12,69506,69509,5,70191,70193,5,70841,70841,7,71463,71467,5,72330,72342,5,94031,94031,5,123628,123631,5,127763,127765,14,127941,127941,14,128043,128062,14,128302,128317,14,128465,128467,14,128539,128539,14,128640,128640,14,128662,128662,14,128703,128703,14,128745,128745,14,129004,129007,14,129329,129330,14,129402,129402,14,129483,129483,14,129686,129704,14,130048,131069,14,173,173,4,1757,1757,1,2200,2207,5,2434,2435,7,2631,2632,5,2817,2817,5,3008,3008,5,3201,3201,5,3387,3388,5,3542,3542,5,3902,3903,7,4190,4192,5,6002,6003,5,6439,6440,5,6765,6770,7,7019,7027,5,7154,7155,7,8205,8205,13,8505,8505,14,9654,9654,14,9757,9757,14,9792,9792,14,9852,9853,14,9890,9894,14,9937,9937,14,9981,9981,14,10035,10036,14,11035,11036,14,42654,42655,5,43346,43347,7,43587,43587,5,44006,44007,7,44173,44199,12,44397,44423,12,44621,44647,12,44845,44871,12,45069,45095,12,45293,45319,12,45517,45543,12,45741,45767,12,45965,45991,12,46189,46215,12,46413,46439,12,46637,46663,12,46861,46887,12,47085,47111,12,47309,47335,12,47533,47559,12,47757,47783,12,47981,48007,12,48205,48231,12,48429,48455,12,48653,48679,12,48877,48903,12,49101,49127,12,49325,49351,12,49549,49575,12,49773,49799,12,49997,50023,12,50221,50247,12,50445,50471,12,50669,50695,12,50893,50919,12,51117,51143,12,51341,51367,12,51565,51591,12,51789,51815,12,52013,52039,12,52237,52263,12,52461,52487,12,52685,52711,12,52909,52935,12,53133,53159,12,53357,53383,12,53581,53607,12,53805,53831,12,54029,54055,12,54253,54279,12,54477,54503,12,54701,54727,12,54925,54951,12,55149,55175,12,68101,68102,5,69762,69762,7,70067,70069,7,70371,70378,5,70720,70721,7,71087,71087,5,71341,71341,5,71995,71996,5,72249,72249,7,72850,72871,5,73109,73109,5,118576,118598,5,121505,121519,5,127245,127247,14,127568,127569,14,127777,127777,14,127872,127891,14,127956,127967,14,128015,128016,14,128110,128172,14,128259,128259,14,128367,128368,14,128424,128424,14,128488,128488,14,128530,128532,14,128550,128551,14,128566,128566,14,128647,128647,14,128656,128656,14,128667,128673,14,128691,128693,14,128715,128715,14,128728,128732,14,128752,128752,14,128765,128767,14,129096,129103,14,129311,129311,14,129344,129349,14,129394,129394,14,129413,129425,14,129466,129471,14,129511,129535,14,129664,129666,14,129719,129722,14,129760,129767,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2307,2307,7,2382,2383,7,2497,2500,5,2563,2563,7,2677,2677,5,2763,2764,7,2879,2879,5,2914,2915,5,3021,3021,5,3142,3144,5,3263,3263,5,3285,3286,5,3398,3400,7,3530,3530,5,3633,3633,5,3864,3865,5,3974,3975,5,4155,4156,7,4229,4230,5,5909,5909,7,6078,6085,7,6277,6278,5,6451,6456,7,6744,6750,5,6846,6846,5,6972,6972,5,7074,7077,5,7146,7148,7,7222,7223,5,7416,7417,5,8234,8238,4,8417,8417,5,9000,9000,14,9203,9203,14,9730,9731,14,9748,9749,14,9762,9763,14,9776,9783,14,9800,9811,14,9831,9831,14,9872,9873,14,9882,9882,14,9900,9903,14,9929,9933,14,9941,9960,14,9974,9974,14,9989,9989,14,10006,10006,14,10062,10062,14,10160,10160,14,11647,11647,5,12953,12953,14,43019,43019,5,43232,43249,5,43443,43443,5,43567,43568,7,43696,43696,5,43765,43765,7,44013,44013,5,44117,44143,12,44229,44255,12,44341,44367,12,44453,44479,12,44565,44591,12,44677,44703,12,44789,44815,12,44901,44927,12,45013,45039,12,45125,45151,12,45237,45263,12,45349,45375,12,45461,45487,12,45573,45599,12,45685,45711,12,45797,45823,12,45909,45935,12,46021,46047,12,46133,46159,12,46245,46271,12,46357,46383,12,46469,46495,12,46581,46607,12,46693,46719,12,46805,46831,12,46917,46943,12,47029,47055,12,47141,47167,12,47253,47279,12,47365,47391,12,47477,47503,12,47589,47615,12,47701,47727,12,47813,47839,12,47925,47951,12,48037,48063,12,48149,48175,12,48261,48287,12,48373,48399,12,48485,48511,12,48597,48623,12,48709,48735,12,48821,48847,12,48933,48959,12,49045,49071,12,49157,49183,12,49269,49295,12,49381,49407,12,49493,49519,12,49605,49631,12,49717,49743,12,49829,49855,12,49941,49967,12,50053,50079,12,50165,50191,12,50277,50303,12,50389,50415,12,50501,50527,12,50613,50639,12,50725,50751,12,50837,50863,12,50949,50975,12,51061,51087,12,51173,51199,12,51285,51311,12,51397,51423,12,51509,51535,12,51621,51647,12,51733,51759,12,51845,51871,12,51957,51983,12,52069,52095,12,52181,52207,12,52293,52319,12,52405,52431,12,52517,52543,12,52629,52655,12,52741,52767,12,52853,52879,12,52965,52991,12,53077,53103,12,53189,53215,12,53301,53327,12,53413,53439,12,53525,53551,12,53637,53663,12,53749,53775,12,53861,53887,12,53973,53999,12,54085,54111,12,54197,54223,12,54309,54335,12,54421,54447,12,54533,54559,12,54645,54671,12,54757,54783,12,54869,54895,12,54981,55007,12,55093,55119,12,55243,55291,10,66045,66045,5,68325,68326,5,69688,69702,5,69817,69818,5,69957,69958,7,70089,70092,5,70198,70199,5,70462,70462,5,70502,70508,5,70750,70750,5,70846,70846,7,71100,71101,5,71230,71230,7,71351,71351,5,71737,71738,5,72000,72000,7,72160,72160,5,72273,72278,5,72752,72758,5,72882,72883,5,73031,73031,5,73461,73462,7,94192,94193,7,119149,119149,7,121403,121452,5,122915,122916,5,126980,126980,14,127358,127359,14,127535,127535,14,127759,127759,14,127771,127771,14,127792,127793,14,127825,127867,14,127897,127899,14,127945,127945,14,127985,127986,14,128000,128007,14,128021,128021,14,128066,128100,14,128184,128235,14,128249,128252,14,128266,128276,14,128335,128335,14,128379,128390,14,128407,128419,14,128444,128444,14,128481,128481,14,128499,128499,14,128526,128526,14,128536,128536,14,128543,128543,14,128556,128556,14,128564,128564,14,128577,128580,14,128643,128645,14,128649,128649,14,128654,128654,14,128660,128660,14,128664,128664,14,128675,128675,14,128686,128689,14,128695,128696,14,128705,128709,14,128717,128719,14,128725,128725,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129009,129023,14,129160,129167,14,129296,129304,14,129320,129327,14,129340,129342,14,129356,129356,14,129388,129392,14,129399,129400,14,129404,129407,14,129432,129442,14,129454,129455,14,129473,129474,14,129485,129487,14,129648,129651,14,129659,129660,14,129671,129679,14,129709,129711,14,129728,129730,14,129751,129753,14,129776,129782,14,917505,917505,4,917760,917999,5,10,10,3,127,159,4,768,879,5,1471,1471,5,1536,1541,1,1648,1648,5,1767,1768,5,1840,1866,5,2070,2073,5,2137,2139,5,2274,2274,1,2363,2363,7,2377,2380,7,2402,2403,5,2494,2494,5,2507,2508,7,2558,2558,5,2622,2624,7,2641,2641,5,2691,2691,7,2759,2760,5,2786,2787,5,2876,2876,5,2881,2884,5,2901,2902,5,3006,3006,5,3014,3016,7,3072,3072,5,3134,3136,5,3157,3158,5,3260,3260,5,3266,3266,5,3274,3275,7,3328,3329,5,3391,3392,7,3405,3405,5,3457,3457,5,3536,3537,7,3551,3551,5,3636,3642,5,3764,3772,5,3895,3895,5,3967,3967,7,3993,4028,5,4146,4151,5,4182,4183,7,4226,4226,5,4253,4253,5,4957,4959,5,5940,5940,7,6070,6070,7,6087,6088,7,6158,6158,4,6432,6434,5,6448,6449,7,6679,6680,5,6742,6742,5,6754,6754,5,6783,6783,5,6912,6915,5,6966,6970,5,6978,6978,5,7042,7042,7,7080,7081,5,7143,7143,7,7150,7150,7,7212,7219,5,7380,7392,5,7412,7412,5,8203,8203,4,8232,8232,4,8265,8265,14,8400,8412,5,8421,8432,5,8617,8618,14,9167,9167,14,9200,9200,14,9410,9410,14,9723,9726,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9774,14,9786,9786,14,9794,9794,14,9823,9823,14,9828,9828,14,9833,9850,14,9855,9855,14,9875,9875,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9935,9935,14,9939,9939,14,9962,9962,14,9972,9972,14,9978,9978,14,9986,9986,14,9997,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10133,10135,14,10548,10549,14,11093,11093,14,12330,12333,5,12441,12442,5,42608,42610,5,43010,43010,5,43045,43046,5,43188,43203,7,43302,43309,5,43392,43394,5,43446,43449,5,43493,43493,5,43571,43572,7,43597,43597,7,43703,43704,5,43756,43757,5,44003,44004,7,44009,44010,7,44033,44059,12,44089,44115,12,44145,44171,12,44201,44227,12,44257,44283,12,44313,44339,12,44369,44395,12,44425,44451,12,44481,44507,12,44537,44563,12,44593,44619,12,44649,44675,12,44705,44731,12,44761,44787,12,44817,44843,12,44873,44899,12,44929,44955,12,44985,45011,12,45041,45067,12,45097,45123,12,45153,45179,12,45209,45235,12,45265,45291,12,45321,45347,12,45377,45403,12,45433,45459,12,45489,45515,12,45545,45571,12,45601,45627,12,45657,45683,12,45713,45739,12,45769,45795,12,45825,45851,12,45881,45907,12,45937,45963,12,45993,46019,12,46049,46075,12,46105,46131,12,46161,46187,12,46217,46243,12,46273,46299,12,46329,46355,12,46385,46411,12,46441,46467,12,46497,46523,12,46553,46579,12,46609,46635,12,46665,46691,12,46721,46747,12,46777,46803,12,46833,46859,12,46889,46915,12,46945,46971,12,47001,47027,12,47057,47083,12,47113,47139,12,47169,47195,12,47225,47251,12,47281,47307,12,47337,47363,12,47393,47419,12,47449,47475,12,47505,47531,12,47561,47587,12,47617,47643,12,47673,47699,12,47729,47755,12,47785,47811,12,47841,47867,12,47897,47923,12,47953,47979,12,48009,48035,12,48065,48091,12,48121,48147,12,48177,48203,12,48233,48259,12,48289,48315,12,48345,48371,12,48401,48427,12,48457,48483,12,48513,48539,12,48569,48595,12,48625,48651,12,48681,48707,12,48737,48763,12,48793,48819,12,48849,48875,12,48905,48931,12,48961,48987,12,49017,49043,12,49073,49099,12,49129,49155,12,49185,49211,12,49241,49267,12,49297,49323,12,49353,49379,12,49409,49435,12,49465,49491,12,49521,49547,12,49577,49603,12,49633,49659,12,49689,49715,12,49745,49771,12,49801,49827,12,49857,49883,12,49913,49939,12,49969,49995,12,50025,50051,12,50081,50107,12,50137,50163,12,50193,50219,12,50249,50275,12,50305,50331,12,50361,50387,12,50417,50443,12,50473,50499,12,50529,50555,12,50585,50611,12,50641,50667,12,50697,50723,12,50753,50779,12,50809,50835,12,50865,50891,12,50921,50947,12,50977,51003,12,51033,51059,12,51089,51115,12,51145,51171,12,51201,51227,12,51257,51283,12,51313,51339,12,51369,51395,12,51425,51451,12,51481,51507,12,51537,51563,12,51593,51619,12,51649,51675,12,51705,51731,12,51761,51787,12,51817,51843,12,51873,51899,12,51929,51955,12,51985,52011,12,52041,52067,12,52097,52123,12,52153,52179,12,52209,52235,12,52265,52291,12,52321,52347,12,52377,52403,12,52433,52459,12,52489,52515,12,52545,52571,12,52601,52627,12,52657,52683,12,52713,52739,12,52769,52795,12,52825,52851,12,52881,52907,12,52937,52963,12,52993,53019,12,53049,53075,12,53105,53131,12,53161,53187,12,53217,53243,12,53273,53299,12,53329,53355,12,53385,53411,12,53441,53467,12,53497,53523,12,53553,53579,12,53609,53635,12,53665,53691,12,53721,53747,12,53777,53803,12,53833,53859,12,53889,53915,12,53945,53971,12,54001,54027,12,54057,54083,12,54113,54139,12,54169,54195,12,54225,54251,12,54281,54307,12,54337,54363,12,54393,54419,12,54449,54475,12,54505,54531,12,54561,54587,12,54617,54643,12,54673,54699,12,54729,54755,12,54785,54811,12,54841,54867,12,54897,54923,12,54953,54979,12,55009,55035,12,55065,55091,12,55121,55147,12,55177,55203,12,65024,65039,5,65520,65528,4,66422,66426,5,68152,68154,5,69291,69292,5,69633,69633,5,69747,69748,5,69811,69814,5,69826,69826,5,69932,69932,7,70016,70017,5,70079,70080,7,70095,70095,5,70196,70196,5,70367,70367,5,70402,70403,7,70464,70464,5,70487,70487,5,70709,70711,7,70725,70725,7,70833,70834,7,70843,70844,7,70849,70849,7,71090,71093,5,71103,71104,5,71227,71228,7,71339,71339,5,71344,71349,5,71458,71461,5,71727,71735,5,71985,71989,7,71998,71998,5,72002,72002,7,72154,72155,5,72193,72202,5,72251,72254,5,72281,72283,5,72344,72345,5,72766,72766,7,72874,72880,5,72885,72886,5,73023,73029,5,73104,73105,5,73111,73111,5,92912,92916,5,94095,94098,5,113824,113827,4,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,125252,125258,5,127183,127183,14,127340,127343,14,127377,127386,14,127491,127503,14,127548,127551,14,127744,127756,14,127761,127761,14,127769,127769,14,127773,127774,14,127780,127788,14,127796,127797,14,127820,127823,14,127869,127869,14,127894,127895,14,127902,127903,14,127943,127943,14,127947,127950,14,127972,127972,14,127988,127988,14,127992,127994,14,128009,128011,14,128019,128019,14,128023,128041,14,128064,128064,14,128102,128107,14,128174,128181,14,128238,128238,14,128246,128247,14,128254,128254,14,128264,128264,14,128278,128299,14,128329,128330,14,128348,128359,14,128371,128377,14,128392,128393,14,128401,128404,14,128421,128421,14,128433,128434,14,128450,128452,14,128476,128478,14,128483,128483,14,128495,128495,14,128506,128506,14,128519,128520,14,128528,128528,14,128534,128534,14,128538,128538,14,128540,128542,14,128544,128549,14,128552,128555,14,128557,128557,14,128560,128563,14,128565,128565,14,128567,128576,14,128581,128591,14,128641,128642,14,128646,128646,14,128648,128648,14,128650,128651,14,128653,128653,14,128655,128655,14,128657,128659,14,128661,128661,14,128663,128663,14,128665,128666,14,128674,128674,14,128676,128677,14,128679,128685,14,128690,128690,14,128694,128694,14,128697,128702,14,128704,128704,14,128710,128714,14,128716,128716,14,128720,128720,14,128723,128724,14,128726,128727,14,128733,128735,14,128742,128744,14,128746,128746,14,128749,128751,14,128753,128754,14,128756,128758,14,128761,128761,14,128763,128764,14,128884,128895,14,128992,129003,14,129008,129008,14,129036,129039,14,129114,129119,14,129198,129279,14,129293,129295,14,129305,129310,14,129312,129319,14,129328,129328,14,129331,129338,14,129343,129343,14,129351,129355,14,129357,129359,14,129375,129387,14,129393,129393,14,129395,129398,14,129401,129401,14,129403,129403,14,129408,129412,14,129426,129431,14,129443,129444,14,129451,129453,14,129456,129465,14,129472,129472,14,129475,129482,14,129484,129484,14,129488,129510,14,129536,129647,14,129652,129652,14,129656,129658,14,129661,129663,14,129667,129670,14,129680,129685,14,129705,129708,14,129712,129718,14,129723,129727,14,129731,129733,14,129744,129750,14,129754,129759,14,129768,129775,14,129783,129791,14,917504,917504,4,917506,917535,4,917632,917759,4,918000,921599,4,0,9,4,11,12,4,14,31,4,169,169,14,174,174,14,1155,1159,5,1425,1469,5,1473,1474,5,1479,1479,5,1552,1562,5,1611,1631,5,1750,1756,5,1759,1764,5,1770,1773,5,1809,1809,5,1958,1968,5,2045,2045,5,2075,2083,5,2089,2093,5,2192,2193,1,2250,2273,5,2275,2306,5,2362,2362,5,2364,2364,5,2369,2376,5,2381,2381,5,2385,2391,5,2433,2433,5,2492,2492,5,2495,2496,7,2503,2504,7,2509,2509,5,2530,2531,5,2561,2562,5,2620,2620,5,2625,2626,5,2635,2637,5,2672,2673,5,2689,2690,5,2748,2748,5,2753,2757,5,2761,2761,7,2765,2765,5,2810,2815,5,2818,2819,7,2878,2878,5,2880,2880,7,2887,2888,7,2893,2893,5,2903,2903,5,2946,2946,5,3007,3007,7,3009,3010,7,3018,3020,7,3031,3031,5,3073,3075,7,3132,3132,5,3137,3140,7,3146,3149,5,3170,3171,5,3202,3203,7,3262,3262,7,3264,3265,7,3267,3268,7,3271,3272,7,3276,3277,5,3298,3299,5,3330,3331,7,3390,3390,5,3393,3396,5,3402,3404,7,3406,3406,1,3426,3427,5,3458,3459,7,3535,3535,5,3538,3540,5,3544,3550,7,3570,3571,7,3635,3635,7,3655,3662,5,3763,3763,7,3784,3789,5,3893,3893,5,3897,3897,5,3953,3966,5,3968,3972,5,3981,3991,5,4038,4038,5,4145,4145,7,4153,4154,5,4157,4158,5,4184,4185,5,4209,4212,5,4228,4228,7,4237,4237,5,4352,4447,8,4520,4607,10,5906,5908,5,5938,5939,5,5970,5971,5,6068,6069,5,6071,6077,5,6086,6086,5,6089,6099,5,6155,6157,5,6159,6159,5,6313,6313,5,6435,6438,7,6441,6443,7,6450,6450,5,6457,6459,5,6681,6682,7,6741,6741,7,6743,6743,7,6752,6752,5,6757,6764,5,6771,6780,5,6832,6845,5,6847,6862,5,6916,6916,7,6965,6965,5,6971,6971,7,6973,6977,7,6979,6980,7,7040,7041,5,7073,7073,7,7078,7079,7,7082,7082,7,7142,7142,5,7144,7145,5,7149,7149,5,7151,7153,5,7204,7211,7,7220,7221,7,7376,7378,5,7393,7393,7,7405,7405,5,7415,7415,7,7616,7679,5,8204,8204,5,8206,8207,4,8233,8233,4,8252,8252,14,8288,8292,4,8294,8303,4,8413,8416,5,8418,8420,5,8482,8482,14,8596,8601,14,8986,8987,14,9096,9096,14,9193,9196,14,9199,9199,14,9201,9202,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,9729,14,9732,9732,14,9735,9741,14,9743,9744,14,9746,9746,14,9750,9751,14,9753,9756,14,9758,9759,14,9761,9761,14,9764,9765,14,9767,9769,14,9771,9773,14,9775,9775,14,9784,9785,14,9787,9791,14,9793,9793,14,9795,9799,14,9812,9822,14,9824,9824,14,9827,9827,14,9829,9830,14,9832,9832,14,9851,9851,14,9854,9854,14,9856,9861,14,9874,9874,14,9876,9876,14,9878,9879,14,9881,9881,14,9883,9884,14,9888,9889,14,9895,9895,14,9898,9899,14,9904,9905,14,9917,9918,14,9924,9925,14,9928,9928,14,9934,9934,14,9936,9936,14,9938,9938,14,9940,9940,14,9961,9961,14,9963,9967,14,9970,9971,14,9973,9973,14,9975,9977,14,9979,9980,14,9982,9985,14,9987,9988,14,9992,9996,14,9998,9998,14,10000,10001,14,10004,10004,14,10013,10013,14,10024,10024,14,10052,10052,14,10060,10060,14,10067,10069,14,10083,10083,14,10085,10087,14,10145,10145,14,10175,10175,14,11013,11015,14,11088,11088,14,11503,11505,5,11744,11775,5,12334,12335,5,12349,12349,14,12951,12951,14,42607,42607,5,42612,42621,5,42736,42737,5,43014,43014,5,43043,43044,7,43047,43047,7,43136,43137,7,43204,43205,5,43263,43263,5,43335,43345,5,43360,43388,8,43395,43395,7,43444,43445,7,43450,43451,7,43454,43456,7,43561,43566,5,43569,43570,5,43573,43574,5,43596,43596,5,43644,43644,5,43698,43700,5,43710,43711,5,43755,43755,7,43758,43759,7,43766,43766,5,44005,44005,5,44008,44008,5,44012,44012,7,44032,44032,11,44060,44060,11,44088,44088,11,44116,44116,11,44144,44144,11,44172,44172,11,44200,44200,11,44228,44228,11,44256,44256,11,44284,44284,11,44312,44312,11,44340,44340,11,44368,44368,11,44396,44396,11,44424,44424,11,44452,44452,11,44480,44480,11,44508,44508,11,44536,44536,11,44564,44564,11,44592,44592,11,44620,44620,11,44648,44648,11,44676,44676,11,44704,44704,11,44732,44732,11,44760,44760,11,44788,44788,11,44816,44816,11,44844,44844,11,44872,44872,11,44900,44900,11,44928,44928,11,44956,44956,11,44984,44984,11,45012,45012,11,45040,45040,11,45068,45068,11,45096,45096,11,45124,45124,11,45152,45152,11,45180,45180,11,45208,45208,11,45236,45236,11,45264,45264,11,45292,45292,11,45320,45320,11,45348,45348,11,45376,45376,11,45404,45404,11,45432,45432,11,45460,45460,11,45488,45488,11,45516,45516,11,45544,45544,11,45572,45572,11,45600,45600,11,45628,45628,11,45656,45656,11,45684,45684,11,45712,45712,11,45740,45740,11,45768,45768,11,45796,45796,11,45824,45824,11,45852,45852,11,45880,45880,11,45908,45908,11,45936,45936,11,45964,45964,11,45992,45992,11,46020,46020,11,46048,46048,11,46076,46076,11,46104,46104,11,46132,46132,11,46160,46160,11,46188,46188,11,46216,46216,11,46244,46244,11,46272,46272,11,46300,46300,11,46328,46328,11,46356,46356,11,46384,46384,11,46412,46412,11,46440,46440,11,46468,46468,11,46496,46496,11,46524,46524,11,46552,46552,11,46580,46580,11,46608,46608,11,46636,46636,11,46664,46664,11,46692,46692,11,46720,46720,11,46748,46748,11,46776,46776,11,46804,46804,11,46832,46832,11,46860,46860,11,46888,46888,11,46916,46916,11,46944,46944,11,46972,46972,11,47000,47000,11,47028,47028,11,47056,47056,11,47084,47084,11,47112,47112,11,47140,47140,11,47168,47168,11,47196,47196,11,47224,47224,11,47252,47252,11,47280,47280,11,47308,47308,11,47336,47336,11,47364,47364,11,47392,47392,11,47420,47420,11,47448,47448,11,47476,47476,11,47504,47504,11,47532,47532,11,47560,47560,11,47588,47588,11,47616,47616,11,47644,47644,11,47672,47672,11,47700,47700,11,47728,47728,11,47756,47756,11,47784,47784,11,47812,47812,11,47840,47840,11,47868,47868,11,47896,47896,11,47924,47924,11,47952,47952,11,47980,47980,11,48008,48008,11,48036,48036,11,48064,48064,11,48092,48092,11,48120,48120,11,48148,48148,11,48176,48176,11,48204,48204,11,48232,48232,11,48260,48260,11,48288,48288,11,48316,48316,11,48344,48344,11,48372,48372,11,48400,48400,11,48428,48428,11,48456,48456,11,48484,48484,11,48512,48512,11,48540,48540,11,48568,48568,11,48596,48596,11,48624,48624,11,48652,48652,11,48680,48680,11,48708,48708,11,48736,48736,11,48764,48764,11,48792,48792,11,48820,48820,11,48848,48848,11,48876,48876,11,48904,48904,11,48932,48932,11,48960,48960,11,48988,48988,11,49016,49016,11,49044,49044,11,49072,49072,11,49100,49100,11,49128,49128,11,49156,49156,11,49184,49184,11,49212,49212,11,49240,49240,11,49268,49268,11,49296,49296,11,49324,49324,11,49352,49352,11,49380,49380,11,49408,49408,11,49436,49436,11,49464,49464,11,49492,49492,11,49520,49520,11,49548,49548,11,49576,49576,11,49604,49604,11,49632,49632,11,49660,49660,11,49688,49688,11,49716,49716,11,49744,49744,11,49772,49772,11,49800,49800,11,49828,49828,11,49856,49856,11,49884,49884,11,49912,49912,11,49940,49940,11,49968,49968,11,49996,49996,11,50024,50024,11,50052,50052,11,50080,50080,11,50108,50108,11,50136,50136,11,50164,50164,11,50192,50192,11,50220,50220,11,50248,50248,11,50276,50276,11,50304,50304,11,50332,50332,11,50360,50360,11,50388,50388,11,50416,50416,11,50444,50444,11,50472,50472,11,50500,50500,11,50528,50528,11,50556,50556,11,50584,50584,11,50612,50612,11,50640,50640,11,50668,50668,11,50696,50696,11,50724,50724,11,50752,50752,11,50780,50780,11,50808,50808,11,50836,50836,11,50864,50864,11,50892,50892,11,50920,50920,11,50948,50948,11,50976,50976,11,51004,51004,11,51032,51032,11,51060,51060,11,51088,51088,11,51116,51116,11,51144,51144,11,51172,51172,11,51200,51200,11,51228,51228,11,51256,51256,11,51284,51284,11,51312,51312,11,51340,51340,11,51368,51368,11,51396,51396,11,51424,51424,11,51452,51452,11,51480,51480,11,51508,51508,11,51536,51536,11,51564,51564,11,51592,51592,11,51620,51620,11,51648,51648,11,51676,51676,11,51704,51704,11,51732,51732,11,51760,51760,11,51788,51788,11,51816,51816,11,51844,51844,11,51872,51872,11,51900,51900,11,51928,51928,11,51956,51956,11,51984,51984,11,52012,52012,11,52040,52040,11,52068,52068,11,52096,52096,11,52124,52124,11,52152,52152,11,52180,52180,11,52208,52208,11,52236,52236,11,52264,52264,11,52292,52292,11,52320,52320,11,52348,52348,11,52376,52376,11,52404,52404,11,52432,52432,11,52460,52460,11,52488,52488,11,52516,52516,11,52544,52544,11,52572,52572,11,52600,52600,11,52628,52628,11,52656,52656,11,52684,52684,11,52712,52712,11,52740,52740,11,52768,52768,11,52796,52796,11,52824,52824,11,52852,52852,11,52880,52880,11,52908,52908,11,52936,52936,11,52964,52964,11,52992,52992,11,53020,53020,11,53048,53048,11,53076,53076,11,53104,53104,11,53132,53132,11,53160,53160,11,53188,53188,11,53216,53216,11,53244,53244,11,53272,53272,11,53300,53300,11,53328,53328,11,53356,53356,11,53384,53384,11,53412,53412,11,53440,53440,11,53468,53468,11,53496,53496,11,53524,53524,11,53552,53552,11,53580,53580,11,53608,53608,11,53636,53636,11,53664,53664,11,53692,53692,11,53720,53720,11,53748,53748,11,53776,53776,11,53804,53804,11,53832,53832,11,53860,53860,11,53888,53888,11,53916,53916,11,53944,53944,11,53972,53972,11,54000,54000,11,54028,54028,11,54056,54056,11,54084,54084,11,54112,54112,11,54140,54140,11,54168,54168,11,54196,54196,11,54224,54224,11,54252,54252,11,54280,54280,11,54308,54308,11,54336,54336,11,54364,54364,11,54392,54392,11,54420,54420,11,54448,54448,11,54476,54476,11,54504,54504,11,54532,54532,11,54560,54560,11,54588,54588,11,54616,54616,11,54644,54644,11,54672,54672,11,54700,54700,11,54728,54728,11,54756,54756,11,54784,54784,11,54812,54812,11,54840,54840,11,54868,54868,11,54896,54896,11,54924,54924,11,54952,54952,11,54980,54980,11,55008,55008,11,55036,55036,11,55064,55064,11,55092,55092,11,55120,55120,11,55148,55148,11,55176,55176,11,55216,55238,9,64286,64286,5,65056,65071,5,65438,65439,5,65529,65531,4,66272,66272,5,68097,68099,5,68108,68111,5,68159,68159,5,68900,68903,5,69446,69456,5,69632,69632,7,69634,69634,7,69744,69744,5,69759,69761,5,69808,69810,7,69815,69816,7,69821,69821,1,69837,69837,1,69927,69931,5,69933,69940,5,70003,70003,5,70018,70018,7,70070,70078,5,70082,70083,1,70094,70094,7,70188,70190,7,70194,70195,7,70197,70197,7,70206,70206,5,70368,70370,7,70400,70401,5,70459,70460,5,70463,70463,7,70465,70468,7,70475,70477,7,70498,70499,7,70512,70516,5,70712,70719,5,70722,70724,5,70726,70726,5,70832,70832,5,70835,70840,5,70842,70842,5,70845,70845,5,70847,70848,5,70850,70851,5,71088,71089,7,71096,71099,7,71102,71102,7,71132,71133,5,71219,71226,5,71229,71229,5,71231,71232,5,71340,71340,7,71342,71343,7,71350,71350,7,71453,71455,5,71462,71462,7,71724,71726,7,71736,71736,7,71984,71984,5,71991,71992,7,71997,71997,7,71999,71999,1,72001,72001,1,72003,72003,5,72148,72151,5,72156,72159,7,72164,72164,7,72243,72248,5,72250,72250,1,72263,72263,5,72279,72280,7,72324,72329,1,72343,72343,7,72751,72751,7,72760,72765,5,72767,72767,5,72873,72873,7,72881,72881,7,72884,72884,7,73009,73014,5,73020,73021,5,73030,73030,1,73098,73102,7,73107,73108,7,73110,73110,7,73459,73460,5,78896,78904,4,92976,92982,5,94033,94087,7,94180,94180,5,113821,113822,5,118528,118573,5,119141,119141,5,119143,119145,5,119150,119154,5,119163,119170,5,119210,119213,5,121344,121398,5,121461,121461,5,121499,121503,5,122880,122886,5,122907,122913,5,122918,122922,5,123566,123566,5,125136,125142,5,126976,126979,14,126981,127182,14,127184,127231,14,127279,127279,14,127344,127345,14,127374,127374,14,127405,127461,14,127489,127490,14,127514,127514,14,127538,127546,14,127561,127567,14,127570,127743,14,127757,127758,14,127760,127760,14,127762,127762,14,127766,127768,14,127770,127770,14,127772,127772,14,127775,127776,14,127778,127779,14,127789,127791,14,127794,127795,14,127798,127798,14,127819,127819,14,127824,127824,14,127868,127868,14,127870,127871,14,127892,127893,14,127896,127896,14,127900,127901,14,127904,127940,14,127942,127942,14,127944,127944,14,127946,127946,14,127951,127955,14,127968,127971,14,127973,127984,14,127987,127987,14,127989,127989,14,127991,127991,14,127995,127999,5,128008,128008,14,128012,128014,14,128017,128018,14,128020,128020,14,128022,128022,14,128042,128042,14,128063,128063,14,128065,128065,14,128101,128101,14,128108,128109,14,128173,128173,14,128182,128183,14,128236,128237,14,128239,128239,14,128245,128245,14,128248,128248,14,128253,128253,14,128255,128258,14,128260,128263,14,128265,128265,14,128277,128277,14,128300,128301,14,128326,128328,14,128331,128334,14,128336,128347,14,128360,128366,14,128369,128370,14,128378,128378,14,128391,128391,14,128394,128397,14,128400,128400,14,128405,128406,14,128420,128420,14,128422,128423,14,128425,128432,14,128435,128443,14,128445,128449,14,128453,128464,14,128468,128475,14,128479,128480,14,128482,128482,14,128484,128487,14,128489,128494,14,128496,128498,14,128500,128505,14,128507,128511,14,128513,128518,14,128521,128525,14,128527,128527,14,128529,128529,14,128533,128533,14,128535,128535,14,128537,128537,14]"); } function getLeftDeleteOffset(offset, str) { if (offset === 0) { return 0; } const emojiOffset = getOffsetBeforeLastEmojiComponent(offset, str); if (emojiOffset !== void 0) { return emojiOffset; } const iterator = new CodePointIterator(str, offset); iterator.prevCodePoint(); return iterator.offset; } function getOffsetBeforeLastEmojiComponent(initialOffset, str) { const iterator = new CodePointIterator(str, initialOffset); let codePoint = iterator.prevCodePoint(); while (isEmojiModifier(codePoint) || codePoint === 65039 || codePoint === 8419) { if (iterator.offset === 0) { return void 0; } codePoint = iterator.prevCodePoint(); } if (!isEmojiImprecise(codePoint)) { return void 0; } let resultOffset = iterator.offset; if (resultOffset > 0) { const optionalZwjCodePoint = iterator.prevCodePoint(); if (optionalZwjCodePoint === 8205) { resultOffset = iterator.offset; } } return resultOffset; } function isEmojiModifier(codePoint) { return 127995 <= codePoint && codePoint <= 127999; } const noBreakWhitespace = " "; const _AmbiguousCharacters = class _AmbiguousCharacters { static getInstance(locales) { return _AmbiguousCharacters.cache.get(Array.from(locales)); } static getLocales() { return _AmbiguousCharacters._locales.value; } constructor(confusableDictionary) { this.confusableDictionary = confusableDictionary; } isAmbiguous(codePoint) { return this.confusableDictionary.has(codePoint); } /** * Returns the non basic ASCII code point that the given code point can be confused, * or undefined if such code point does note exist. */ getPrimaryConfusable(codePoint) { return this.confusableDictionary.get(codePoint); } getConfusableCodePoints() { return new Set(this.confusableDictionary.keys()); } }; _AmbiguousCharacters.ambiguousCharacterData = new Lazy(() => { return JSON.parse('{"_common":[8232,32,8233,32,5760,32,8192,32,8193,32,8194,32,8195,32,8196,32,8197,32,8198,32,8200,32,8201,32,8202,32,8287,32,8199,32,8239,32,2042,95,65101,95,65102,95,65103,95,8208,45,8209,45,8210,45,65112,45,1748,45,8259,45,727,45,8722,45,10134,45,11450,45,1549,44,1643,44,184,44,42233,44,894,59,2307,58,2691,58,1417,58,1795,58,1796,58,5868,58,65072,58,6147,58,6153,58,8282,58,1475,58,760,58,42889,58,8758,58,720,58,42237,58,451,33,11601,33,660,63,577,63,2429,63,5038,63,42731,63,119149,46,8228,46,1793,46,1794,46,42510,46,68176,46,1632,46,1776,46,42232,46,1373,96,65287,96,8219,96,1523,96,8242,96,1370,96,8175,96,65344,96,900,96,8189,96,8125,96,8127,96,8190,96,697,96,884,96,712,96,714,96,715,96,756,96,699,96,701,96,700,96,702,96,42892,96,1497,96,2036,96,2037,96,5194,96,5836,96,94033,96,94034,96,65339,91,10088,40,10098,40,12308,40,64830,40,65341,93,10089,41,10099,41,12309,41,64831,41,10100,123,119060,123,10101,125,65342,94,8270,42,1645,42,8727,42,66335,42,5941,47,8257,47,8725,47,8260,47,9585,47,10187,47,10744,47,119354,47,12755,47,12339,47,11462,47,20031,47,12035,47,65340,92,65128,92,8726,92,10189,92,10741,92,10745,92,119311,92,119355,92,12756,92,20022,92,12034,92,42872,38,708,94,710,94,5869,43,10133,43,66203,43,8249,60,10094,60,706,60,119350,60,5176,60,5810,60,5120,61,11840,61,12448,61,42239,61,8250,62,10095,62,707,62,119351,62,5171,62,94015,62,8275,126,732,126,8128,126,8764,126,65372,124,65293,45,118002,50,120784,50,120794,50,120804,50,120814,50,120824,50,130034,50,42842,50,423,50,1000,50,42564,50,5311,50,42735,50,119302,51,118003,51,120785,51,120795,51,120805,51,120815,51,120825,51,130035,51,42923,51,540,51,439,51,42858,51,11468,51,1248,51,94011,51,71882,51,118004,52,120786,52,120796,52,120806,52,120816,52,120826,52,130036,52,5070,52,71855,52,118005,53,120787,53,120797,53,120807,53,120817,53,120827,53,130037,53,444,53,71867,53,118006,54,120788,54,120798,54,120808,54,120818,54,120828,54,130038,54,11474,54,5102,54,71893,54,119314,55,118007,55,120789,55,120799,55,120809,55,120819,55,120829,55,130039,55,66770,55,71878,55,2819,56,2538,56,2666,56,125131,56,118008,56,120790,56,120800,56,120810,56,120820,56,120830,56,130040,56,547,56,546,56,66330,56,2663,57,2920,57,2541,57,3437,57,118009,57,120791,57,120801,57,120811,57,120821,57,120831,57,130041,57,42862,57,11466,57,71884,57,71852,57,71894,57,9082,97,65345,97,119834,97,119886,97,119938,97,119990,97,120042,97,120094,97,120146,97,120198,97,120250,97,120302,97,120354,97,120406,97,120458,97,593,97,945,97,120514,97,120572,97,120630,97,120688,97,120746,97,65313,65,117974,65,119808,65,119860,65,119912,65,119964,65,120016,65,120068,65,120120,65,120172,65,120224,65,120276,65,120328,65,120380,65,120432,65,913,65,120488,65,120546,65,120604,65,120662,65,120720,65,5034,65,5573,65,42222,65,94016,65,66208,65,119835,98,119887,98,119939,98,119991,98,120043,98,120095,98,120147,98,120199,98,120251,98,120303,98,120355,98,120407,98,120459,98,388,98,5071,98,5234,98,5551,98,65314,66,8492,66,117975,66,119809,66,119861,66,119913,66,120017,66,120069,66,120121,66,120173,66,120225,66,120277,66,120329,66,120381,66,120433,66,42932,66,914,66,120489,66,120547,66,120605,66,120663,66,120721,66,5108,66,5623,66,42192,66,66178,66,66209,66,66305,66,65347,99,8573,99,119836,99,119888,99,119940,99,119992,99,120044,99,120096,99,120148,99,120200,99,120252,99,120304,99,120356,99,120408,99,120460,99,7428,99,1010,99,11429,99,43951,99,66621,99,128844,67,71913,67,71922,67,65315,67,8557,67,8450,67,8493,67,117976,67,119810,67,119862,67,119914,67,119966,67,120018,67,120174,67,120226,67,120278,67,120330,67,120382,67,120434,67,1017,67,11428,67,5087,67,42202,67,66210,67,66306,67,66581,67,66844,67,8574,100,8518,100,119837,100,119889,100,119941,100,119993,100,120045,100,120097,100,120149,100,120201,100,120253,100,120305,100,120357,100,120409,100,120461,100,1281,100,5095,100,5231,100,42194,100,8558,68,8517,68,117977,68,119811,68,119863,68,119915,68,119967,68,120019,68,120071,68,120123,68,120175,68,120227,68,120279,68,120331,68,120383,68,120435,68,5024,68,5598,68,5610,68,42195,68,8494,101,65349,101,8495,101,8519,101,119838,101,119890,101,119942,101,120046,101,120098,101,120150,101,120202,101,120254,101,120306,101,120358,101,120410,101,120462,101,43826,101,1213,101,8959,69,65317,69,8496,69,117978,69,119812,69,119864,69,119916,69,120020,69,120072,69,120124,69,120176,69,120228,69,120280,69,120332,69,120384,69,120436,69,917,69,120492,69,120550,69,120608,69,120666,69,120724,69,11577,69,5036,69,42224,69,71846,69,71854,69,66182,69,119839,102,119891,102,119943,102,119995,102,120047,102,120099,102,120151,102,120203,102,120255,102,120307,102,120359,102,120411,102,120463,102,43829,102,42905,102,383,102,7837,102,1412,102,119315,70,8497,70,117979,70,119813,70,119865,70,119917,70,120021,70,120073,70,120125,70,120177,70,120229,70,120281,70,120333,70,120385,70,120437,70,42904,70,988,70,120778,70,5556,70,42205,70,71874,70,71842,70,66183,70,66213,70,66853,70,65351,103,8458,103,119840,103,119892,103,119944,103,120048,103,120100,103,120152,103,120204,103,120256,103,120308,103,120360,103,120412,103,120464,103,609,103,7555,103,397,103,1409,103,117980,71,119814,71,119866,71,119918,71,119970,71,120022,71,120074,71,120126,71,120178,71,120230,71,120282,71,120334,71,120386,71,120438,71,1292,71,5056,71,5107,71,42198,71,65352,104,8462,104,119841,104,119945,104,119997,104,120049,104,120101,104,120153,104,120205,104,120257,104,120309,104,120361,104,120413,104,120465,104,1211,104,1392,104,5058,104,65320,72,8459,72,8460,72,8461,72,117981,72,119815,72,119867,72,119919,72,120023,72,120179,72,120231,72,120283,72,120335,72,120387,72,120439,72,919,72,120494,72,120552,72,120610,72,120668,72,120726,72,11406,72,5051,72,5500,72,42215,72,66255,72,731,105,9075,105,65353,105,8560,105,8505,105,8520,105,119842,105,119894,105,119946,105,119998,105,120050,105,120102,105,120154,105,120206,105,120258,105,120310,105,120362,105,120414,105,120466,105,120484,105,618,105,617,105,953,105,8126,105,890,105,120522,105,120580,105,120638,105,120696,105,120754,105,1110,105,42567,105,1231,105,43893,105,5029,105,71875,105,65354,106,8521,106,119843,106,119895,106,119947,106,119999,106,120051,106,120103,106,120155,106,120207,106,120259,106,120311,106,120363,106,120415,106,120467,106,1011,106,1112,106,65322,74,117983,74,119817,74,119869,74,119921,74,119973,74,120025,74,120077,74,120129,74,120181,74,120233,74,120285,74,120337,74,120389,74,120441,74,42930,74,895,74,1032,74,5035,74,5261,74,42201,74,119844,107,119896,107,119948,107,120000,107,120052,107,120104,107,120156,107,120208,107,120260,107,120312,107,120364,107,120416,107,120468,107,8490,75,65323,75,117984,75,119818,75,119870,75,119922,75,119974,75,120026,75,120078,75,120130,75,120182,75,120234,75,120286,75,120338,75,120390,75,120442,75,922,75,120497,75,120555,75,120613,75,120671,75,120729,75,11412,75,5094,75,5845,75,42199,75,66840,75,1472,108,8739,73,9213,73,65512,73,1633,108,1777,73,66336,108,125127,108,118001,108,120783,73,120793,73,120803,73,120813,73,120823,73,130033,73,65321,73,8544,73,8464,73,8465,73,117982,108,119816,73,119868,73,119920,73,120024,73,120128,73,120180,73,120232,73,120284,73,120336,73,120388,73,120440,73,65356,108,8572,73,8467,108,119845,108,119897,108,119949,108,120001,108,120053,108,120105,73,120157,73,120209,73,120261,73,120313,73,120365,73,120417,73,120469,73,448,73,120496,73,120554,73,120612,73,120670,73,120728,73,11410,73,1030,73,1216,73,1493,108,1503,108,1575,108,126464,108,126592,108,65166,108,65165,108,1994,108,11599,73,5825,73,42226,73,93992,73,66186,124,66313,124,119338,76,8556,76,8466,76,117985,76,119819,76,119871,76,119923,76,120027,76,120079,76,120131,76,120183,76,120235,76,120287,76,120339,76,120391,76,120443,76,11472,76,5086,76,5290,76,42209,76,93974,76,71843,76,71858,76,66587,76,66854,76,65325,77,8559,77,8499,77,117986,77,119820,77,119872,77,119924,77,120028,77,120080,77,120132,77,120184,77,120236,77,120288,77,120340,77,120392,77,120444,77,924,77,120499,77,120557,77,120615,77,120673,77,120731,77,1018,77,11416,77,5047,77,5616,77,5846,77,42207,77,66224,77,66321,77,119847,110,119899,110,119951,110,120003,110,120055,110,120107,110,120159,110,120211,110,120263,110,120315,110,120367,110,120419,110,120471,110,1400,110,1404,110,65326,78,8469,78,117987,78,119821,78,119873,78,119925,78,119977,78,120029,78,120081,78,120185,78,120237,78,120289,78,120341,78,120393,78,120445,78,925,78,120500,78,120558,78,120616,78,120674,78,120732,78,11418,78,42208,78,66835,78,3074,111,3202,111,3330,111,3458,111,2406,111,2662,111,2790,111,3046,111,3174,111,3302,111,3430,111,3664,111,3792,111,4160,111,1637,111,1781,111,65359,111,8500,111,119848,111,119900,111,119952,111,120056,111,120108,111,120160,111,120212,111,120264,111,120316,111,120368,111,120420,111,120472,111,7439,111,7441,111,43837,111,959,111,120528,111,120586,111,120644,111,120702,111,120760,111,963,111,120532,111,120590,111,120648,111,120706,111,120764,111,11423,111,4351,111,1413,111,1505,111,1607,111,126500,111,126564,111,126596,111,65259,111,65260,111,65258,111,65257,111,1726,111,64428,111,64429,111,64427,111,64426,111,1729,111,64424,111,64425,111,64423,111,64422,111,1749,111,3360,111,4125,111,66794,111,71880,111,71895,111,66604,111,1984,79,2534,79,2918,79,12295,79,70864,79,71904,79,118000,79,120782,79,120792,79,120802,79,120812,79,120822,79,130032,79,65327,79,117988,79,119822,79,119874,79,119926,79,119978,79,120030,79,120082,79,120134,79,120186,79,120238,79,120290,79,120342,79,120394,79,120446,79,927,79,120502,79,120560,79,120618,79,120676,79,120734,79,11422,79,1365,79,11604,79,4816,79,2848,79,66754,79,42227,79,71861,79,66194,79,66219,79,66564,79,66838,79,9076,112,65360,112,119849,112,119901,112,119953,112,120005,112,120057,112,120109,112,120161,112,120213,112,120265,112,120317,112,120369,112,120421,112,120473,112,961,112,120530,112,120544,112,120588,112,120602,112,120646,112,120660,112,120704,112,120718,112,120762,112,120776,112,11427,112,65328,80,8473,80,117989,80,119823,80,119875,80,119927,80,119979,80,120031,80,120083,80,120187,80,120239,80,120291,80,120343,80,120395,80,120447,80,929,80,120504,80,120562,80,120620,80,120678,80,120736,80,11426,80,5090,80,5229,80,42193,80,66197,80,119850,113,119902,113,119954,113,120006,113,120058,113,120110,113,120162,113,120214,113,120266,113,120318,113,120370,113,120422,113,120474,113,1307,113,1379,113,1382,113,8474,81,117990,81,119824,81,119876,81,119928,81,119980,81,120032,81,120084,81,120188,81,120240,81,120292,81,120344,81,120396,81,120448,81,11605,81,119851,114,119903,114,119955,114,120007,114,120059,114,120111,114,120163,114,120215,114,120267,114,120319,114,120371,114,120423,114,120475,114,43847,114,43848,114,7462,114,11397,114,43905,114,119318,82,8475,82,8476,82,8477,82,117991,82,119825,82,119877,82,119929,82,120033,82,120189,82,120241,82,120293,82,120345,82,120397,82,120449,82,422,82,5025,82,5074,82,66740,82,5511,82,42211,82,94005,82,65363,115,119852,115,119904,115,119956,115,120008,115,120060,115,120112,115,120164,115,120216,115,120268,115,120320,115,120372,115,120424,115,120476,115,42801,115,445,115,1109,115,43946,115,71873,115,66632,115,65331,83,117992,83,119826,83,119878,83,119930,83,119982,83,120034,83,120086,83,120138,83,120190,83,120242,83,120294,83,120346,83,120398,83,120450,83,1029,83,1359,83,5077,83,5082,83,42210,83,94010,83,66198,83,66592,83,119853,116,119905,116,119957,116,120009,116,120061,116,120113,116,120165,116,120217,116,120269,116,120321,116,120373,116,120425,116,120477,116,8868,84,10201,84,128872,84,65332,84,117993,84,119827,84,119879,84,119931,84,119983,84,120035,84,120087,84,120139,84,120191,84,120243,84,120295,84,120347,84,120399,84,120451,84,932,84,120507,84,120565,84,120623,84,120681,84,120739,84,11430,84,5026,84,42196,84,93962,84,71868,84,66199,84,66225,84,66325,84,119854,117,119906,117,119958,117,120010,117,120062,117,120114,117,120166,117,120218,117,120270,117,120322,117,120374,117,120426,117,120478,117,42911,117,7452,117,43854,117,43858,117,651,117,965,117,120534,117,120592,117,120650,117,120708,117,120766,117,1405,117,66806,117,71896,117,8746,85,8899,85,117994,85,119828,85,119880,85,119932,85,119984,85,120036,85,120088,85,120140,85,120192,85,120244,85,120296,85,120348,85,120400,85,120452,85,1357,85,4608,85,66766,85,5196,85,42228,85,94018,85,71864,85,8744,118,8897,118,65366,118,8564,118,119855,118,119907,118,119959,118,120011,118,120063,118,120115,118,120167,118,120219,118,120271,118,120323,118,120375,118,120427,118,120479,118,7456,118,957,118,120526,118,120584,118,120642,118,120700,118,120758,118,1141,118,1496,118,71430,118,43945,118,71872,118,119309,86,1639,86,1783,86,8548,86,117995,86,119829,86,119881,86,119933,86,119985,86,120037,86,120089,86,120141,86,120193,86,120245,86,120297,86,120349,86,120401,86,120453,86,1140,86,11576,86,5081,86,5167,86,42719,86,42214,86,93960,86,71840,86,66845,86,623,119,119856,119,119908,119,119960,119,120012,119,120064,119,120116,119,120168,119,120220,119,120272,119,120324,119,120376,119,120428,119,120480,119,7457,119,1121,119,1309,119,1377,119,71434,119,71438,119,71439,119,43907,119,71910,87,71919,87,117996,87,119830,87,119882,87,119934,87,119986,87,120038,87,120090,87,120142,87,120194,87,120246,87,120298,87,120350,87,120402,87,120454,87,1308,87,5043,87,5076,87,42218,87,5742,120,10539,120,10540,120,10799,120,65368,120,8569,120,119857,120,119909,120,119961,120,120013,120,120065,120,120117,120,120169,120,120221,120,120273,120,120325,120,120377,120,120429,120,120481,120,5441,120,5501,120,5741,88,9587,88,66338,88,71916,88,65336,88,8553,88,117997,88,119831,88,119883,88,119935,88,119987,88,120039,88,120091,88,120143,88,120195,88,120247,88,120299,88,120351,88,120403,88,120455,88,42931,88,935,88,120510,88,120568,88,120626,88,120684,88,120742,88,11436,88,11613,88,5815,88,42219,88,66192,88,66228,88,66327,88,66855,88,611,121,7564,121,65369,121,119858,121,119910,121,119962,121,120014,121,120066,121,120118,121,120170,121,120222,121,120274,121,120326,121,120378,121,120430,121,120482,121,655,121,7935,121,43866,121,947,121,8509,121,120516,121,120574,121,120632,121,120690,121,120748,121,1199,121,4327,121,71900,121,65337,89,117998,89,119832,89,119884,89,119936,89,119988,89,120040,89,120092,89,120144,89,120196,89,120248,89,120300,89,120352,89,120404,89,120456,89,933,89,978,89,120508,89,120566,89,120624,89,120682,89,120740,89,11432,89,1198,89,5033,89,5053,89,42220,89,94019,89,71844,89,66226,89,119859,122,119911,122,119963,122,120015,122,120067,122,120119,122,120171,122,120223,122,120275,122,120327,122,120379,122,120431,122,120483,122,7458,122,43923,122,71876,122,71909,90,66293,90,65338,90,8484,90,8488,90,117999,90,119833,90,119885,90,119937,90,119989,90,120041,90,120197,90,120249,90,120301,90,120353,90,120405,90,120457,90,918,90,120493,90,120551,90,120609,90,120667,90,120725,90,5059,90,42204,90,71849,90,65282,34,65283,35,65284,36,65285,37,65286,38,65290,42,65291,43,65294,46,65295,47,65296,48,65298,50,65299,51,65300,52,65301,53,65302,54,65303,55,65304,56,65305,57,65308,60,65309,61,65310,62,65312,64,65316,68,65318,70,65319,71,65324,76,65329,81,65330,82,65333,85,65334,86,65335,87,65343,95,65346,98,65348,100,65350,102,65355,107,65357,109,65358,110,65361,113,65362,114,65364,116,65365,117,65367,119,65370,122,65371,123,65373,125,119846,109],"_default":[160,32,8211,45,65374,126,8218,44,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"cs":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"de":[65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"es":[8211,45,65374,126,8218,44,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"fr":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"it":[160,32,8211,45,65374,126,8218,44,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"ja":[8211,45,8218,44,65281,33,8216,96,8245,96,180,96,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65292,44,65297,49,65307,59],"ko":[8211,45,65374,126,8218,44,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"pl":[65374,126,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"pt-BR":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"qps-ploc":[160,32,8211,45,65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"ru":[65374,126,8218,44,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,305,105,921,73,1009,112,215,120,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"tr":[160,32,8211,45,65374,126,8218,44,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41,65292,44,65297,49,65307,59,65311,63],"zh-hans":[160,32,65374,126,8218,44,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65297,49],"zh-hant":[8211,45,65374,126,8218,44,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89]}'); }); _AmbiguousCharacters.cache = new LRUCachedFunction({ getCacheKey: JSON.stringify }, (locales) => { function arrayToMap(arr) { const result = /* @__PURE__ */ new Map(); for (let i2 = 0; i2 < arr.length; i2 += 2) { result.set(arr[i2], arr[i2 + 1]); } return result; } function mergeMaps(map1, map2) { const result = new Map(map1); for (const [key, value] of map2) { result.set(key, value); } return result; } function intersectMaps(map1, map2) { if (!map1) { return map2; } const result = /* @__PURE__ */ new Map(); for (const [key, value] of map1) { if (map2.has(key)) { result.set(key, value); } } return result; } const data = _AmbiguousCharacters.ambiguousCharacterData.value; let filteredLocales = locales.filter((l) => !l.startsWith("_") && l in data); if (filteredLocales.length === 0) { filteredLocales = ["_default"]; } let languageSpecificMap = void 0; for (const locale of filteredLocales) { const map2 = arrayToMap(data[locale]); languageSpecificMap = intersectMaps(languageSpecificMap, map2); } const commonMap = arrayToMap(data["_common"]); const map = mergeMaps(commonMap, languageSpecificMap); return new _AmbiguousCharacters(map); }); _AmbiguousCharacters._locales = new Lazy(() => Object.keys(_AmbiguousCharacters.ambiguousCharacterData.value).filter((k) => !k.startsWith("_"))); let AmbiguousCharacters = _AmbiguousCharacters; const _InvisibleCharacters = class _InvisibleCharacters { static getRawData() { return JSON.parse('{"_common":[11,12,13,127,847,1564,4447,4448,6068,6069,6155,6156,6157,6158,7355,7356,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8204,8205,8206,8207,8234,8235,8236,8237,8238,8239,8287,8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,10240,12644,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65279,65440,65520,65521,65522,65523,65524,65525,65526,65527,65528,65532,78844,119155,119156,119157,119158,119159,119160,119161,119162,917504,917505,917506,917507,917508,917509,917510,917511,917512,917513,917514,917515,917516,917517,917518,917519,917520,917521,917522,917523,917524,917525,917526,917527,917528,917529,917530,917531,917532,917533,917534,917535,917536,917537,917538,917539,917540,917541,917542,917543,917544,917545,917546,917547,917548,917549,917550,917551,917552,917553,917554,917555,917556,917557,917558,917559,917560,917561,917562,917563,917564,917565,917566,917567,917568,917569,917570,917571,917572,917573,917574,917575,917576,917577,917578,917579,917580,917581,917582,917583,917584,917585,917586,917587,917588,917589,917590,917591,917592,917593,917594,917595,917596,917597,917598,917599,917600,917601,917602,917603,917604,917605,917606,917607,917608,917609,917610,917611,917612,917613,917614,917615,917616,917617,917618,917619,917620,917621,917622,917623,917624,917625,917626,917627,917628,917629,917630,917631,917760,917761,917762,917763,917764,917765,917766,917767,917768,917769,917770,917771,917772,917773,917774,917775,917776,917777,917778,917779,917780,917781,917782,917783,917784,917785,917786,917787,917788,917789,917790,917791,917792,917793,917794,917795,917796,917797,917798,917799,917800,917801,917802,917803,917804,917805,917806,917807,917808,917809,917810,917811,917812,917813,917814,917815,917816,917817,917818,917819,917820,917821,917822,917823,917824,917825,917826,917827,917828,917829,917830,917831,917832,917833,917834,917835,917836,917837,917838,917839,917840,917841,917842,917843,917844,917845,917846,917847,917848,917849,917850,917851,917852,917853,917854,917855,917856,917857,917858,917859,917860,917861,917862,917863,917864,917865,917866,917867,917868,917869,917870,917871,917872,917873,917874,917875,917876,917877,917878,917879,917880,917881,917882,917883,917884,917885,917886,917887,917888,917889,917890,917891,917892,917893,917894,917895,917896,917897,917898,917899,917900,917901,917902,917903,917904,917905,917906,917907,917908,917909,917910,917911,917912,917913,917914,917915,917916,917917,917918,917919,917920,917921,917922,917923,917924,917925,917926,917927,917928,917929,917930,917931,917932,917933,917934,917935,917936,917937,917938,917939,917940,917941,917942,917943,917944,917945,917946,917947,917948,917949,917950,917951,917952,917953,917954,917955,917956,917957,917958,917959,917960,917961,917962,917963,917964,917965,917966,917967,917968,917969,917970,917971,917972,917973,917974,917975,917976,917977,917978,917979,917980,917981,917982,917983,917984,917985,917986,917987,917988,917989,917990,917991,917992,917993,917994,917995,917996,917997,917998,917999],"cs":[173,8203,12288],"de":[173,8203,12288],"es":[8203,12288],"fr":[173,8203,12288],"it":[160,173,12288],"ja":[173],"ko":[173,12288],"pl":[173,8203,12288],"pt-BR":[173,8203,12288],"qps-ploc":[160,173,8203,12288],"ru":[173,12288],"tr":[160,173,8203,12288],"zh-hans":[160,173,8203,12288],"zh-hant":[173,12288]}'); } static getData() { if (!this._data) { this._data = new Set([...Object.values(_InvisibleCharacters.getRawData())].flat()); } return this._data; } static isInvisibleCharacter(codePoint) { return _InvisibleCharacters.getData().has(codePoint); } static get codePoints() { return _InvisibleCharacters.getData(); } }; _InvisibleCharacters._data = void 0; let InvisibleCharacters = _InvisibleCharacters; let safeProcess; const vscodeGlobal = globalThis.vscode; if (typeof vscodeGlobal !== "undefined" && typeof vscodeGlobal.process !== "undefined") { const sandboxProcess = vscodeGlobal.process; safeProcess = { get platform() { return sandboxProcess.platform; }, get arch() { return sandboxProcess.arch; }, get env() { return sandboxProcess.env; }, cwd() { return sandboxProcess.cwd(); } }; } else if (typeof process !== "undefined" && typeof process?.versions?.node === "string") { safeProcess = { get platform() { return process.platform; }, get arch() { return process.arch; }, get env() { return process.env; }, cwd() { return process.env["VSCODE_CWD"] || process.cwd(); } }; } else { safeProcess = { // Supported get platform() { return isWindows ? "win32" : isMacintosh ? "darwin" : "linux"; }, get arch() { return void 0; }, // Unsupported get env() { return {}; }, cwd() { return "/"; } }; } const cwd = safeProcess.cwd; const env = safeProcess.env; const platform = safeProcess.platform; const CHAR_UPPERCASE_A = 65; const CHAR_LOWERCASE_A = 97; const CHAR_UPPERCASE_Z = 90; const CHAR_LOWERCASE_Z = 122; const CHAR_DOT = 46; const CHAR_FORWARD_SLASH = 47; const CHAR_BACKWARD_SLASH = 92; const CHAR_COLON = 58; const CHAR_QUESTION_MARK = 63; class ErrorInvalidArgType extends Error { constructor(name, expected, actual) { let determiner; if (typeof expected === "string" && expected.indexOf("not ") === 0) { determiner = "must not be"; expected = expected.replace(/^not /, ""); } else { determiner = "must be"; } const type = name.indexOf(".") !== -1 ? "property" : "argument"; let msg = `The "${name}" ${type} ${determiner} of type ${expected}`; msg += `. Received type ${typeof actual}`; super(msg); this.code = "ERR_INVALID_ARG_TYPE"; } } function validateObject(pathObject, name) { if (pathObject === null || typeof pathObject !== "object") { throw new ErrorInvalidArgType(name, "Object", pathObject); } } function validateString(value, name) { if (typeof value !== "string") { throw new ErrorInvalidArgType(name, "string", value); } } const platformIsWin32 = platform === "win32"; function isPathSeparator$1(code) { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; } function isPosixPathSeparator(code) { return code === CHAR_FORWARD_SLASH; } function isWindowsDeviceRoot(code) { return code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z || code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z; } function normalizeString(path, allowAboveRoot, separator2, isPathSeparator2) { let res = ""; let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; let code = 0; for (let i2 = 0; i2 <= path.length; ++i2) { if (i2 < path.length) { code = path.charCodeAt(i2); } else if (isPathSeparator2(code)) { break; } else { code = CHAR_FORWARD_SLASH; } if (isPathSeparator2(code)) { if (lastSlash === i2 - 1 || dots === 1) ; else if (dots === 2) { if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) { if (res.length > 2) { const lastSlashIndex = res.lastIndexOf(separator2); if (lastSlashIndex === -1) { res = ""; lastSegmentLength = 0; } else { res = res.slice(0, lastSlashIndex); lastSegmentLength = res.length - 1 - res.lastIndexOf(separator2); } lastSlash = i2; dots = 0; continue; } else if (res.length !== 0) { res = ""; lastSegmentLength = 0; lastSlash = i2; dots = 0; continue; } } if (allowAboveRoot) { res += res.length > 0 ? `${separator2}..` : ".."; lastSegmentLength = 2; } } else { if (res.length > 0) { res += `${separator2}${path.slice(lastSlash + 1, i2)}`; } else { res = path.slice(lastSlash + 1, i2); } lastSegmentLength = i2 - lastSlash - 1; } lastSlash = i2; dots = 0; } else if (code === CHAR_DOT && dots !== -1) { ++dots; } else { dots = -1; } } return res; } function formatExt(ext) { return ext ? `${ext[0] === "." ? "" : "."}${ext}` : ""; } function _format(sep2, pathObject) { validateObject(pathObject, "pathObject"); const dir = pathObject.dir || pathObject.root; const base = pathObject.base || `${pathObject.name || ""}${formatExt(pathObject.ext)}`; if (!dir) { return base; } return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep2}${base}`; } const win32 = { // path.resolve([from ...], to) resolve(...pathSegments) { let resolvedDevice = ""; let resolvedTail = ""; let resolvedAbsolute = false; for (let i2 = pathSegments.length - 1; i2 >= -1; i2--) { let path; if (i2 >= 0) { path = pathSegments[i2]; validateString(path, `paths[${i2}]`); if (path.length === 0) { continue; } } else if (resolvedDevice.length === 0) { path = cwd(); } else { path = env[`=${resolvedDevice}`] || cwd(); if (path === void 0 || path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH) { path = `${resolvedDevice}\\`; } } const len = path.length; let rootEnd = 0; let device = ""; let isAbsolute = false; const code = path.charCodeAt(0); if (len === 1) { if (isPathSeparator$1(code)) { rootEnd = 1; isAbsolute = true; } } else if (isPathSeparator$1(code)) { isAbsolute = true; if (isPathSeparator$1(path.charCodeAt(1))) { let j = 2; let last = j; while (j < len && !isPathSeparator$1(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { const firstPart = path.slice(last, j); last = j; while (j < len && isPathSeparator$1(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { last = j; while (j < len && !isPathSeparator$1(path.charCodeAt(j))) { j++; } if (j === len || j !== last) { device = `\\\\${firstPart}\\${path.slice(last, j)}`; rootEnd = j; } } } } else { rootEnd = 1; } } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { device = path.slice(0, 2); rootEnd = 2; if (len > 2 && isPathSeparator$1(path.charCodeAt(2))) { isAbsolute = true; rootEnd = 3; } } if (device.length > 0) { if (resolvedDevice.length > 0) { if (device.toLowerCase() !== resolvedDevice.toLowerCase()) { continue; } } else { resolvedDevice = device; } } if (resolvedAbsolute) { if (resolvedDevice.length > 0) { break; } } else { resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; resolvedAbsolute = isAbsolute; if (isAbsolute && resolvedDevice.length > 0) { break; } } } resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isPathSeparator$1); return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || "."; }, normalize(path) { validateString(path, "path"); const len = path.length; if (len === 0) { return "."; } let rootEnd = 0; let device; let isAbsolute = false; const code = path.charCodeAt(0); if (len === 1) { return isPosixPathSeparator(code) ? "\\" : path; } if (isPathSeparator$1(code)) { isAbsolute = true; if (isPathSeparator$1(path.charCodeAt(1))) { let j = 2; let last = j; while (j < len && !isPathSeparator$1(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { const firstPart = path.slice(last, j); last = j; while (j < len && isPathSeparator$1(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { last = j; while (j < len && !isPathSeparator$1(path.charCodeAt(j))) { j++; } if (j === len) { return `\\\\${firstPart}\\${path.slice(last)}\\`; } if (j !== last) { device = `\\\\${firstPart}\\${path.slice(last, j)}`; rootEnd = j; } } } } else { rootEnd = 1; } } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { device = path.slice(0, 2); rootEnd = 2; if (len > 2 && isPathSeparator$1(path.charCodeAt(2))) { isAbsolute = true; rootEnd = 3; } } let tail2 = rootEnd < len ? normalizeString(path.slice(rootEnd), !isAbsolute, "\\", isPathSeparator$1) : ""; if (tail2.length === 0 && !isAbsolute) { tail2 = "."; } if (tail2.length > 0 && isPathSeparator$1(path.charCodeAt(len - 1))) { tail2 += "\\"; } if (!isAbsolute && device === void 0 && path.includes(":")) { if (tail2.length >= 2 && isWindowsDeviceRoot(tail2.charCodeAt(0)) && tail2.charCodeAt(1) === CHAR_COLON) { return `.\\${tail2}`; } let index = path.indexOf(":"); do { if (index === len - 1 || isPathSeparator$1(path.charCodeAt(index + 1))) { return `.\\${tail2}`; } } while ((index = path.indexOf(":", index + 1)) !== -1); } if (device === void 0) { return isAbsolute ? `\\${tail2}` : tail2; } return isAbsolute ? `${device}\\${tail2}` : `${device}${tail2}`; }, isAbsolute(path) { validateString(path, "path"); const len = path.length; if (len === 0) { return false; } const code = path.charCodeAt(0); return isPathSeparator$1(code) || // Possible device root len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isPathSeparator$1(path.charCodeAt(2)); }, join(...paths) { if (paths.length === 0) { return "."; } let joined; let firstPart; for (let i2 = 0; i2 < paths.length; ++i2) { const arg = paths[i2]; validateString(arg, "path"); if (arg.length > 0) { if (joined === void 0) { joined = firstPart = arg; } else { joined += `\\${arg}`; } } } if (joined === void 0) { return "."; } let needsReplace = true; let slashCount = 0; if (typeof firstPart === "string" && isPathSeparator$1(firstPart.charCodeAt(0))) { ++slashCount; const firstLen = firstPart.length; if (firstLen > 1 && isPathSeparator$1(firstPart.charCodeAt(1))) { ++slashCount; if (firstLen > 2) { if (isPathSeparator$1(firstPart.charCodeAt(2))) { ++slashCount; } else { needsReplace = false; } } } } if (needsReplace) { while (slashCount < joined.length && isPathSeparator$1(joined.charCodeAt(slashCount))) { slashCount++; } if (slashCount >= 2) { joined = `\\${joined.slice(slashCount)}`; } } return win32.normalize(joined); }, // It will solve the relative path from `from` to `to`, for instance: // from = 'C:\\orandea\\test\\aaa' // to = 'C:\\orandea\\impl\\bbb' // The output of the function should be: '..\\..\\impl\\bbb' relative(from, to) { validateString(from, "from"); validateString(to, "to"); if (from === to) { return ""; } const fromOrig = win32.resolve(from); const toOrig = win32.resolve(to); if (fromOrig === toOrig) { return ""; } from = fromOrig.toLowerCase(); to = toOrig.toLowerCase(); if (from === to) { return ""; } if (fromOrig.length !== from.length || toOrig.length !== to.length) { const fromSplit = fromOrig.split("\\"); const toSplit = toOrig.split("\\"); if (fromSplit[fromSplit.length - 1] === "") { fromSplit.pop(); } if (toSplit[toSplit.length - 1] === "") { toSplit.pop(); } const fromLen2 = fromSplit.length; const toLen2 = toSplit.length; const length2 = fromLen2 < toLen2 ? fromLen2 : toLen2; let i3; for (i3 = 0; i3 < length2; i3++) { if (fromSplit[i3].toLowerCase() !== toSplit[i3].toLowerCase()) { break; } } if (i3 === 0) { return toOrig; } else if (i3 === length2) { if (toLen2 > length2) { return toSplit.slice(i3).join("\\"); } if (fromLen2 > length2) { return "..\\".repeat(fromLen2 - 1 - i3) + ".."; } return ""; } return "..\\".repeat(fromLen2 - i3) + toSplit.slice(i3).join("\\"); } let fromStart = 0; while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) { fromStart++; } let fromEnd = from.length; while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) { fromEnd--; } const fromLen = fromEnd - fromStart; let toStart = 0; while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { toStart++; } let toEnd = to.length; while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) { toEnd--; } const toLen = toEnd - toStart; const length = fromLen < toLen ? fromLen : toLen; let lastCommonSep = -1; let i2 = 0; for (; i2 < length; i2++) { const fromCode = from.charCodeAt(fromStart + i2); if (fromCode !== to.charCodeAt(toStart + i2)) { break; } else if (fromCode === CHAR_BACKWARD_SLASH) { lastCommonSep = i2; } } if (i2 !== length) { if (lastCommonSep === -1) { return toOrig; } } else { if (toLen > length) { if (to.charCodeAt(toStart + i2) === CHAR_BACKWARD_SLASH) { return toOrig.slice(toStart + i2 + 1); } if (i2 === 2) { return toOrig.slice(toStart + i2); } } if (fromLen > length) { if (from.charCodeAt(fromStart + i2) === CHAR_BACKWARD_SLASH) { lastCommonSep = i2; } else if (i2 === 2) { lastCommonSep = 3; } } if (lastCommonSep === -1) { lastCommonSep = 0; } } let out = ""; for (i2 = fromStart + lastCommonSep + 1; i2 <= fromEnd; ++i2) { if (i2 === fromEnd || from.charCodeAt(i2) === CHAR_BACKWARD_SLASH) { out += out.length === 0 ? ".." : "\\.."; } } toStart += lastCommonSep; if (out.length > 0) { return `${out}${toOrig.slice(toStart, toEnd)}`; } if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { ++toStart; } return toOrig.slice(toStart, toEnd); }, toNamespacedPath(path) { if (typeof path !== "string" || path.length === 0) { return path; } const resolvedPath = win32.resolve(path); if (resolvedPath.length <= 2) { return path; } if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) { if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) { const code = resolvedPath.charCodeAt(2); if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) { return `\\\\?\\UNC\\${resolvedPath.slice(2)}`; } } } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) && resolvedPath.charCodeAt(1) === CHAR_COLON && resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) { return `\\\\?\\${resolvedPath}`; } return resolvedPath; }, dirname(path) { validateString(path, "path"); const len = path.length; if (len === 0) { return "."; } let rootEnd = -1; let offset = 0; const code = path.charCodeAt(0); if (len === 1) { return isPathSeparator$1(code) ? path : "."; } if (isPathSeparator$1(code)) { rootEnd = offset = 1; if (isPathSeparator$1(path.charCodeAt(1))) { let j = 2; let last = j; while (j < len && !isPathSeparator$1(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { last = j; while (j < len && isPathSeparator$1(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { last = j; while (j < len && !isPathSeparator$1(path.charCodeAt(j))) { j++; } if (j === len) { return path; } if (j !== last) { rootEnd = offset = j + 1; } } } } } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { rootEnd = len > 2 && isPathSeparator$1(path.charCodeAt(2)) ? 3 : 2; offset = rootEnd; } let end = -1; let matchedSlash = true; for (let i2 = len - 1; i2 >= offset; --i2) { if (isPathSeparator$1(path.charCodeAt(i2))) { if (!matchedSlash) { end = i2; break; } } else { matchedSlash = false; } } if (end === -1) { if (rootEnd === -1) { return "."; } end = rootEnd; } return path.slice(0, end); }, basename(path, suffix) { if (suffix !== void 0) { validateString(suffix, "suffix"); } validateString(path, "path"); let start = 0; let end = -1; let matchedSlash = true; let i2; if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) { start = 2; } if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) { if (suffix === path) { return ""; } let extIdx = suffix.length - 1; let firstNonSlashEnd = -1; for (i2 = path.length - 1; i2 >= start; --i2) { const code = path.charCodeAt(i2); if (isPathSeparator$1(code)) { if (!matchedSlash) { start = i2 + 1; break; } } else { if (firstNonSlashEnd === -1) { matchedSlash = false; firstNonSlashEnd = i2 + 1; } if (extIdx >= 0) { if (code === suffix.charCodeAt(extIdx)) { if (--extIdx === -1) { end = i2; } } else { extIdx = -1; end = firstNonSlashEnd; } } } } if (start === end) { end = firstNonSlashEnd; } else if (end === -1) { end = path.length; } return path.slice(start, end); } for (i2 = path.length - 1; i2 >= start; --i2) { if (isPathSeparator$1(path.charCodeAt(i2))) { if (!matchedSlash) { start = i2 + 1; break; } } else if (end === -1) { matchedSlash = false; end = i2 + 1; } } if (end === -1) { return ""; } return path.slice(start, end); }, extname(path) { validateString(path, "path"); let start = 0; let startDot = -1; let startPart = 0; let end = -1; let matchedSlash = true; let preDotState = 0; if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) { start = startPart = 2; } for (let i2 = path.length - 1; i2 >= start; --i2) { const code = path.charCodeAt(i2); if (isPathSeparator$1(code)) { if (!matchedSlash) { startPart = i2 + 1; break; } continue; } if (end === -1) { matchedSlash = false; end = i2 + 1; } if (code === CHAR_DOT) { if (startDot === -1) { startDot = i2; } else if (preDotState !== 1) { preDotState = 1; } } else if (startDot !== -1) { preDotState = -1; } } if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot preDotState === 0 || // The (right-most) trimmed path component is exactly '..' preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { return ""; } return path.slice(startDot, end); }, format: _format.bind(null, "\\"), parse(path) { validateString(path, "path"); const ret = { root: "", dir: "", base: "", ext: "", name: "" }; if (path.length === 0) { return ret; } const len = path.length; let rootEnd = 0; let code = path.charCodeAt(0); if (len === 1) { if (isPathSeparator$1(code)) { ret.root = ret.dir = path; return ret; } ret.base = ret.name = path; return ret; } if (isPathSeparator$1(code)) { rootEnd = 1; if (isPathSeparator$1(path.charCodeAt(1))) { let j = 2; let last = j; while (j < len && !isPathSeparator$1(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { last = j; while (j < len && isPathSeparator$1(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { last = j; while (j < len && !isPathSeparator$1(path.charCodeAt(j))) { j++; } if (j === len) { rootEnd = j; } else if (j !== last) { rootEnd = j + 1; } } } } } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { if (len <= 2) { ret.root = ret.dir = path; return ret; } rootEnd = 2; if (isPathSeparator$1(path.charCodeAt(2))) { if (len === 3) { ret.root = ret.dir = path; return ret; } rootEnd = 3; } } if (rootEnd > 0) { ret.root = path.slice(0, rootEnd); } let startDot = -1; let startPart = rootEnd; let end = -1; let matchedSlash = true; let i2 = path.length - 1; let preDotState = 0; for (; i2 >= rootEnd; --i2) { code = path.charCodeAt(i2); if (isPathSeparator$1(code)) { if (!matchedSlash) { startPart = i2 + 1; break; } continue; } if (end === -1) { matchedSlash = false; end = i2 + 1; } if (code === CHAR_DOT) { if (startDot === -1) { startDot = i2; } else if (preDotState !== 1) { preDotState = 1; } } else if (startDot !== -1) { preDotState = -1; } } if (end !== -1) { if (startDot === -1 || // We saw a non-dot character immediately before the dot preDotState === 0 || // The (right-most) trimmed path component is exactly '..' preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { ret.base = ret.name = path.slice(startPart, end); } else { ret.name = path.slice(startPart, startDot); ret.base = path.slice(startPart, end); ret.ext = path.slice(startDot, end); } } if (startPart > 0 && startPart !== rootEnd) { ret.dir = path.slice(0, startPart - 1); } else { ret.dir = ret.root; } return ret; }, sep: "\\", delimiter: ";", win32: null, posix: null }; const posixCwd = (() => { if (platformIsWin32) { const regexp = /\\/g; return () => { const cwd$1 = cwd().replace(regexp, "/"); return cwd$1.slice(cwd$1.indexOf("/")); }; } return () => cwd(); })(); const posix = { // path.resolve([from ...], to) resolve(...pathSegments) { let resolvedPath = ""; let resolvedAbsolute = false; for (let i2 = pathSegments.length - 1; i2 >= 0 && !resolvedAbsolute; i2--) { const path = pathSegments[i2]; validateString(path, `paths[${i2}]`); if (path.length === 0) { continue; } resolvedPath = `${path}/${resolvedPath}`; resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; } if (!resolvedAbsolute) { const cwd2 = posixCwd(); resolvedPath = `${cwd2}/${resolvedPath}`; resolvedAbsolute = cwd2.charCodeAt(0) === CHAR_FORWARD_SLASH; } resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator); if (resolvedAbsolute) { return `/${resolvedPath}`; } return resolvedPath.length > 0 ? resolvedPath : "."; }, normalize(path) { validateString(path, "path"); if (path.length === 0) { return "."; } const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator); if (path.length === 0) { if (isAbsolute) { return "/"; } return trailingSeparator ? "./" : "."; } if (trailingSeparator) { path += "/"; } return isAbsolute ? `/${path}` : path; }, isAbsolute(path) { validateString(path, "path"); return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH; }, join(...paths) { if (paths.length === 0) { return "."; } const path = []; for (let i2 = 0; i2 < paths.length; ++i2) { const arg = paths[i2]; validateString(arg, "path"); if (arg.length > 0) { path.push(arg); } } if (path.length === 0) { return "."; } return posix.normalize(path.join("/")); }, relative(from, to) { validateString(from, "from"); validateString(to, "to"); if (from === to) { return ""; } from = posix.resolve(from); to = posix.resolve(to); if (from === to) { return ""; } const fromStart = 1; const fromEnd = from.length; const fromLen = fromEnd - fromStart; const toStart = 1; const toLen = to.length - toStart; const length = fromLen < toLen ? fromLen : toLen; let lastCommonSep = -1; let i2 = 0; for (; i2 < length; i2++) { const fromCode = from.charCodeAt(fromStart + i2); if (fromCode !== to.charCodeAt(toStart + i2)) { break; } else if (fromCode === CHAR_FORWARD_SLASH) { lastCommonSep = i2; } } if (i2 === length) { if (toLen > length) { if (to.charCodeAt(toStart + i2) === CHAR_FORWARD_SLASH) { return to.slice(toStart + i2 + 1); } if (i2 === 0) { return to.slice(toStart + i2); } } else if (fromLen > length) { if (from.charCodeAt(fromStart + i2) === CHAR_FORWARD_SLASH) { lastCommonSep = i2; } else if (i2 === 0) { lastCommonSep = 0; } } } let out = ""; for (i2 = fromStart + lastCommonSep + 1; i2 <= fromEnd; ++i2) { if (i2 === fromEnd || from.charCodeAt(i2) === CHAR_FORWARD_SLASH) { out += out.length === 0 ? ".." : "/.."; } } return `${out}${to.slice(toStart + lastCommonSep)}`; }, toNamespacedPath(path) { return path; }, dirname(path) { validateString(path, "path"); if (path.length === 0) { return "."; } const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; let end = -1; let matchedSlash = true; for (let i2 = path.length - 1; i2 >= 1; --i2) { if (path.charCodeAt(i2) === CHAR_FORWARD_SLASH) { if (!matchedSlash) { end = i2; break; } } else { matchedSlash = false; } } if (end === -1) { return hasRoot ? "/" : "."; } if (hasRoot && end === 1) { return "//"; } return path.slice(0, end); }, basename(path, suffix) { if (suffix !== void 0) { validateString(suffix, "suffix"); } validateString(path, "path"); let start = 0; let end = -1; let matchedSlash = true; let i2; if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) { if (suffix === path) { return ""; } let extIdx = suffix.length - 1; let firstNonSlashEnd = -1; for (i2 = path.length - 1; i2 >= 0; --i2) { const code = path.charCodeAt(i2); if (code === CHAR_FORWARD_SLASH) { if (!matchedSlash) { start = i2 + 1; break; } } else { if (firstNonSlashEnd === -1) { matchedSlash = false; firstNonSlashEnd = i2 + 1; } if (extIdx >= 0) { if (code === suffix.charCodeAt(extIdx)) { if (--extIdx === -1) { end = i2; } } else { extIdx = -1; end = firstNonSlashEnd; } } } } if (start === end) { end = firstNonSlashEnd; } else if (end === -1) { end = path.length; } return path.slice(start, end); } for (i2 = path.length - 1; i2 >= 0; --i2) { if (path.charCodeAt(i2) === CHAR_FORWARD_SLASH) { if (!matchedSlash) { start = i2 + 1; break; } } else if (end === -1) { matchedSlash = false; end = i2 + 1; } } if (end === -1) { return ""; } return path.slice(start, end); }, extname(path) { validateString(path, "path"); let startDot = -1; let startPart = 0; let end = -1; let matchedSlash = true; let preDotState = 0; for (let i2 = path.length - 1; i2 >= 0; --i2) { const char = path[i2]; if (char === "/") { if (!matchedSlash) { startPart = i2 + 1; break; } continue; } if (end === -1) { matchedSlash = false; end = i2 + 1; } if (char === ".") { if (startDot === -1) { startDot = i2; } else if (preDotState !== 1) { preDotState = 1; } } else if (startDot !== -1) { preDotState = -1; } } if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot preDotState === 0 || // The (right-most) trimmed path component is exactly '..' preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { return ""; } return path.slice(startDot, end); }, format: _format.bind(null, "/"), parse(path) { validateString(path, "path"); const ret = { root: "", dir: "", base: "", ext: "", name: "" }; if (path.length === 0) { return ret; } const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; let start; if (isAbsolute) { ret.root = "/"; start = 1; } else { start = 0; } let startDot = -1; let startPart = 0; let end = -1; let matchedSlash = true; let i2 = path.length - 1; let preDotState = 0; for (; i2 >= start; --i2) { const code = path.charCodeAt(i2); if (code === CHAR_FORWARD_SLASH) { if (!matchedSlash) { startPart = i2 + 1; break; } continue; } if (end === -1) { matchedSlash = false; end = i2 + 1; } if (code === CHAR_DOT) { if (startDot === -1) { startDot = i2; } else if (preDotState !== 1) { preDotState = 1; } } else if (startDot !== -1) { preDotState = -1; } } if (end !== -1) { const start2 = startPart === 0 && isAbsolute ? 1 : startPart; if (startDot === -1 || // We saw a non-dot character immediately before the dot preDotState === 0 || // The (right-most) trimmed path component is exactly '..' preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { ret.base = ret.name = path.slice(start2, end); } else { ret.name = path.slice(start2, startDot); ret.base = path.slice(start2, end); ret.ext = path.slice(startDot, end); } } if (startPart > 0) { ret.dir = path.slice(0, startPart - 1); } else if (isAbsolute) { ret.dir = "/"; } return ret; }, sep: "/", delimiter: ":", win32: null, posix: null }; posix.win32 = win32.win32 = win32; posix.posix = win32.posix = posix; const normalize = platformIsWin32 ? win32.normalize : posix.normalize; const resolve$1 = platformIsWin32 ? win32.resolve : posix.resolve; const relative = platformIsWin32 ? win32.relative : posix.relative; const dirname$1 = platformIsWin32 ? win32.dirname : posix.dirname; const basename$1 = platformIsWin32 ? win32.basename : posix.basename; const extname$1 = platformIsWin32 ? win32.extname : posix.extname; const sep = platformIsWin32 ? win32.sep : posix.sep; const _schemePattern = /^\w[\w\d+.-]*$/; const _singleSlashStart = /^\//; const _doubleSlashStart = /^\/\//; function _validateUri(ret, _strict) { if (!ret.scheme && _strict) { throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`); } if (ret.scheme && !_schemePattern.test(ret.scheme)) { throw new Error("[UriError]: Scheme contains illegal characters."); } if (ret.path) { if (ret.authority) { if (!_singleSlashStart.test(ret.path)) { throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character'); } } else { if (_doubleSlashStart.test(ret.path)) { throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")'); } } } } function _schemeFix(scheme, _strict) { if (!scheme && !_strict) { return "file"; } return scheme; } function _referenceResolution(scheme, path) { switch (scheme) { case "https": case "http": case "file": if (!path) { path = _slash; } else if (path[0] !== _slash) { path = _slash + path; } break; } return path; } const _empty = ""; const _slash = "/"; const _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; class URI { static isUri(thing) { if (thing instanceof URI) { return true; } if (!thing || typeof thing !== "object") { return false; } return typeof thing.authority === "string" && typeof thing.fragment === "string" && typeof thing.path === "string" && typeof thing.query === "string" && typeof thing.scheme === "string" && typeof thing.fsPath === "string" && typeof thing.with === "function" && typeof thing.toString === "function"; } /** * @internal */ constructor(schemeOrData, authority, path, query, fragment, _strict = false) { if (typeof schemeOrData === "object") { this.scheme = schemeOrData.scheme || _empty; this.authority = schemeOrData.authority || _empty; this.path = schemeOrData.path || _empty; this.query = schemeOrData.query || _empty; this.fragment = schemeOrData.fragment || _empty; } else { this.scheme = _schemeFix(schemeOrData, _strict); this.authority = authority || _empty; this.path = _referenceResolution(this.scheme, path || _empty); this.query = query || _empty; this.fragment = fragment || _empty; _validateUri(this, _strict); } } // ---- filesystem path ----------------------- /** * Returns a string representing the corresponding file system path of this URI. * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the * platform specific path separator. * * * Will *not* validate the path for invalid characters and semantics. * * Will *not* look at the scheme of this URI. * * The result shall *not* be used for display purposes but for accessing a file on disk. * * * The *difference* to `URI#path` is the use of the platform specific separator and the handling * of UNC paths. See the below sample of a file-uri with an authority (UNC path). * * ```ts const u = URI.parse('file://server/c$/folder/file.txt') u.authority === 'server' u.path === '/shares/c$/file.txt' u.fsPath === '\\server\c$\folder\file.txt' ``` * * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path, * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working * with URIs that represent files on disk (`file` scheme). */ get fsPath() { return uriToFsPath(this, false); } // ---- modify to new ------------------------- with(change) { if (!change) { return this; } let { scheme, authority, path, query, fragment } = change; if (scheme === void 0) { scheme = this.scheme; } else if (scheme === null) { scheme = _empty; } if (authority === void 0) { authority = this.authority; } else if (authority === null) { authority = _empty; } if (path === void 0) { path = this.path; } else if (path === null) { path = _empty; } if (query === void 0) { query = this.query; } else if (query === null) { query = _empty; } if (fragment === void 0) { fragment = this.fragment; } else if (fragment === null) { fragment = _empty; } if (scheme === this.scheme && authority === this.authority && path === this.path && query === this.query && fragment === this.fragment) { return this; } return new Uri$1(scheme, authority, path, query, fragment); } // ---- parse & validate ------------------------ /** * Creates a new URI from a string, e.g. `http://www.example.com/some/path`, * `file:///usr/home`, or `scheme:with/path`. * * @param value A string which represents an URI (see `URI#toString`). */ static parse(value, _strict = false) { const match2 = _regexp.exec(value); if (!match2) { return new Uri$1(_empty, _empty, _empty, _empty, _empty); } return new Uri$1(match2[2] || _empty, percentDecode(match2[4] || _empty), percentDecode(match2[5] || _empty), percentDecode(match2[7] || _empty), percentDecode(match2[9] || _empty), _strict); } /** * Creates a new URI from a file system path, e.g. `c:\my\files`, * `/usr/home`, or `\\server\share\some\path`. * * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as** * `URI.parse('file://' + path)` because the path might contain characters that are * interpreted (# and ?). See the following sample: * ```ts const good = URI.file('/coding/c#/project1'); good.scheme === 'file'; good.path === '/coding/c#/project1'; good.fragment === ''; const bad = URI.parse('file://' + '/coding/c#/project1'); bad.scheme === 'file'; bad.path === '/coding/c'; // path is now broken bad.fragment === '/project1'; ``` * * @param path A file system path (see `URI#fsPath`) */ static file(path) { let authority = _empty; if (isWindows) { path = path.replace(/\\/g, _slash); } if (path[0] === _slash && path[1] === _slash) { const idx = path.indexOf(_slash, 2); if (idx === -1) { authority = path.substring(2); path = _slash; } else { authority = path.substring(2, idx); path = path.substring(idx) || _slash; } } return new Uri$1("file", authority, path, _empty, _empty); } /** * Creates new URI from uri components. * * Unless `strict` is `true` the scheme is defaults to be `file`. This function performs * validation and should be used for untrusted uri components retrieved from storage, * user input, command arguments etc */ static from(components, strict) { const result = new Uri$1(components.scheme, components.authority, components.path, components.query, components.fragment, strict); return result; } /** * Join a URI path with path fragments and normalizes the resulting path. * * @param uri The input URI. * @param pathFragment The path fragment to add to the URI path. * @returns The resulting URI. */ static joinPath(uri, ...pathFragment) { if (!uri.path) { throw new Error(`[UriError]: cannot call joinPath on URI without path`); } let newPath; if (isWindows && uri.scheme === "file") { newPath = URI.file(win32.join(uriToFsPath(uri, true), ...pathFragment)).path; } else { newPath = posix.join(uri.path, ...pathFragment); } return uri.with({ path: newPath }); } // ---- printing/externalize --------------------------- /** * Creates a string representation for this URI. It's guaranteed that calling * `URI.parse` with the result of this function creates an URI which is equal * to this URI. * * * The result shall *not* be used for display purposes but for externalization or transport. * * The result will be encoded using the percentage encoding and encoding happens mostly * ignore the scheme-specific encoding rules. * * @param skipEncoding Do not encode the result, default is `false` */ toString(skipEncoding = false) { return _asFormatted(this, skipEncoding); } toJSON() { return this; } static revive(data) { if (!data) { return data; } else if (data instanceof URI) { return data; } else { const result = new Uri$1(data); result._formatted = data.external ?? null; result._fsPath = data._sep === _pathSepMarker ? data.fsPath ?? null : null; return result; } } } const _pathSepMarker = isWindows ? 1 : void 0; let Uri$1 = class Uri extends URI { constructor() { super(...arguments); this._formatted = null; this._fsPath = null; } get fsPath() { if (!this._fsPath) { this._fsPath = uriToFsPath(this, false); } return this._fsPath; } toString(skipEncoding = false) { if (!skipEncoding) { if (!this._formatted) { this._formatted = _asFormatted(this, false); } return this._formatted; } else { return _asFormatted(this, true); } } toJSON() { const res = { $mid: 1 /* MarshalledId.Uri */ }; if (this._fsPath) { res.fsPath = this._fsPath; res._sep = _pathSepMarker; } if (this._formatted) { res.external = this._formatted; } if (this.path) { res.path = this.path; } if (this.scheme) { res.scheme = this.scheme; } if (this.authority) { res.authority = this.authority; } if (this.query) { res.query = this.query; } if (this.fragment) { res.fragment = this.fragment; } return res; } }; const encodeTable = { [ 58 /* CharCode.Colon */ ]: "%3A", // gen-delims [ 47 /* CharCode.Slash */ ]: "%2F", [ 63 /* CharCode.QuestionMark */ ]: "%3F", [ 35 /* CharCode.Hash */ ]: "%23", [ 91 /* CharCode.OpenSquareBracket */ ]: "%5B", [ 93 /* CharCode.CloseSquareBracket */ ]: "%5D", [ 64 /* CharCode.AtSign */ ]: "%40", [ 33 /* CharCode.ExclamationMark */ ]: "%21", // sub-delims [ 36 /* CharCode.DollarSign */ ]: "%24", [ 38 /* CharCode.Ampersand */ ]: "%26", [ 39 /* CharCode.SingleQuote */ ]: "%27", [ 40 /* CharCode.OpenParen */ ]: "%28", [ 41 /* CharCode.CloseParen */ ]: "%29", [ 42 /* CharCode.Asterisk */ ]: "%2A", [ 43 /* CharCode.Plus */ ]: "%2B", [ 44 /* CharCode.Comma */ ]: "%2C", [ 59 /* CharCode.Semicolon */ ]: "%3B", [ 61 /* CharCode.Equals */ ]: "%3D", [ 32 /* CharCode.Space */ ]: "%20" }; function encodeURIComponentFast(uriComponent, isPath, isAuthority) { let res = void 0; let nativeEncodePos = -1; for (let pos = 0; pos < uriComponent.length; pos++) { const code = uriComponent.charCodeAt(pos); if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 45 || code === 46 || code === 95 || code === 126 || isPath && code === 47 || isAuthority && code === 91 || isAuthority && code === 93 || isAuthority && code === 58) { if (nativeEncodePos !== -1) { res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); nativeEncodePos = -1; } if (res !== void 0) { res += uriComponent.charAt(pos); } } else { if (res === void 0) { res = uriComponent.substr(0, pos); } const escaped = encodeTable[code]; if (escaped !== void 0) { if (nativeEncodePos !== -1) { res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos)); nativeEncodePos = -1; } res += escaped; } else if (nativeEncodePos === -1) { nativeEncodePos = pos; } } } if (nativeEncodePos !== -1) { res += encodeURIComponent(uriComponent.substring(nativeEncodePos)); } return res !== void 0 ? res : uriComponent; } function encodeURIComponentMinimal(path) { let res = void 0; for (let pos = 0; pos < path.length; pos++) { const code = path.charCodeAt(pos); if (code === 35 || code === 63) { if (res === void 0) { res = path.substr(0, pos); } res += encodeTable[code]; } else { if (res !== void 0) { res += path[pos]; } } } return res !== void 0 ? res : path; } function uriToFsPath(uri, keepDriveLetterCasing) { let value; if (uri.authority && uri.path.length > 1 && uri.scheme === "file") { value = `//${uri.authority}${uri.path}`; } else if (uri.path.charCodeAt(0) === 47 && (uri.path.charCodeAt(1) >= 65 && uri.path.charCodeAt(1) <= 90 || uri.path.charCodeAt(1) >= 97 && uri.path.charCodeAt(1) <= 122) && uri.path.charCodeAt(2) === 58) { if (!keepDriveLetterCasing) { value = uri.path[1].toLowerCase() + uri.path.substr(2); } else { value = uri.path.substr(1); } } else { value = uri.path; } if (isWindows) { value = value.replace(/\//g, "\\"); } return value; } function _asFormatted(uri, skipEncoding) { const encoder = !skipEncoding ? encodeURIComponentFast : encodeURIComponentMinimal; let res = ""; let { scheme, authority, path, query, fragment } = uri; if (scheme) { res += scheme; res += ":"; } if (authority || scheme === "file") { res += _slash; res += _slash; } if (authority) { let idx = authority.indexOf("@"); if (idx !== -1) { const userinfo = authority.substr(0, idx); authority = authority.substr(idx + 1); idx = userinfo.lastIndexOf(":"); if (idx === -1) { res += encoder(userinfo, false, false); } else { res += encoder(userinfo.substr(0, idx), false, false); res += ":"; res += encoder(userinfo.substr(idx + 1), false, true); } res += "@"; } authority = authority.toLowerCase(); idx = authority.lastIndexOf(":"); if (idx === -1) { res += encoder(authority, false, true); } else { res += encoder(authority.substr(0, idx), false, true); res += authority.substr(idx); } } if (path) { if (path.length >= 3 && path.charCodeAt(0) === 47 && path.charCodeAt(2) === 58) { const code = path.charCodeAt(1); if (code >= 65 && code <= 90) { path = `/${String.fromCharCode(code + 32)}:${path.substr(3)}`; } } else if (path.length >= 2 && path.charCodeAt(1) === 58) { const code = path.charCodeAt(0); if (code >= 65 && code <= 90) { path = `${String.fromCharCode(code + 32)}:${path.substr(2)}`; } } res += encoder(path, true, false); } if (query) { res += "?"; res += encoder(query, false, false); } if (fragment) { res += "#"; res += !skipEncoding ? encodeURIComponentFast(fragment, false, false) : fragment; } return res; } function decodeURIComponentGraceful(str) { try { return decodeURIComponent(str); } catch { if (str.length > 3) { return str.substr(0, 3) + decodeURIComponentGraceful(str.substr(3)); } else { return str; } } } const _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g; function percentDecode(str) { if (!str.match(_rEncodedAsHex)) { return str; } return str.replace(_rEncodedAsHex, (match2) => decodeURIComponentGraceful(match2)); } var Schemas; (function(Schemas2) { Schemas2.inMemory = "inmemory"; Schemas2.vscode = "vscode"; Schemas2.internal = "private"; Schemas2.walkThrough = "walkThrough"; Schemas2.walkThroughSnippet = "walkThroughSnippet"; Schemas2.http = "http"; Schemas2.https = "https"; Schemas2.file = "file"; Schemas2.mailto = "mailto"; Schemas2.untitled = "untitled"; Schemas2.data = "data"; Schemas2.command = "command"; Schemas2.vscodeRemote = "vscode-remote"; Schemas2.vscodeRemoteResource = "vscode-remote-resource"; Schemas2.vscodeManagedRemoteResource = "vscode-managed-remote-resource"; Schemas2.vscodeUserData = "vscode-userdata"; Schemas2.vscodeCustomEditor = "vscode-custom-editor"; Schemas2.vscodeNotebookCell = "vscode-notebook-cell"; Schemas2.vscodeNotebookCellMetadata = "vscode-notebook-cell-metadata"; Schemas2.vscodeNotebookCellMetadataDiff = "vscode-notebook-cell-metadata-diff"; Schemas2.vscodeNotebookCellOutput = "vscode-notebook-cell-output"; Schemas2.vscodeNotebookCellOutputDiff = "vscode-notebook-cell-output-diff"; Schemas2.vscodeNotebookMetadata = "vscode-notebook-metadata"; Schemas2.vscodeInteractiveInput = "vscode-interactive-input"; Schemas2.vscodeSettings = "vscode-settings"; Schemas2.vscodeWorkspaceTrust = "vscode-workspace-trust"; Schemas2.vscodeTerminal = "vscode-terminal"; Schemas2.vscodeChatCodeBlock = "vscode-chat-code-block"; Schemas2.vscodeChatCodeCompareBlock = "vscode-chat-code-compare-block"; Schemas2.vscodeChatEditor = "vscode-chat-editor"; Schemas2.vscodeChatInput = "chatSessionInput"; Schemas2.vscodeChatSession = "vscode-chat-session"; Schemas2.webviewPanel = "webview-panel"; Schemas2.vscodeWebview = "vscode-webview"; Schemas2.extension = "extension"; Schemas2.vscodeFileResource = "vscode-file"; Schemas2.tmp = "tmp"; Schemas2.vsls = "vsls"; Schemas2.vscodeSourceControl = "vscode-scm"; Schemas2.commentsInput = "comment"; Schemas2.codeSetting = "code-setting"; Schemas2.outputChannel = "output"; Schemas2.accessibleView = "accessible-view"; Schemas2.chatEditingSnapshotScheme = "chat-editing-snapshot-text-model"; Schemas2.chatEditingModel = "chat-editing-text-model"; })(Schemas || (Schemas = {})); function matchesScheme(target, scheme) { if (URI.isUri(target)) { return equalsIgnoreCase(target.scheme, scheme); } else { return startsWithIgnoreCase(target, scheme + ":"); } } function matchesSomeScheme(target, ...schemes) { return schemes.some((scheme) => matchesScheme(target, scheme)); } const connectionTokenQueryName = "tkn"; class RemoteAuthoritiesImpl { constructor() { this._hosts = /* @__PURE__ */ Object.create(null); this._ports = /* @__PURE__ */ Object.create(null); this._connectionTokens = /* @__PURE__ */ Object.create(null); this._preferredWebSchema = "http"; this._delegate = null; this._serverRootPath = "/"; } setPreferredWebSchema(schema) { this._preferredWebSchema = schema; } get _remoteResourcesPath() { return posix.join(this._serverRootPath, Schemas.vscodeRemoteResource); } rewrite(uri) { if (this._delegate) { try { return this._delegate(uri); } catch (err) { onUnexpectedError(err); return uri; } } const authority = uri.authority; let host = this._hosts[authority]; if (host && host.indexOf(":") !== -1 && host.indexOf("[") === -1) { host = `[${host}]`; } const port = this._ports[authority]; const connectionToken = this._connectionTokens[authority]; let query = `path=${encodeURIComponent(uri.path)}`; if (typeof connectionToken === "string") { query += `&${connectionTokenQueryName}=${encodeURIComponent(connectionToken)}`; } return URI.from({ scheme: isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource, authority: `${host}:${port}`, path: this._remoteResourcesPath, query }); } } const RemoteAuthorities = new RemoteAuthoritiesImpl(); const VSCODE_AUTHORITY = "vscode-app"; const _FileAccessImpl = class _FileAccessImpl { /** * Returns a URI to use in contexts where the browser is responsible * for loading (e.g. fetch()) or when used within the DOM. * * **Note:** use `dom.ts#asCSSUrl` whenever the URL is to be used in CSS context. */ uriToBrowserUri(uri) { if (uri.scheme === Schemas.vscodeRemote) { return RemoteAuthorities.rewrite(uri); } if ( // ...only ever for `file` resources uri.scheme === Schemas.file && // ...and we run in native environments (isNative || // ...or web worker extensions on desktop webWorkerOrigin === `${Schemas.vscodeFileResource}://${_FileAccessImpl.FALLBACK_AUTHORITY}`) ) { return uri.with({ scheme: Schemas.vscodeFileResource, // We need to provide an authority here so that it can serve // as origin for network and loading matters in chromium. // If the URI is not coming with an authority already, we // add our own authority: uri.authority || _FileAccessImpl.FALLBACK_AUTHORITY, query: null, fragment: null }); } return uri; } }; _FileAccessImpl.FALLBACK_AUTHORITY = VSCODE_AUTHORITY; let FileAccessImpl = _FileAccessImpl; const FileAccess = new FileAccessImpl(); var COI; (function(COI2) { const coiHeaders = /* @__PURE__ */ new Map([ ["1", { "Cross-Origin-Opener-Policy": "same-origin" }], ["2", { "Cross-Origin-Embedder-Policy": "require-corp" }], ["3", { "Cross-Origin-Opener-Policy": "same-origin", "Cross-Origin-Embedder-Policy": "require-corp" }] ]); COI2.CoopAndCoep = Object.freeze(coiHeaders.get("3")); const coiSearchParamName = "vscode-coi"; function getHeadersFromQuery(url) { let params; if (typeof url === "string") { params = new URL(url).searchParams; } else if (url instanceof URL) { params = url.searchParams; } else if (URI.isUri(url)) { params = new URL(url.toString(true)).searchParams; } const value = params?.get(coiSearchParamName); if (!value) { return void 0; } return coiHeaders.get(value); } COI2.getHeadersFromQuery = getHeadersFromQuery; function addSearchParam(urlOrSearch, coop, coep) { if (!globalThis.crossOriginIsolated) { return; } const value = coop && coep ? "3" : coep ? "2" : "1"; if (urlOrSearch instanceof URLSearchParams) { urlOrSearch.set(coiSearchParamName, value); } else { urlOrSearch[coiSearchParamName] = value; } } COI2.addSearchParam = addSearchParam; })(COI || (COI = {})); const hasBuffer = typeof Buffer !== "undefined"; new Lazy(() => new Uint8Array(256)); let textDecoder; class VSBuffer { /** * When running in a nodejs context, if `actual` is not a nodejs Buffer, the backing store for * the returned `VSBuffer` instance might use a nodejs Buffer allocated from node's Buffer pool, * which is not transferrable. */ static wrap(actual) { if (hasBuffer && !Buffer.isBuffer(actual)) { actual = Buffer.from(actual.buffer, actual.byteOffset, actual.byteLength); } return new VSBuffer(actual); } constructor(buffer) { this.buffer = buffer; this.byteLength = this.buffer.byteLength; } toString() { if (hasBuffer) { return this.buffer.toString(); } else { if (!textDecoder) { textDecoder = new TextDecoder(); } return textDecoder.decode(this.buffer); } } } function readUInt16LE(source, offset) { return source[offset + 0] << 0 >>> 0 | source[offset + 1] << 8 >>> 0; } function writeUInt16LE(destination, value, offset) { destination[offset + 0] = value & 255; value = value >>> 8; destination[offset + 1] = value & 255; } function readUInt32BE(source, offset) { return source[offset] * 2 ** 24 + source[offset + 1] * 2 ** 16 + source[offset + 2] * 2 ** 8 + source[offset + 3]; } function writeUInt32BE(destination, value, offset) { destination[offset + 3] = value; value = value >>> 8; destination[offset + 2] = value; value = value >>> 8; destination[offset + 1] = value; value = value >>> 8; destination[offset] = value; } function readUInt8(source, offset) { return source[offset]; } function writeUInt8(destination, value, offset) { destination[offset] = value; } const hexChars = "0123456789abcdef"; function encodeHex({ buffer }) { let result = ""; for (let i2 = 0; i2 < buffer.length; i2++) { const byte = buffer[i2]; result += hexChars[byte >>> 4]; result += hexChars[byte & 15]; } return result; } function hash(obj) { return doHash(obj, 0); } function doHash(obj, hashVal) { switch (typeof obj) { case "object": if (obj === null) { return numberHash(349, hashVal); } else if (Array.isArray(obj)) { return arrayHash(obj, hashVal); } return objectHash(obj, hashVal); case "string": return stringHash(obj, hashVal); case "boolean": return booleanHash(obj, hashVal); case "number": return numberHash(obj, hashVal); case "undefined": return numberHash(937, hashVal); default: return numberHash(617, hashVal); } } function numberHash(val, initialHashVal) { return (initialHashVal << 5) - initialHashVal + val | 0; } function booleanHash(b, initialHashVal) { return numberHash(b ? 433 : 863, initialHashVal); } function stringHash(s, hashVal) { hashVal = numberHash(149417, hashVal); for (let i2 = 0, length = s.length; i2 < length; i2++) { hashVal = numberHash(s.charCodeAt(i2), hashVal); } return hashVal; } function arrayHash(arr, initialHashVal) { initialHashVal = numberHash(104579, initialHashVal); return arr.reduce((hashVal, item) => doHash(item, hashVal), initialHashVal); } function objectHash(obj, initialHashVal) { initialHashVal = numberHash(181387, initialHashVal); return Object.keys(obj).sort().reduce((hashVal, key) => { hashVal = stringHash(key, hashVal); return doHash(obj[key], hashVal); }, initialHashVal); } function leftRotate$2(value, bits, totalBits = 32) { const delta = totalBits - bits; const mask = ~((1 << delta) - 1); return (value << bits | (mask & value) >>> delta) >>> 0; } function toHexString(bufferOrValue, bitsize = 32) { if (bufferOrValue instanceof ArrayBuffer) { return encodeHex(VSBuffer.wrap(new Uint8Array(bufferOrValue))); } return (bufferOrValue >>> 0).toString(16).padStart(bitsize / 4, "0"); } const _StringSHA1 = class _StringSHA1 { // 80 * 4 = 320 constructor() { this._h0 = 1732584193; this._h1 = 4023233417; this._h2 = 2562383102; this._h3 = 271733878; this._h4 = 3285377520; this._buff = new Uint8Array( 64 + 3 /* to fit any utf-8 */ ); this._buffDV = new DataView(this._buff.buffer); this._buffLen = 0; this._totalLen = 0; this._leftoverHighSurrogate = 0; this._finished = false; } update(str) { const strLen = str.length; if (strLen === 0) { return; } const buff = this._buff; let buffLen = this._buffLen; let leftoverHighSurrogate = this._leftoverHighSurrogate; let charCode; let offset; if (leftoverHighSurrogate !== 0) { charCode = leftoverHighSurrogate; offset = -1; leftoverHighSurrogate = 0; } else { charCode = str.charCodeAt(0); offset = 0; } while (true) { let codePoint = charCode; if (isHighSurrogate(charCode)) { if (offset + 1 < strLen) { const nextCharCode = str.charCodeAt(offset + 1); if (isLowSurrogate(nextCharCode)) { offset++; codePoint = computeCodePoint(charCode, nextCharCode); } else { codePoint = 65533; } } else { leftoverHighSurrogate = charCode; break; } } else if (isLowSurrogate(charCode)) { codePoint = 65533; } buffLen = this._push(buff, buffLen, codePoint); offset++; if (offset < strLen) { charCode = str.charCodeAt(offset); } else { break; } } this._buffLen = buffLen; this._leftoverHighSurrogate = leftoverHighSurrogate; } _push(buff, buffLen, codePoint) { if (codePoint < 128) { buff[buffLen++] = codePoint; } else if (codePoint < 2048) { buff[buffLen++] = 192 | (codePoint & 1984) >>> 6; buff[buffLen++] = 128 | (codePoint & 63) >>> 0; } else if (codePoint < 65536) { buff[buffLen++] = 224 | (codePoint & 61440) >>> 12; buff[buffLen++] = 128 | (codePoint & 4032) >>> 6; buff[buffLen++] = 128 | (codePoint & 63) >>> 0; } else { buff[buffLen++] = 240 | (codePoint & 1835008) >>> 18; buff[buffLen++] = 128 | (codePoint & 258048) >>> 12; buff[buffLen++] = 128 | (codePoint & 4032) >>> 6; buff[buffLen++] = 128 | (codePoint & 63) >>> 0; } if (buffLen >= 64) { this._step(); buffLen -= 64; this._totalLen += 64; buff[0] = buff[64 + 0]; buff[1] = buff[64 + 1]; buff[2] = buff[64 + 2]; } return buffLen; } digest() { if (!this._finished) { this._finished = true; if (this._leftoverHighSurrogate) { this._leftoverHighSurrogate = 0; this._buffLen = this._push( this._buff, this._buffLen, 65533 /* SHA1Constant.UNICODE_REPLACEMENT */ ); } this._totalLen += this._buffLen; this._wrapUp(); } return toHexString(this._h0) + toHexString(this._h1) + toHexString(this._h2) + toHexString(this._h3) + toHexString(this._h4); } _wrapUp() { this._buff[this._buffLen++] = 128; this._buff.subarray(this._buffLen).fill(0); if (this._buffLen > 56) { this._step(); this._buff.fill(0); } const ml = 8 * this._totalLen; this._buffDV.setUint32(56, Math.floor(ml / 4294967296), false); this._buffDV.setUint32(60, ml % 4294967296, false); this._step(); } _step() { const bigBlock32 = _StringSHA1._bigBlock32; const data = this._buffDV; for (let j = 0; j < 64; j += 4) { bigBlock32.setUint32(j, data.getUint32(j, false), false); } for (let j = 64; j < 320; j += 4) { bigBlock32.setUint32(j, leftRotate$2(bigBlock32.getUint32(j - 12, false) ^ bigBlock32.getUint32(j - 32, false) ^ bigBlock32.getUint32(j - 56, false) ^ bigBlock32.getUint32(j - 64, false), 1), false); } let a = this._h0; let b = this._h1; let c = this._h2; let d = this._h3; let e = this._h4; let f, k; let temp; for (let j = 0; j < 80; j++) { if (j < 20) { f = b & c | ~b & d; k = 1518500249; } else if (j < 40) { f = b ^ c ^ d; k = 1859775393; } else if (j < 60) { f = b & c | b & d | c & d; k = 2400959708; } else { f = b ^ c ^ d; k = 3395469782; } temp = leftRotate$2(a, 5) + f + e + k + bigBlock32.getUint32(j * 4, false) & 4294967295; e = d; d = c; c = leftRotate$2(b, 30); b = a; a = temp; } this._h0 = this._h0 + a & 4294967295; this._h1 = this._h1 + b & 4294967295; this._h2 = this._h2 + c & 4294967295; this._h3 = this._h3 + d & 4294967295; this._h4 = this._h4 + e & 4294967295; } }; _StringSHA1._bigBlock32 = new DataView(new ArrayBuffer(320)); let StringSHA1 = _StringSHA1; class DebugNameData { constructor(owner, debugNameSource, referenceFn) { this.owner = owner; this.debugNameSource = debugNameSource; this.referenceFn = referenceFn; } getDebugName(target) { return getDebugName(target, this); } } const countPerName = /* @__PURE__ */ new Map(); const cachedDebugName = /* @__PURE__ */ new WeakMap(); function getDebugName(target, data) { const cached = cachedDebugName.get(target); if (cached) { return cached; } const dbgName = computeDebugName(target, data); if (dbgName) { let count = countPerName.get(dbgName) ?? 0; count++; countPerName.set(dbgName, count); const result = count === 1 ? dbgName : `${dbgName}#${count}`; cachedDebugName.set(target, result); return result; } return void 0; } function computeDebugName(self2, data) { const cached = cachedDebugName.get(self2); if (cached) { return cached; } const ownerStr = data.owner ? formatOwner(data.owner) + `.` : ""; let result; const debugNameSource = data.debugNameSource; if (debugNameSource !== void 0) { if (typeof debugNameSource === "function") { result = debugNameSource(); if (result !== void 0) { return ownerStr + result; } } else { return ownerStr + debugNameSource; } } const referenceFn = data.referenceFn; if (referenceFn !== void 0) { result = getFunctionName(referenceFn); if (result !== void 0) { return ownerStr + result; } } if (data.owner !== void 0) { const key = findKey(data.owner, self2); if (key !== void 0) { return ownerStr + key; } } return void 0; } function findKey(obj, value) { for (const key in obj) { if (obj[key] === value) { return key; } } return void 0; } const countPerClassName = /* @__PURE__ */ new Map(); const ownerId = /* @__PURE__ */ new WeakMap(); function formatOwner(owner) { const id = ownerId.get(owner); if (id) { return id; } const className2 = getClassName$1(owner) ?? "Object"; let count = countPerClassName.get(className2) ?? 0; count++; countPerClassName.set(className2, count); const result = count === 1 ? className2 : `${className2}#${count}`; ownerId.set(owner, result); return result; } function getClassName$1(obj) { const ctor = obj.constructor; if (ctor) { if (ctor.name === "Object") { return void 0; } return ctor.name; } return void 0; } function getFunctionName(fn) { const fnSrc = fn.toString(); const regexp = /\/\*\*\s*@description\s*([^*]*)\*\//; const match2 = regexp.exec(fnSrc); const result = match2 ? match2[1] : void 0; return result?.trim(); } function tail(arr) { if (arr.length === 0) { throw new Error("Invalid tail call"); } return [arr.slice(0, arr.length - 1), arr[arr.length - 1]]; } function equals$1(one, other, itemEquals2 = (a, b) => a === b) { if (one === other) { return true; } if (!one || !other) { return false; } if (one.length !== other.length) { return false; } for (let i2 = 0, len = one.length; i2 < len; i2++) { if (!itemEquals2(one[i2], other[i2])) { return false; } } return true; } function removeFastWithoutKeepingOrder(array2, index) { const last = array2.length - 1; if (index < last) { array2[index] = array2[last]; } array2.pop(); } function binarySearch(array2, key, comparator) { return binarySearch2(array2.length, (i2) => comparator(array2[i2], key)); } function binarySearch2(length, compareToKey) { let low = 0, high = length - 1; while (low <= high) { const mid = (low + high) / 2 | 0; const comp = compareToKey(mid); if (comp < 0) { low = mid + 1; } else if (comp > 0) { high = mid - 1; } else { return mid; } } return -(low + 1); } function quickSelect(nth, data, compare2) { nth = nth | 0; if (nth >= data.length) { throw new TypeError("invalid index"); } const pivotValue = data[Math.floor(data.length * Math.random())]; const lower = []; const higher = []; const pivots = []; for (const value of data) { const val = compare2(value, pivotValue); if (val < 0) { lower.push(value); } else if (val > 0) { higher.push(value); } else { pivots.push(value); } } if (nth < lower.length) { return quickSelect(nth, lower, compare2); } else if (nth < lower.length + pivots.length) { return pivots[0]; } else { return quickSelect(nth - (lower.length + pivots.length), higher, compare2); } } function groupBy(data, compare2) { const result = []; let currentGroup = void 0; for (const element of data.slice(0).sort(compare2)) { if (!currentGroup || compare2(currentGroup[0], element) !== 0) { currentGroup = [element]; result.push(currentGroup); } else { currentGroup.push(element); } } return result; } function* groupAdjacentBy(items, shouldBeGrouped) { let currentGroup; let last; for (const item of items) { if (last !== void 0 && shouldBeGrouped(last, item)) { currentGroup.push(item); } else { if (currentGroup) { yield currentGroup; } currentGroup = [item]; } last = item; } if (currentGroup) { yield currentGroup; } } function forEachAdjacent(arr, f) { for (let i2 = 0; i2 <= arr.length; i2++) { f(i2 === 0 ? void 0 : arr[i2 - 1], i2 === arr.length ? void 0 : arr[i2]); } } function forEachWithNeighbors(arr, f) { for (let i2 = 0; i2 < arr.length; i2++) { f(i2 === 0 ? void 0 : arr[i2 - 1], arr[i2], i2 + 1 === arr.length ? void 0 : arr[i2 + 1]); } } function coalesce(array2) { return array2.filter((e) => !!e); } function coalesceInPlace(array2) { let to = 0; for (let i2 = 0; i2 < array2.length; i2++) { if (!!array2[i2]) { array2[to] = array2[i2]; to += 1; } } array2.length = to; } function isFalsyOrEmpty(obj) { return !Array.isArray(obj) || obj.length === 0; } function isNonEmptyArray(obj) { return Array.isArray(obj) && obj.length > 0; } function distinct(array2, keyFn = (value) => value) { const seen = /* @__PURE__ */ new Set(); return array2.filter((element) => { const key = keyFn(element); if (seen.has(key)) { return false; } seen.add(key); return true; }); } function range(arg, to) { let from = typeof to === "number" ? arg : 0; if (typeof to === "number") { from = arg; } else { from = 0; to = arg; } const result = []; if (from <= to) { for (let i2 = from; i2 < to; i2++) { result.push(i2); } } else { for (let i2 = from; i2 > to; i2--) { result.push(i2); } } return result; } function arrayInsert(target, insertIndex, insertArr) { const before = target.slice(0, insertIndex); const after2 = target.slice(insertIndex); return before.concat(insertArr, after2); } function pushToStart(arr, value) { const index = arr.indexOf(value); if (index > -1) { arr.splice(index, 1); arr.unshift(value); } } function pushToEnd(arr, value) { const index = arr.indexOf(value); if (index > -1) { arr.splice(index, 1); arr.push(value); } } function pushMany(arr, items) { for (const item of items) { arr.push(item); } } function asArray(x) { return Array.isArray(x) ? x : [x]; } function insertInto(array2, start, newItems) { const startIdx = getActualStartIndex(array2, start); const originalLength = array2.length; const newItemsLength = newItems.length; array2.length = originalLength + newItemsLength; for (let i2 = originalLength - 1; i2 >= startIdx; i2--) { array2[i2 + newItemsLength] = array2[i2]; } for (let i2 = 0; i2 < newItemsLength; i2++) { array2[i2 + startIdx] = newItems[i2]; } } function splice$1(array2, start, deleteCount, newItems) { const index = getActualStartIndex(array2, start); let result = array2.splice(index, deleteCount); if (result === void 0) { result = []; } insertInto(array2, index, newItems); return result; } function getActualStartIndex(array2, start) { return start < 0 ? Math.max(start + array2.length, 0) : Math.min(start, array2.length); } var CompareResult; (function(CompareResult2) { function isLessThan(result) { return result < 0; } CompareResult2.isLessThan = isLessThan; function isLessThanOrEqual(result) { return result <= 0; } CompareResult2.isLessThanOrEqual = isLessThanOrEqual; function isGreaterThan(result) { return result > 0; } CompareResult2.isGreaterThan = isGreaterThan; function isNeitherLessOrGreaterThan(result) { return result === 0; } CompareResult2.isNeitherLessOrGreaterThan = isNeitherLessOrGreaterThan; CompareResult2.greaterThan = 1; CompareResult2.lessThan = -1; CompareResult2.neitherLessOrGreaterThan = 0; })(CompareResult || (CompareResult = {})); function compareBy(selector, comparator) { return (a, b) => comparator(selector(a), selector(b)); } function tieBreakComparators(...comparators) { return (item1, item2) => { for (const comparator of comparators) { const result = comparator(item1, item2); if (!CompareResult.isNeitherLessOrGreaterThan(result)) { return result; } } return CompareResult.neitherLessOrGreaterThan; }; } const numberComparator = (a, b) => a - b; const booleanComparator = (a, b) => numberComparator(a ? 1 : 0, b ? 1 : 0); function reverseOrder(comparator) { return (a, b) => -comparator(a, b); } function compareUndefinedSmallest(comparator) { return (a, b) => { if (a === void 0) { return b === void 0 ? CompareResult.neitherLessOrGreaterThan : CompareResult.lessThan; } else if (b === void 0) { return CompareResult.greaterThan; } return comparator(a, b); }; } class ArrayQueue { /** * Constructs a queue that is backed by the given array. Runtime is O(1). */ constructor(items) { this.firstIdx = 0; this.items = items; this.lastIdx = this.items.length - 1; } get length() { return this.lastIdx - this.firstIdx + 1; } /** * Consumes elements from the beginning of the queue as long as the predicate returns true. * If no elements were consumed, `null` is returned. Has a runtime of O(result.length). */ takeWhile(predicate) { let startIdx = this.firstIdx; while (startIdx < this.items.length && predicate(this.items[startIdx])) { startIdx++; } const result = startIdx === this.firstIdx ? null : this.items.slice(this.firstIdx, startIdx); this.firstIdx = startIdx; return result; } /** * Consumes elements from the end of the queue as long as the predicate returns true. * If no elements were consumed, `null` is returned. * The result has the same order as the underlying array! */ takeFromEndWhile(predicate) { let endIdx = this.lastIdx; while (endIdx >= 0 && predicate(this.items[endIdx])) { endIdx--; } const result = endIdx === this.lastIdx ? null : this.items.slice(endIdx + 1, this.lastIdx + 1); this.lastIdx = endIdx; return result; } peek() { if (this.length === 0) { return void 0; } return this.items[this.firstIdx]; } dequeue() { const result = this.items[this.firstIdx]; this.firstIdx++; return result; } takeCount(count) { const result = this.items.slice(this.firstIdx, this.firstIdx + count); this.firstIdx += count; return result; } } const _CallbackIterable = class _CallbackIterable { constructor(iterate) { this.iterate = iterate; } toArray() { const result = []; this.iterate((item) => { result.push(item); return true; }); return result; } filter(predicate) { return new _CallbackIterable((cb) => this.iterate((item) => predicate(item) ? cb(item) : true)); } map(mapFn) { return new _CallbackIterable((cb) => this.iterate((item) => cb(mapFn(item)))); } findLast(predicate) { let result; this.iterate((item) => { if (predicate(item)) { result = item; } return true; }); return result; } findLastMaxBy(comparator) { let result; let first2 = true; this.iterate((item) => { if (first2 || CompareResult.isGreaterThan(comparator(item, result))) { first2 = false; result = item; } return true; }); return result; } }; _CallbackIterable.empty = new _CallbackIterable((_callback) => { }); let CallbackIterable = _CallbackIterable; class Permutation { constructor(_indexMap) { this._indexMap = _indexMap; } /** * Returns a permutation that sorts the given array according to the given compare function. */ static createSortPermutation(arr, compareFn) { const sortIndices = Array.from(arr.keys()).sort((index1, index2) => compareFn(arr[index1], arr[index2])); return new Permutation(sortIndices); } /** * Returns a new array with the elements of the given array re-arranged according to this permutation. */ apply(arr) { return arr.map((_, index) => arr[this._indexMap[index]]); } /** * Returns a new permutation that undoes the re-arrangement of this permutation. */ inverse() { const inverseIndexMap = this._indexMap.slice(); for (let i2 = 0; i2 < this._indexMap.length; i2++) { inverseIndexMap[this._indexMap[i2]] = i2; } return new Permutation(inverseIndexMap); } } function sum(array2) { return array2.reduce((acc, value) => acc + value, 0); } const strictEquals = (a, b) => a === b; function itemsEquals(itemEquals2 = strictEquals) { return (a, b) => equals$1(a, b, itemEquals2); } function itemEquals() { return (a, b) => a.equals(b); } function equalsIfDefined(equalsOrV1, v2, equals2) { if (equals2 !== void 0) { const v1 = equalsOrV1; if (v1 === void 0 || v1 === null || v2 === void 0 || v2 === null) { return v2 === v1; } return equals2(v1, v2); } else { const equals3 = equalsOrV1; return (v1, v22) => { if (v1 === void 0 || v1 === null || v22 === void 0 || v22 === null) { return v22 === v1; } return equals3(v1, v22); }; } } function structuralEquals(a, b) { if (a === b) { return true; } if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) { return false; } for (let i2 = 0; i2 < a.length; i2++) { if (!structuralEquals(a[i2], b[i2])) { return false; } } return true; } if (a && typeof a === "object" && b && typeof b === "object") { if (Object.getPrototypeOf(a) === Object.prototype && Object.getPrototypeOf(b) === Object.prototype) { const aObj = a; const bObj = b; const keysA = Object.keys(aObj); const keysB = Object.keys(bObj); const keysBSet = new Set(keysB); if (keysA.length !== keysB.length) { return false; } for (const key of keysA) { if (!keysBSet.has(key)) { return false; } if (!structuralEquals(aObj[key], bObj[key])) { return false; } } return true; } } return false; } function handleBugIndicatingErrorRecovery(message) { const err = new Error("BugIndicatingErrorRecovery: " + message); onUnexpectedError(err); console.error("recovered from an error that indicates a bug", err); } let globalObservableLogger; function addLogger(logger) { if (!globalObservableLogger) { globalObservableLogger = logger; } else if (globalObservableLogger instanceof ComposedLogger) { globalObservableLogger.loggers.push(logger); } else { globalObservableLogger = new ComposedLogger([globalObservableLogger, logger]); } } function getLogger() { return globalObservableLogger; } class ComposedLogger { constructor(loggers) { this.loggers = loggers; } handleObservableCreated(observable, location) { for (const logger of this.loggers) { logger.handleObservableCreated(observable, location); } } handleOnListenerCountChanged(observable, newCount) { for (const logger of this.loggers) { logger.handleOnListenerCountChanged(observable, newCount); } } handleObservableUpdated(observable, info) { for (const logger of this.loggers) { logger.handleObservableUpdated(observable, info); } } handleAutorunCreated(autorun2, location) { for (const logger of this.loggers) { logger.handleAutorunCreated(autorun2, location); } } handleAutorunDisposed(autorun2) { for (const logger of this.loggers) { logger.handleAutorunDisposed(autorun2); } } handleAutorunDependencyChanged(autorun2, observable, change) { for (const logger of this.loggers) { logger.handleAutorunDependencyChanged(autorun2, observable, change); } } handleAutorunStarted(autorun2) { for (const logger of this.loggers) { logger.handleAutorunStarted(autorun2); } } handleAutorunFinished(autorun2) { for (const logger of this.loggers) { logger.handleAutorunFinished(autorun2); } } handleDerivedDependencyChanged(derived2, observable, change) { for (const logger of this.loggers) { logger.handleDerivedDependencyChanged(derived2, observable, change); } } handleDerivedCleared(observable) { for (const logger of this.loggers) { logger.handleDerivedCleared(observable); } } handleBeginTransaction(transaction2) { for (const logger of this.loggers) { logger.handleBeginTransaction(transaction2); } } handleEndTransaction(transaction2) { for (const logger of this.loggers) { logger.handleEndTransaction(transaction2); } } } function transaction(fn, getDebugName2) { const tx = new TransactionImpl(fn, getDebugName2); try { fn(tx); } finally { tx.finish(); } } let _globalTransaction = void 0; function globalTransaction(fn) { if (_globalTransaction) { fn(_globalTransaction); } else { const tx = new TransactionImpl(fn, void 0); _globalTransaction = tx; try { fn(tx); } finally { tx.finish(); _globalTransaction = void 0; } } } async function asyncTransaction(fn, getDebugName2) { const tx = new TransactionImpl(fn, getDebugName2); try { await fn(tx); } finally { tx.finish(); } } function subtransaction(tx, fn, getDebugName2) { if (!tx) { transaction(fn, getDebugName2); } else { fn(tx); } } class TransactionImpl { constructor(_fn, _getDebugName) { this._fn = _fn; this._getDebugName = _getDebugName; this._updatingObservers = []; getLogger()?.handleBeginTransaction(this); } getDebugName() { if (this._getDebugName) { return this._getDebugName(); } return getFunctionName(this._fn); } updateObserver(observer, observable) { if (!this._updatingObservers) { handleBugIndicatingErrorRecovery("Transaction already finished!"); transaction((tx) => { tx.updateObserver(observer, observable); }); return; } this._updatingObservers.push({ observer, observable }); observer.beginUpdate(observable); } finish() { const updatingObservers = this._updatingObservers; if (!updatingObservers) { handleBugIndicatingErrorRecovery("transaction.finish() has already been called!"); return; } for (let i2 = 0; i2 < updatingObservers.length; i2++) { const { observer, observable } = updatingObservers[i2]; observer.endUpdate(observable); } this._updatingObservers = null; getLogger()?.handleEndTransaction(this); } debugGetUpdatingObservers() { return this._updatingObservers; } } var DebugLocation; (function(DebugLocation2) { let enabled = false; function enable() { enabled = true; } DebugLocation2.enable = enable; function ofCaller() { if (!enabled) { return void 0; } const Err = Error; const l = Err.stackTraceLimit; Err.stackTraceLimit = 3; const stack = new Error().stack; Err.stackTraceLimit = l; return DebugLocationImpl.fromStack(stack, 2); } DebugLocation2.ofCaller = ofCaller; })(DebugLocation || (DebugLocation = {})); class DebugLocationImpl { static fromStack(stack, parentIdx) { const lines = stack.split("\n"); const location = parseLine(lines[parentIdx + 1]); if (location) { return new DebugLocationImpl(location.fileName, location.line, location.column, location.id); } else { return void 0; } } constructor(fileName, line, column, id) { this.fileName = fileName; this.line = line; this.column = column; this.id = id; } } function parseLine(stackLine) { const match2 = stackLine.match(/\((.*):(\d+):(\d+)\)/); if (match2) { return { fileName: match2[1], line: parseInt(match2[2]), column: parseInt(match2[3]), id: stackLine }; } const match22 = stackLine.match(/at ([^\(\)]*):(\d+):(\d+)/); if (match22) { return { fileName: match22[1], line: parseInt(match22[2]), column: parseInt(match22[3]), id: stackLine }; } return void 0; } let _derived; function _setDerivedOpts(derived2) { _derived = derived2; } let _recomputeInitiallyAndOnChange; function _setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange2) { _recomputeInitiallyAndOnChange = recomputeInitiallyAndOnChange2; } class ConvenientObservable { get TChange() { return null; } reportChanges() { this.get(); } /** @sealed */ read(reader) { if (reader) { return reader.readObservable(this); } else { return this.get(); } } map(fnOrOwner, fnOrUndefined, debugLocation = DebugLocation.ofCaller()) { const owner = fnOrUndefined === void 0 ? void 0 : fnOrOwner; const fn = fnOrUndefined === void 0 ? fnOrOwner : fnOrUndefined; return _derived({ owner, debugName: () => { const name = getFunctionName(fn); if (name !== void 0) { return name; } const regexp = /^\s*\(?\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\s*\)?\s*=>\s*\1(?:\??)\.([a-zA-Z_$][a-zA-Z_$0-9]*)\s*$/; const match2 = regexp.exec(fn.toString()); if (match2) { return `${this.debugName}.${match2[2]}`; } if (!owner) { return `${this.debugName} (mapped)`; } return void 0; }, debugReferenceFn: fn }, (reader) => fn(this.read(reader), reader), debugLocation); } /** * @sealed * Converts an observable of an observable value into a direct observable of the value. */ flatten() { return _derived({ owner: void 0, debugName: () => `${this.debugName} (flattened)` }, (reader) => this.read(reader).read(reader)); } recomputeInitiallyAndOnChange(store, handleValue) { store.add(_recomputeInitiallyAndOnChange(this, handleValue)); return this; } } class BaseObservable extends ConvenientObservable { constructor(debugLocation) { super(); this._observers = /* @__PURE__ */ new Set(); getLogger()?.handleObservableCreated(this, debugLocation); } addObserver(observer) { const len = this._observers.size; this._observers.add(observer); if (len === 0) { this.onFirstObserverAdded(); } if (len !== this._observers.size) { getLogger()?.handleOnListenerCountChanged(this, this._observers.size); } } removeObserver(observer) { const deleted = this._observers.delete(observer); if (deleted && this._observers.size === 0) { this.onLastObserverRemoved(); } if (deleted) { getLogger()?.handleOnListenerCountChanged(this, this._observers.size); } } onFirstObserverAdded() { } onLastObserverRemoved() { } debugGetObservers() { return this._observers; } } function observableValue(nameOrOwner, initialValue, debugLocation = DebugLocation.ofCaller()) { let debugNameData; if (typeof nameOrOwner === "string") { debugNameData = new DebugNameData(void 0, nameOrOwner, void 0); } else { debugNameData = new DebugNameData(nameOrOwner, void 0, void 0); } return new ObservableValue(debugNameData, initialValue, strictEquals, debugLocation); } class ObservableValue extends BaseObservable { get debugName() { return this._debugNameData.getDebugName(this) ?? "ObservableValue"; } constructor(_debugNameData, initialValue, _equalityComparator, debugLocation) { super(debugLocation); this._debugNameData = _debugNameData; this._equalityComparator = _equalityComparator; this._value = initialValue; getLogger()?.handleObservableUpdated(this, { hadValue: false, newValue: initialValue, change: void 0, didChange: true, oldValue: void 0 }); } get() { return this._value; } set(value, tx, change) { if (change === void 0 && this._equalityComparator(this._value, value)) { return; } let _tx; if (!tx) { tx = _tx = new TransactionImpl(() => { }, () => `Setting ${this.debugName}`); } try { const oldValue = this._value; this._setValue(value); getLogger()?.handleObservableUpdated(this, { oldValue, newValue: value, change, didChange: true, hadValue: true }); for (const observer of this._observers) { tx.updateObserver(observer, this); observer.handleChange(this, change); } } finally { if (_tx) { _tx.finish(); } } } toString() { return `${this.debugName}: ${this._value}`; } _setValue(newValue) { this._value = newValue; } debugGetState() { return { value: this._value }; } debugSetValue(value) { this._value = value; } } function disposableObservableValue(nameOrOwner, initialValue, debugLocation = DebugLocation.ofCaller()) { let debugNameData; if (typeof nameOrOwner === "string") { debugNameData = new DebugNameData(void 0, nameOrOwner, void 0); } else { debugNameData = new DebugNameData(nameOrOwner, void 0, void 0); } return new DisposableObservableValue(debugNameData, initialValue, strictEquals, debugLocation); } class DisposableObservableValue extends ObservableValue { _setValue(newValue) { if (this._value === newValue) { return; } if (this._value) { this._value.dispose(); } this._value = newValue; } dispose() { this._value?.dispose(); } } class LazyObservableValue extends BaseObservable { get debugName() { return this._debugNameData.getDebugName(this) ?? "LazyObservableValue"; } constructor(_debugNameData, initialValue, _equalityComparator, debugLocation) { super(debugLocation); this._debugNameData = _debugNameData; this._equalityComparator = _equalityComparator; this._isUpToDate = true; this._deltas = []; this._updateCounter = 0; this._value = initialValue; } get() { this._update(); return this._value; } _update() { if (this._isUpToDate) { return; } this._isUpToDate = true; if (this._deltas.length > 0) { for (const change of this._deltas) { getLogger()?.handleObservableUpdated(this, { change, didChange: true, oldValue: "(unknown)", newValue: this._value, hadValue: true }); for (const observer of this._observers) { observer.handleChange(this, change); } } this._deltas.length = 0; } else { getLogger()?.handleObservableUpdated(this, { change: void 0, didChange: true, oldValue: "(unknown)", newValue: this._value, hadValue: true }); for (const observer of this._observers) { observer.handleChange(this, void 0); } } } _beginUpdate() { this._updateCounter++; if (this._updateCounter === 1) { for (const observer of this._observers) { observer.beginUpdate(this); } } } _endUpdate() { this._updateCounter--; if (this._updateCounter === 0) { this._update(); const observers = [...this._observers]; for (const r of observers) { r.endUpdate(this); } } } addObserver(observer) { const shouldCallBeginUpdate = !this._observers.has(observer) && this._updateCounter > 0; super.addObserver(observer); if (shouldCallBeginUpdate) { observer.beginUpdate(this); } } removeObserver(observer) { const shouldCallEndUpdate = this._observers.has(observer) && this._updateCounter > 0; super.removeObserver(observer); if (shouldCallEndUpdate) { observer.endUpdate(this); } } set(value, tx, change) { if (change === void 0 && this._equalityComparator(this._value, value)) { return; } let _tx; if (!tx) { tx = _tx = new TransactionImpl(() => { }, () => `Setting ${this.debugName}`); } try { this._isUpToDate = false; this._setValue(value); if (change !== void 0) { this._deltas.push(change); } tx.updateObserver({ beginUpdate: () => this._beginUpdate(), endUpdate: () => this._endUpdate(), handleChange: (observable, change2) => { }, handlePossibleChange: (observable) => { } }, this); if (this._updateCounter > 1) { for (const observer of this._observers) { observer.handlePossibleChange(this); } } } finally { if (_tx) { _tx.finish(); } } } toString() { return `${this.debugName}: ${this._value}`; } _setValue(newValue) { this._value = newValue; } } function observableValueOpts(options, initialValue, debugLocation = DebugLocation.ofCaller()) { if (options.lazy) { return new LazyObservableValue(new DebugNameData(options.owner, options.debugName, void 0), initialValue, options.equalsFn ?? strictEquals, debugLocation); } return new ObservableValue(new DebugNameData(options.owner, options.debugName, void 0), initialValue, options.equalsFn ?? strictEquals, debugLocation); } function autorunStateToString(state) { switch (state) { case 1: return "dependenciesMightHaveChanged"; case 2: return "stale"; case 3: return "upToDate"; default: return ""; } } class AutorunObserver { get debugName() { return this._debugNameData.getDebugName(this) ?? "(anonymous)"; } constructor(_debugNameData, _runFn, _changeTracker, debugLocation) { this._debugNameData = _debugNameData; this._runFn = _runFn; this._changeTracker = _changeTracker; this._state = 2; this._updateCount = 0; this._disposed = false; this._dependencies = /* @__PURE__ */ new Set(); this._dependenciesToBeRemoved = /* @__PURE__ */ new Set(); this._isRunning = false; this._store = void 0; this._delayedStore = void 0; this._changeSummary = this._changeTracker?.createChangeSummary(void 0); getLogger()?.handleAutorunCreated(this, debugLocation); this._run(); } dispose() { if (this._disposed) { return; } this._disposed = true; for (const o of this._dependencies) { o.removeObserver(this); } this._dependencies.clear(); if (this._store !== void 0) { this._store.dispose(); } if (this._delayedStore !== void 0) { this._delayedStore.dispose(); } getLogger()?.handleAutorunDisposed(this); } _run() { const emptySet = this._dependenciesToBeRemoved; this._dependenciesToBeRemoved = this._dependencies; this._dependencies = emptySet; this._state = 3; try { if (!this._disposed) { getLogger()?.handleAutorunStarted(this); const changeSummary = this._changeSummary; const delayedStore = this._delayedStore; if (delayedStore !== void 0) { this._delayedStore = void 0; } try { this._isRunning = true; if (this._changeTracker) { this._changeTracker.beforeUpdate?.(this, changeSummary); this._changeSummary = this._changeTracker.createChangeSummary(changeSummary); } if (this._store !== void 0) { this._store.dispose(); this._store = void 0; } this._runFn(this, changeSummary); } catch (e) { onBugIndicatingError(e); } finally { this._isRunning = false; if (delayedStore !== void 0) { delayedStore.dispose(); } } } } finally { if (!this._disposed) { getLogger()?.handleAutorunFinished(this); } for (const o of this._dependenciesToBeRemoved) { o.removeObserver(this); } this._dependenciesToBeRemoved.clear(); } } toString() { return `Autorun<${this.debugName}>`; } // IObserver implementation beginUpdate(_observable) { if (this._state === 3) { this._state = 1; } this._updateCount++; } endUpdate(_observable) { try { if (this._updateCount === 1) { do { if (this._state === 1) { this._state = 3; for (const d of this._dependencies) { d.reportChanges(); if (this._state === 2) { break; } } } if (this._state !== 3) { this._run(); } } while (this._state !== 3); } } finally { this._updateCount--; } assertFn(() => this._updateCount >= 0); } handlePossibleChange(observable) { if (this._state === 3 && this._isDependency(observable)) { this._state = 1; } } handleChange(observable, change) { if (this._isDependency(observable)) { getLogger()?.handleAutorunDependencyChanged(this, observable, change); try { const shouldReact = this._changeTracker ? this._changeTracker.handleChange({ changedObservable: observable, change, didChange: (o) => o === observable }, this._changeSummary) : true; if (shouldReact) { this._state = 2; } } catch (e) { onBugIndicatingError(e); } } } _isDependency(observable) { return this._dependencies.has(observable) && !this._dependenciesToBeRemoved.has(observable); } // IReader implementation _ensureNoRunning() { if (!this._isRunning) { throw new BugIndicatingError("The reader object cannot be used outside its compute function!"); } } readObservable(observable) { this._ensureNoRunning(); if (this._disposed) { return observable.get(); } observable.addObserver(this); const value = observable.get(); this._dependencies.add(observable); this._dependenciesToBeRemoved.delete(observable); return value; } get store() { this._ensureNoRunning(); if (this._disposed) { throw new BugIndicatingError("Cannot access store after dispose"); } if (this._store === void 0) { this._store = new DisposableStore(); } return this._store; } debugGetState() { return { isRunning: this._isRunning, updateCount: this._updateCount, dependencies: this._dependencies, state: this._state, stateStr: autorunStateToString(this._state) }; } debugRerun() { if (!this._isRunning) { this._run(); } else { this._state = 2; } } } function autorun(fn, debugLocation = DebugLocation.ofCaller()) { return new AutorunObserver(new DebugNameData(void 0, void 0, fn), fn, void 0, debugLocation); } function autorunOpts(options, fn, debugLocation = DebugLocation.ofCaller()) { return new AutorunObserver(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, void 0, debugLocation); } function autorunHandleChanges(options, fn, debugLocation = DebugLocation.ofCaller()) { return new AutorunObserver(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, options.changeTracker, debugLocation); } function autorunWithStoreHandleChanges(options, fn) { const store = new DisposableStore(); const disposable = autorunHandleChanges({ owner: options.owner, debugName: options.debugName, debugReferenceFn: options.debugReferenceFn ?? fn, changeTracker: options.changeTracker }, (reader, changeSummary) => { store.clear(); fn(reader, changeSummary, store); }); return toDisposable(() => { disposable.dispose(); store.dispose(); }); } function autorunWithStore(fn) { const store = new DisposableStore(); const disposable = autorunOpts({ owner: void 0, debugName: void 0, debugReferenceFn: fn }, (reader) => { store.clear(); fn(reader, store); }); return toDisposable(() => { disposable.dispose(); store.dispose(); }); } function autorunDelta(observable, handler) { let _lastValue; return autorunOpts({ debugReferenceFn: handler }, (reader) => { const newValue = observable.read(reader); const lastValue = _lastValue; _lastValue = newValue; handler({ lastValue, newValue }); }); } function derivedStateToString(state) { switch (state) { case 0: return "initial"; case 1: return "dependenciesMightHaveChanged"; case 2: return "stale"; case 3: return "upToDate"; default: return ""; } } class Derived extends BaseObservable { get debugName() { return this._debugNameData.getDebugName(this) ?? "(anonymous)"; } constructor(_debugNameData, _computeFn, _changeTracker, _handleLastObserverRemoved = void 0, _equalityComparator, debugLocation) { super(debugLocation); this._debugNameData = _debugNameData; this._computeFn = _computeFn; this._changeTracker = _changeTracker; this._handleLastObserverRemoved = _handleLastObserverRemoved; this._equalityComparator = _equalityComparator; this._state = 0; this._value = void 0; this._updateCount = 0; this._dependencies = /* @__PURE__ */ new Set(); this._dependenciesToBeRemoved = /* @__PURE__ */ new Set(); this._changeSummary = void 0; this._isUpdating = false; this._isComputing = false; this._didReportChange = false; this._isInBeforeUpdate = false; this._isReaderValid = false; this._store = void 0; this._delayedStore = void 0; this._removedObserverToCallEndUpdateOn = null; this._changeSummary = this._changeTracker?.createChangeSummary(void 0); } onLastObserverRemoved() { this._state = 0; this._value = void 0; getLogger()?.handleDerivedCleared(this); for (const d of this._dependencies) { d.removeObserver(this); } this._dependencies.clear(); if (this._store !== void 0) { this._store.dispose(); this._store = void 0; } if (this._delayedStore !== void 0) { this._delayedStore.dispose(); this._delayedStore = void 0; } this._handleLastObserverRemoved?.(); } get() { const checkEnabled = false; if (this._isComputing && checkEnabled) ; if (this._observers.size === 0) { let result; try { this._isReaderValid = true; let changeSummary = void 0; if (this._changeTracker) { changeSummary = this._changeTracker.createChangeSummary(void 0); this._changeTracker.beforeUpdate?.(this, changeSummary); } result = this._computeFn(this, changeSummary); } finally { this._isReaderValid = false; } this.onLastObserverRemoved(); return result; } else { do { if (this._state === 1) { for (const d of this._dependencies) { d.reportChanges(); if (this._state === 2) { break; } } } if (this._state === 1) { this._state = 3; } if (this._state !== 3) { this._recompute(); } } while (this._state !== 3); return this._value; } } _recompute() { let didChange = false; this._isComputing = true; this._didReportChange = false; const emptySet = this._dependenciesToBeRemoved; this._dependenciesToBeRemoved = this._dependencies; this._dependencies = emptySet; try { const changeSummary = this._changeSummary; this._isReaderValid = true; if (this._changeTracker) { this._isInBeforeUpdate = true; this._changeTracker.beforeUpdate?.(this, changeSummary); this._isInBeforeUpdate = false; this._changeSummary = this._changeTracker?.createChangeSummary(changeSummary); } const hadValue = this._state !== 0; const oldValue = this._value; this._state = 3; const delayedStore = this._delayedStore; if (delayedStore !== void 0) { this._delayedStore = void 0; } try { if (this._store !== void 0) { this._store.dispose(); this._store = void 0; } this._value = this._computeFn(this, changeSummary); } finally { this._isReaderValid = false; for (const o of this._dependenciesToBeRemoved) { o.removeObserver(this); } this._dependenciesToBeRemoved.clear(); if (delayedStore !== void 0) { delayedStore.dispose(); } } didChange = this._didReportChange || hadValue && !this._equalityComparator(oldValue, this._value); getLogger()?.handleObservableUpdated(this, { oldValue, newValue: this._value, change: void 0, didChange, hadValue }); } catch (e) { onBugIndicatingError(e); } this._isComputing = false; if (!this._didReportChange && didChange) { for (const r of this._observers) { r.handleChange(this, void 0); } } else { this._didReportChange = false; } } toString() { return `LazyDerived<${this.debugName}>`; } // IObserver Implementation beginUpdate(_observable) { if (this._isUpdating) { throw new BugIndicatingError("Cyclic deriveds are not supported yet!"); } this._updateCount++; this._isUpdating = true; try { const propagateBeginUpdate = this._updateCount === 1; if (this._state === 3) { this._state = 1; if (!propagateBeginUpdate) { for (const r of this._observers) { r.handlePossibleChange(this); } } } if (propagateBeginUpdate) { for (const r of this._observers) { r.beginUpdate(this); } } } finally { this._isUpdating = false; } } endUpdate(_observable) { this._updateCount--; if (this._updateCount === 0) { const observers = [...this._observers]; for (const r of observers) { r.endUpdate(this); } if (this._removedObserverToCallEndUpdateOn) { const observers2 = [...this._removedObserverToCallEndUpdateOn]; this._removedObserverToCallEndUpdateOn = null; for (const r of observers2) { r.endUpdate(this); } } } assertFn(() => this._updateCount >= 0); } handlePossibleChange(observable) { if (this._state === 3 && this._dependencies.has(observable) && !this._dependenciesToBeRemoved.has(observable)) { this._state = 1; for (const r of this._observers) { r.handlePossibleChange(this); } } } handleChange(observable, change) { if (this._dependencies.has(observable) && !this._dependenciesToBeRemoved.has(observable) || this._isInBeforeUpdate) { getLogger()?.handleDerivedDependencyChanged(this, observable, change); let shouldReact = false; try { shouldReact = this._changeTracker ? this._changeTracker.handleChange({ changedObservable: observable, change, didChange: (o) => o === observable }, this._changeSummary) : true; } catch (e) { onBugIndicatingError(e); } const wasUpToDate = this._state === 3; if (shouldReact && (this._state === 1 || wasUpToDate)) { this._state = 2; if (wasUpToDate) { for (const r of this._observers) { r.handlePossibleChange(this); } } } } } // IReader Implementation _ensureReaderValid() { if (!this._isReaderValid) { throw new BugIndicatingError("The reader object cannot be used outside its compute function!"); } } readObservable(observable) { this._ensureReaderValid(); observable.addObserver(this); const value = observable.get(); this._dependencies.add(observable); this._dependenciesToBeRemoved.delete(observable); return value; } get store() { this._ensureReaderValid(); if (this._store === void 0) { this._store = new DisposableStore(); } return this._store; } addObserver(observer) { const shouldCallBeginUpdate = !this._observers.has(observer) && this._updateCount > 0; super.addObserver(observer); if (shouldCallBeginUpdate) { if (this._removedObserverToCallEndUpdateOn && this._removedObserverToCallEndUpdateOn.has(observer)) { this._removedObserverToCallEndUpdateOn.delete(observer); } else { observer.beginUpdate(this); } } } removeObserver(observer) { if (this._observers.has(observer) && this._updateCount > 0) { if (!this._removedObserverToCallEndUpdateOn) { this._removedObserverToCallEndUpdateOn = /* @__PURE__ */ new Set(); } this._removedObserverToCallEndUpdateOn.add(observer); } super.removeObserver(observer); } debugGetState() { return { state: this._state, stateStr: derivedStateToString(this._state), updateCount: this._updateCount, isComputing: this._isComputing, dependencies: this._dependencies, value: this._value }; } debugSetValue(newValue) { this._value = newValue; } debugRecompute() { if (!this._isComputing) { this._recompute(); } else { this._state = 2; } } setValue(newValue, tx, change) { this._value = newValue; const observers = this._observers; tx.updateObserver(this, this); for (const d of observers) { d.handleChange(this, change); } } } class DerivedWithSetter extends Derived { constructor(debugNameData, computeFn, changeTracker, handleLastObserverRemoved = void 0, equalityComparator, set, debugLocation) { super(debugNameData, computeFn, changeTracker, handleLastObserverRemoved, equalityComparator, debugLocation); this.set = set; } } function derived(computeFnOrOwner, computeFn, debugLocation = DebugLocation.ofCaller()) { if (computeFn !== void 0) { return new Derived(new DebugNameData(computeFnOrOwner, void 0, computeFn), computeFn, void 0, void 0, strictEquals, debugLocation); } return new Derived(new DebugNameData(void 0, void 0, computeFnOrOwner), computeFnOrOwner, void 0, void 0, strictEquals, debugLocation); } function derivedWithSetter(owner, computeFn, setter, debugLocation = DebugLocation.ofCaller()) { return new DerivedWithSetter(new DebugNameData(owner, void 0, computeFn), computeFn, void 0, void 0, strictEquals, setter, debugLocation); } function derivedOpts(options, computeFn, debugLocation = DebugLocation.ofCaller()) { return new Derived(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn), computeFn, void 0, options.onLastObserverRemoved, options.equalsFn ?? strictEquals, debugLocation); } _setDerivedOpts(derivedOpts); function derivedHandleChanges(options, computeFn, debugLocation = DebugLocation.ofCaller()) { return new Derived(new DebugNameData(options.owner, options.debugName, void 0), computeFn, options.changeTracker, void 0, options.equalityComparer ?? strictEquals, debugLocation); } function derivedDisposable(computeFnOrOwner, computeFnOrUndefined, debugLocation = DebugLocation.ofCaller()) { let computeFn; let owner; if (computeFnOrUndefined === void 0) { computeFn = computeFnOrOwner; owner = void 0; } else { owner = computeFnOrOwner; computeFn = computeFnOrUndefined; } let store = void 0; return new Derived(new DebugNameData(owner, void 0, computeFn), (r) => { if (!store) { store = new DisposableStore(); } else { store.clear(); } const result = computeFn(r); if (result) { store.add(result); } return result; }, void 0, () => { if (store) { store.dispose(); store = void 0; } }, strictEquals, debugLocation); } class ObservablePromise { constructor(promise) { this._value = observableValue(this, void 0); this.promiseResult = this._value; this.promise = promise.then((value) => { transaction((tx) => { this._value.set(new PromiseResult(value, void 0), tx); }); return value; }, (error) => { transaction((tx) => { this._value.set(new PromiseResult(void 0, error), tx); }); throw error; }); } } class PromiseResult { constructor(data, error) { this.data = data; this.error = error; } /** * Returns the value if the promise resolved, otherwise throws the error. */ getDataOrThrow() { if (this.error) { throw this.error; } return this.data; } } function waitForState(observable, predicate, isError, cancellationToken) { if (!predicate) { predicate = (state) => state !== null && state !== void 0; } return new Promise((resolve2, reject) => { let isImmediateRun = true; let shouldDispose = false; const stateObs = observable.map((state) => { return { isFinished: predicate(state), error: isError ? isError(state) : false, state }; }); const d = autorun((reader) => { const { isFinished, error, state } = stateObs.read(reader); if (isFinished || error) { if (isImmediateRun) { shouldDispose = true; } else { d.dispose(); } if (error) { reject(error === true ? state : error); } else { resolve2(state); } } }); if (cancellationToken) { const dc = cancellationToken.onCancellationRequested(() => { d.dispose(); dc.dispose(); reject(new CancellationError()); }); if (cancellationToken.isCancellationRequested) { d.dispose(); dc.dispose(); reject(new CancellationError()); return; } } isImmediateRun = false; if (shouldDispose) { d.dispose(); } }); } function observableFromEvent(...args) { let owner; let event; let getValue; let debugLocation; if (args.length === 2) { [event, getValue] = args; } else { [owner, event, getValue, debugLocation] = args; } return new FromEventObservable(new DebugNameData(owner, void 0, getValue), event, getValue, () => FromEventObservable.globalTransaction, strictEquals, debugLocation ?? DebugLocation.ofCaller()); } function observableFromEventOpts(options, event, getValue, debugLocation = DebugLocation.ofCaller()) { return new FromEventObservable(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? getValue), event, getValue, () => FromEventObservable.globalTransaction, options.equalsFn ?? strictEquals, debugLocation); } class FromEventObservable extends BaseObservable { constructor(_debugNameData, event, _getValue, _getTransaction, _equalityComparator, debugLocation) { super(debugLocation); this._debugNameData = _debugNameData; this.event = event; this._getValue = _getValue; this._getTransaction = _getTransaction; this._equalityComparator = _equalityComparator; this._hasValue = false; this.handleEvent = (args) => { const newValue = this._getValue(args); const oldValue = this._value; const didChange = !this._hasValue || !this._equalityComparator(oldValue, newValue); let didRunTransaction = false; if (didChange) { this._value = newValue; if (this._hasValue) { didRunTransaction = true; subtransaction(this._getTransaction(), (tx) => { getLogger()?.handleObservableUpdated(this, { oldValue, newValue, change: void 0, didChange, hadValue: this._hasValue }); for (const o of this._observers) { tx.updateObserver(o, this); o.handleChange(this, void 0); } }, () => { const name = this.getDebugName(); return "Event fired" + (name ? `: ${name}` : ""); }); } this._hasValue = true; } if (!didRunTransaction) { getLogger()?.handleObservableUpdated(this, { oldValue, newValue, change: void 0, didChange, hadValue: this._hasValue }); } }; } getDebugName() { return this._debugNameData.getDebugName(this); } get debugName() { const name = this.getDebugName(); return "From Event" + (name ? `: ${name}` : ""); } onFirstObserverAdded() { this._subscription = this.event(this.handleEvent); } onLastObserverRemoved() { this._subscription.dispose(); this._subscription = void 0; this._hasValue = false; this._value = void 0; } get() { if (this._subscription) { if (!this._hasValue) { this.handleEvent(void 0); } return this._value; } else { const value = this._getValue(void 0); return value; } } debugSetValue(value) { this._value = value; } debugGetState() { return { value: this._value, hasValue: this._hasValue }; } } (function(observableFromEvent2) { observableFromEvent2.Observer = FromEventObservable; function batchEventsGlobally(tx, fn) { let didSet = false; if (FromEventObservable.globalTransaction === void 0) { FromEventObservable.globalTransaction = tx; didSet = true; } try { fn(); } finally { if (didSet) { FromEventObservable.globalTransaction = void 0; } } } observableFromEvent2.batchEventsGlobally = batchEventsGlobally; })(observableFromEvent || (observableFromEvent = {})); function observableSignal(debugNameOrOwner, debugLocation = DebugLocation.ofCaller()) { if (typeof debugNameOrOwner === "string") { return new ObservableSignal(debugNameOrOwner, void 0, debugLocation); } else { return new ObservableSignal(void 0, debugNameOrOwner, debugLocation); } } class ObservableSignal extends BaseObservable { get debugName() { return new DebugNameData(this._owner, this._debugName, void 0).getDebugName(this) ?? "Observable Signal"; } toString() { return this.debugName; } constructor(_debugName, _owner, debugLocation) { super(debugLocation); this._debugName = _debugName; this._owner = _owner; } trigger(tx, change) { if (!tx) { transaction((tx2) => { this.trigger(tx2, change); }, () => `Trigger signal ${this.debugName}`); return; } for (const o of this._observers) { tx.updateObserver(o, this); o.handleChange(this, change); } } get() { } } function debouncedObservable(observable, debounceMs) { let hasValue = false; let lastValue; let timeout2 = void 0; return observableFromEvent((cb) => { const d = autorun((reader) => { const value = observable.read(reader); if (!hasValue) { hasValue = true; lastValue = value; } else { if (timeout2) { clearTimeout(timeout2); } timeout2 = setTimeout(() => { lastValue = value; cb(); }, debounceMs); } }); return { dispose() { d.dispose(); hasValue = false; lastValue = void 0; } }; }, () => { if (hasValue) { return lastValue; } else { return observable.get(); } }); } function recomputeInitiallyAndOnChange(observable, handleValue) { const o = new KeepAliveObserver(true, handleValue); observable.addObserver(o); try { o.beginUpdate(observable); } finally { o.endUpdate(observable); } return toDisposable(() => { observable.removeObserver(o); }); } _setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange); class KeepAliveObserver { constructor(_forceRecompute, _handleValue) { this._forceRecompute = _forceRecompute; this._handleValue = _handleValue; this._counter = 0; } beginUpdate(observable) { this._counter++; } endUpdate(observable) { if (this._counter === 1 && this._forceRecompute) { if (this._handleValue) { this._handleValue(observable.get()); } else { observable.reportChanges(); } } this._counter--; } handlePossibleChange(observable) { } handleChange(observable, change) { } } function derivedObservableWithCache(owner, computeFn) { let lastValue = void 0; const observable = derivedOpts({ owner, debugReferenceFn: computeFn }, (reader) => { lastValue = computeFn(reader, lastValue); return lastValue; }); return observable; } function mapObservableArrayCached(owner, items, map, keySelector) { let m = new ArrayMap$1(map, keySelector); const self2 = derivedOpts({ debugReferenceFn: map, owner, onLastObserverRemoved: () => { m.dispose(); m = new ArrayMap$1(map); } }, (reader) => { m.setItems(items.read(reader)); return m.getItems(); }); return self2; } let ArrayMap$1 = class ArrayMap { constructor(_map, _keySelector) { this._map = _map; this._keySelector = _keySelector; this._cache = /* @__PURE__ */ new Map(); this._items = []; } dispose() { this._cache.forEach((entry) => entry.store.dispose()); this._cache.clear(); } setItems(items) { const newItems = []; const itemsToRemove = new Set(this._cache.keys()); for (const item of items) { const key = this._keySelector ? this._keySelector(item) : item; let entry = this._cache.get(key); if (!entry) { const store = new DisposableStore(); const out = this._map(item, store); entry = { out, store }; this._cache.set(key, entry); } else { itemsToRemove.delete(key); } newItems.push(entry.out); } for (const item of itemsToRemove) { const entry = this._cache.get(item); entry.store.dispose(); this._cache.delete(item); } this._items = newItems; } getItems() { return this._items; } }; function recordChanges(obs) { return { createChangeSummary: (_previousChangeSummary) => { return { changes: [] }; }, handleChange(ctx, changeSummary) { for (const key in obs) { if (ctx.didChange(obs[key])) { changeSummary.changes.push({ key, change: ctx.change }); } } return true; }, beforeUpdate(reader, changeSummary) { for (const key in obs) { if (key === "changes") { throw new BugIndicatingError('property name "changes" is reserved for change tracking'); } changeSummary[key] = obs[key].read(reader); } } }; } function recordChangesLazy(getObs) { let obs = void 0; return { createChangeSummary: (_previousChangeSummary) => { return { changes: [] }; }, handleChange(ctx, changeSummary) { if (!obs) { obs = getObs(); } for (const key in obs) { if (ctx.didChange(obs[key])) { changeSummary.changes.push({ key, change: ctx.change }); } } return true; }, beforeUpdate(reader, changeSummary) { if (!obs) { obs = getObs(); } for (const key in obs) { if (key === "changes") { throw new BugIndicatingError('property name "changes" is reserved for change tracking'); } changeSummary[key] = obs[key].read(reader); } } }; } function constObservable(value) { return new ConstObservable(value); } class ConstObservable extends ConvenientObservable { constructor(value) { super(); this.value = value; } get debugName() { return this.toString(); } get() { return this.value; } addObserver(observer) { } removeObserver(observer) { } toString() { return `Const: ${this.value}`; } } function observableSignalFromEvent(owner, event, debugLocation = DebugLocation.ofCaller()) { return new FromEventObservableSignal(typeof owner === "string" ? owner : new DebugNameData(owner, void 0, void 0), event, debugLocation); } class FromEventObservableSignal extends BaseObservable { constructor(debugNameDataOrName, event, debugLocation) { super(debugLocation); this.event = event; this.handleEvent = () => { transaction((tx) => { for (const o of this._observers) { tx.updateObserver(o, this); o.handleChange(this, void 0); } }, () => this.debugName); }; this.debugName = typeof debugNameDataOrName === "string" ? debugNameDataOrName : debugNameDataOrName.getDebugName(this) ?? "Observable Signal From Event"; } onFirstObserverAdded() { this.subscription = this.event(this.handleEvent); } onLastObserverRemoved() { this.subscription.dispose(); this.subscription = void 0; } get() { } } function runOnChange(observable, cb) { let _previousValue; let _firstRun = true; return autorunWithStoreHandleChanges({ changeTracker: { createChangeSummary: () => ({ deltas: [], didChange: false }), handleChange: (context, changeSummary) => { if (context.didChange(observable)) { const e = context.change; if (e !== void 0) { changeSummary.deltas.push(e); } changeSummary.didChange = true; } return true; } } }, (reader, changeSummary) => { const value = observable.read(reader); const previousValue = _previousValue; if (changeSummary.didChange) { _previousValue = value; cb(value, previousValue, changeSummary.deltas); } if (_firstRun) { _firstRun = false; _previousValue = value; } }); } function runOnChangeWithStore(observable, cb) { const store = new DisposableStore(); const disposable = runOnChange(observable, (value, previousValue, deltas) => { store.clear(); cb(value, previousValue, deltas, store); }); return { dispose() { disposable.dispose(); store.dispose(); } }; } function runOnChangeWithCancellationToken(observable, cb) { return runOnChangeWithStore(observable, (value, previousValue, deltas, store) => { cb(value, previousValue, deltas, cancelOnDispose(store)); }); } function derivedConstOnceDefined(owner, fn) { return derivedObservableWithCache(owner, (reader, lastValue) => lastValue ?? fn(reader)); } function formatValue(value, availableLen) { switch (typeof value) { case "number": return "" + value; case "string": if (value.length + 2 <= availableLen) { return `"${value}"`; } return `"${value.substr(0, availableLen - 7)}"+...`; case "boolean": return value ? "true" : "false"; case "undefined": return "undefined"; case "object": if (value === null) { return "null"; } if (Array.isArray(value)) { return formatArray(value, availableLen); } return formatObject(value, availableLen); case "symbol": return value.toString(); case "function": return `[[Function${value.name ? " " + value.name : ""}]]`; default: return "" + value; } } function formatArray(value, availableLen) { let result = "[ "; let first2 = true; for (const val of value) { if (!first2) { result += ", "; } if (result.length - 5 > availableLen) { result += "..."; break; } first2 = false; result += `${formatValue(val, availableLen - result.length)}`; } result += " ]"; return result; } function formatObject(value, availableLen) { if (typeof value.toString === "function" && value.toString !== Object.prototype.toString) { const val = value.toString(); if (val.length <= availableLen) { return val; } return val.substring(0, availableLen - 3) + "..."; } const className2 = getClassName$1(value); let result = className2 ? className2 + "(" : "{ "; let first2 = true; for (const [key, val] of Object.entries(value)) { if (!first2) { result += ", "; } if (result.length - 5 > availableLen) { result += "..."; break; } first2 = false; result += `${key}: ${formatValue(val, availableLen - result.length)}`; } result += className2 ? ")" : " }"; return result; } class SimpleTypedRpcConnection { static createClient(channelFactory, getHandler) { return new SimpleTypedRpcConnection(channelFactory, getHandler); } constructor(_channelFactory, _getHandler) { this._channelFactory = _channelFactory; this._getHandler = _getHandler; this._channel = this._channelFactory({ handleNotification: (notificationData) => { const m = notificationData; const fn = this._getHandler().notifications[m[0]]; if (!fn) { throw new Error(`Unknown notification "${m[0]}"!`); } fn(...m[1]); }, handleRequest: (requestData) => { const m = requestData; try { const result = this._getHandler().requests[m[0]](...m[1]); return { type: "result", value: result }; } catch (e) { return { type: "error", value: e }; } } }); const requests = new Proxy({}, { get: (target, key) => { return async (...args) => { const result = await this._channel.sendRequest([key, args]); if (result.type === "error") { throw result.value; } else { return result.value; } }; } }); const notifications = new Proxy({}, { get: (target, key) => { return (...args) => { this._channel.sendNotification([key, args]); }; } }); this.api = { notifications, requests }; } } function registerDebugChannel(channelId, createClient) { const g = globalThis; let queuedNotifications = []; let curHost = void 0; const { channel, handler } = createChannelFactoryFromDebugChannel({ sendNotification: (data) => { if (curHost) { curHost.sendNotification(data); } else { queuedNotifications.push(data); } } }); let curClient = void 0; (g.$$debugValueEditor_debugChannels ?? (g.$$debugValueEditor_debugChannels = {}))[channelId] = (host) => { curClient = createClient(); curHost = host; for (const n2 of queuedNotifications) { host.sendNotification(n2); } queuedNotifications = []; return handler; }; return SimpleTypedRpcConnection.createClient(channel, () => { if (!curClient) { throw new Error("Not supported"); } return curClient; }); } function createChannelFactoryFromDebugChannel(host) { let h2; const channel = (handler) => { h2 = handler; return { sendNotification: (data) => { host.sendNotification(data); }, sendRequest: (data) => { throw new Error("not supported"); } }; }; return { channel, handler: { handleRequest: (data) => { if (data.type === "notification") { return h2?.handleNotification(data.data); } else { return h2?.handleRequest(data.data); } } } }; } class Throttler { constructor() { this._timeout = void 0; } throttle(fn, timeoutMs) { if (this._timeout === void 0) { this._timeout = setTimeout(() => { this._timeout = void 0; fn(); }, timeoutMs); } } dispose() { if (this._timeout !== void 0) { clearTimeout(this._timeout); } } } function deepAssign(target, source) { for (const key in source) { if (!!target[key] && typeof target[key] === "object" && !!source[key] && typeof source[key] === "object") { deepAssign(target[key], source[key]); } else { target[key] = source[key]; } } } function deepAssignDeleteNulls(target, source) { for (const key in source) { if (source[key] === null) { delete target[key]; } else if (!!target[key] && typeof target[key] === "object" && !!source[key] && typeof source[key] === "object") { deepAssignDeleteNulls(target[key], source[key]); } else { target[key] = source[key]; } } } const _DevToolsLogger = class _DevToolsLogger { static getInstance() { if (_DevToolsLogger._instance === void 0) { _DevToolsLogger._instance = new _DevToolsLogger(); } return _DevToolsLogger._instance; } getTransactionState() { const affected = []; const txs = [...this._activeTransactions]; if (txs.length === 0) { return void 0; } const observerQueue = txs.flatMap((t) => t.debugGetUpdatingObservers() ?? []).map((o) => o.observer); const processedObservers = /* @__PURE__ */ new Set(); while (observerQueue.length > 0) { const observer = observerQueue.shift(); if (processedObservers.has(observer)) { continue; } processedObservers.add(observer); const state = this._getInfo(observer, (d) => { if (!processedObservers.has(d)) { observerQueue.push(d); } }); if (state) { affected.push(state); } } return { names: txs.map((t) => t.getDebugName() ?? "tx"), affected }; } _getObservableInfo(observable) { const info = this._instanceInfos.get(observable); if (!info) { onUnexpectedError(new BugIndicatingError("No info found")); return void 0; } return info; } _getAutorunInfo(autorun2) { const info = this._instanceInfos.get(autorun2); if (!info) { onUnexpectedError(new BugIndicatingError("No info found")); return void 0; } return info; } _getInfo(observer, queue) { if (observer instanceof Derived) { const observersToUpdate = [...observer.debugGetObservers()]; for (const o of observersToUpdate) { queue(o); } const info = this._getObservableInfo(observer); if (!info) { return; } const observerState = observer.debugGetState(); const base = { name: observer.debugName, instanceId: info.instanceId, updateCount: observerState.updateCount }; const changedDependencies = [...info.changedObservables].map((o) => this._instanceInfos.get(o)?.instanceId).filter(isDefined); if (observerState.isComputing) { return { ...base, type: "observable/derived", state: "updating", changedDependencies, initialComputation: false }; } switch (observerState.state) { case 0: return { ...base, type: "observable/derived", state: "noValue" }; case 3: return { ...base, type: "observable/derived", state: "upToDate" }; case 2: return { ...base, type: "observable/derived", state: "stale", changedDependencies }; case 1: return { ...base, type: "observable/derived", state: "possiblyStale" }; } } else if (observer instanceof AutorunObserver) { const info = this._getAutorunInfo(observer); if (!info) { return void 0; } const base = { name: observer.debugName, instanceId: info.instanceId, updateCount: info.updateCount }; const changedDependencies = [...info.changedObservables].map((o) => this._instanceInfos.get(o).instanceId); if (observer.debugGetState().isRunning) { return { ...base, type: "autorun", state: "updating", changedDependencies }; } switch (observer.debugGetState().state) { case 3: return { ...base, type: "autorun", state: "upToDate" }; case 2: return { ...base, type: "autorun", state: "stale", changedDependencies }; case 1: return { ...base, type: "autorun", state: "possiblyStale" }; } } return void 0; } _formatObservable(obs) { const info = this._getObservableInfo(obs); if (!info) { return void 0; } return { name: obs.debugName, instanceId: info.instanceId }; } _formatObserver(obs) { if (obs instanceof Derived) { return { name: obs.toString(), instanceId: this._getObservableInfo(obs)?.instanceId }; } const autorunInfo = this._getAutorunInfo(obs); if (autorunInfo) { return { name: obs.toString(), instanceId: autorunInfo.instanceId }; } return void 0; } constructor() { this._declarationId = 0; this._instanceId = 0; this._declarations = /* @__PURE__ */ new Map(); this._instanceInfos = /* @__PURE__ */ new WeakMap(); this._aliveInstances = /* @__PURE__ */ new Map(); this._activeTransactions = /* @__PURE__ */ new Set(); this._channel = registerDebugChannel("observableDevTools", () => { return { notifications: { setDeclarationIdFilter: (declarationIds) => { }, logObservableValue: (observableId) => { console.log("logObservableValue", observableId); }, flushUpdates: () => { this._flushUpdates(); }, resetUpdates: () => { this._pendingChanges = null; this._channel.api.notifications.handleChange(this._fullState, true); } }, requests: { getDeclarations: () => { const result = {}; for (const decl of this._declarations.values()) { result[decl.id] = decl; } return { decls: result }; }, getSummarizedInstances: () => { return null; }, getObservableValueInfo: (instanceId) => { const obs = this._aliveInstances.get(instanceId); return { observers: [...obs.debugGetObservers()].map((d) => this._formatObserver(d)).filter(isDefined) }; }, getDerivedInfo: (instanceId) => { const d = this._aliveInstances.get(instanceId); return { dependencies: [...d.debugGetState().dependencies].map((d2) => this._formatObservable(d2)).filter(isDefined), observers: [...d.debugGetObservers()].map((d2) => this._formatObserver(d2)).filter(isDefined) }; }, getAutorunInfo: (instanceId) => { const obs = this._aliveInstances.get(instanceId); return { dependencies: [...obs.debugGetState().dependencies].map((d) => this._formatObservable(d)).filter(isDefined) }; }, getTransactionState: () => { return this.getTransactionState(); }, setValue: (instanceId, jsonValue) => { const obs = this._aliveInstances.get(instanceId); if (obs instanceof Derived) { obs.debugSetValue(jsonValue); } else if (obs instanceof ObservableValue) { obs.debugSetValue(jsonValue); } else if (obs instanceof FromEventObservable) { obs.debugSetValue(jsonValue); } else { throw new BugIndicatingError("Observable is not supported"); } const observers = [...obs.debugGetObservers()]; for (const d of observers) { d.beginUpdate(obs); } for (const d of observers) { d.handleChange(obs, void 0); } for (const d of observers) { d.endUpdate(obs); } }, getValue: (instanceId) => { const obs = this._aliveInstances.get(instanceId); if (obs instanceof Derived) { return formatValue(obs.debugGetState().value, 200); } else if (obs instanceof ObservableValue) { return formatValue(obs.debugGetState().value, 200); } return void 0; }, logValue: (instanceId) => { const obs = this._aliveInstances.get(instanceId); if (obs && "get" in obs) { console.log("Logged Value:", obs.get()); } else { throw new BugIndicatingError("Observable is not supported"); } }, rerun: (instanceId) => { const obs = this._aliveInstances.get(instanceId); if (obs instanceof Derived) { obs.debugRecompute(); } else if (obs instanceof AutorunObserver) { obs.debugRerun(); } else { throw new BugIndicatingError("Observable is not supported"); } } } }; }); this._pendingChanges = null; this._changeThrottler = new Throttler(); this._fullState = {}; this._flushUpdates = () => { if (this._pendingChanges !== null) { this._channel.api.notifications.handleChange(this._pendingChanges, false); this._pendingChanges = null; } }; DebugLocation.enable(); } _handleChange(update) { deepAssignDeleteNulls(this._fullState, update); if (this._pendingChanges === null) { this._pendingChanges = update; } else { deepAssign(this._pendingChanges, update); } this._changeThrottler.throttle(this._flushUpdates, 10); } _getDeclarationId(type, location) { if (!location) { return -1; } let decInfo = this._declarations.get(location.id); if (decInfo === void 0) { decInfo = { id: this._declarationId++, type, url: location.fileName, line: location.line, column: location.column }; this._declarations.set(location.id, decInfo); this._handleChange({ decls: { [decInfo.id]: decInfo } }); } return decInfo.id; } handleObservableCreated(observable, location) { const declarationId = this._getDeclarationId("observable/value", location); const info = { declarationId, instanceId: this._instanceId++, listenerCount: 0, lastValue: void 0, updateCount: 0, changedObservables: /* @__PURE__ */ new Set() }; this._instanceInfos.set(observable, info); } handleOnListenerCountChanged(observable, newCount) { const info = this._getObservableInfo(observable); if (!info) { return; } if (info.listenerCount === 0 && newCount > 0) { const type = observable instanceof Derived ? "observable/derived" : "observable/value"; this._aliveInstances.set(info.instanceId, observable); this._handleChange({ instances: { [info.instanceId]: { instanceId: info.instanceId, declarationId: info.declarationId, formattedValue: info.lastValue, type, name: observable.debugName } } }); } else if (info.listenerCount > 0 && newCount === 0) { this._handleChange({ instances: { [info.instanceId]: null } }); this._aliveInstances.delete(info.instanceId); } info.listenerCount = newCount; } handleObservableUpdated(observable, changeInfo) { if (observable instanceof Derived) { this._handleDerivedRecomputed(observable, changeInfo); return; } const info = this._getObservableInfo(observable); if (info) { if (changeInfo.didChange) { info.lastValue = formatValue(changeInfo.newValue, 30); if (info.listenerCount > 0) { this._handleChange({ instances: { [info.instanceId]: { formattedValue: info.lastValue } } }); } } } } handleAutorunCreated(autorun2, location) { const declarationId = this._getDeclarationId("autorun", location); const info = { declarationId, instanceId: this._instanceId++, updateCount: 0, changedObservables: /* @__PURE__ */ new Set() }; this._instanceInfos.set(autorun2, info); this._aliveInstances.set(info.instanceId, autorun2); if (info) { this._handleChange({ instances: { [info.instanceId]: { instanceId: info.instanceId, declarationId: info.declarationId, runCount: 0, type: "autorun", name: autorun2.debugName } } }); } } handleAutorunDisposed(autorun2) { const info = this._getAutorunInfo(autorun2); if (!info) { return; } this._handleChange({ instances: { [info.instanceId]: null } }); this._instanceInfos.delete(autorun2); this._aliveInstances.delete(info.instanceId); } handleAutorunDependencyChanged(autorun2, observable, change) { const info = this._getAutorunInfo(autorun2); if (!info) { return; } info.changedObservables.add(observable); } handleAutorunStarted(autorun2) { } handleAutorunFinished(autorun2) { const info = this._getAutorunInfo(autorun2); if (!info) { return; } info.changedObservables.clear(); info.updateCount++; this._handleChange({ instances: { [info.instanceId]: { runCount: info.updateCount } } }); } handleDerivedDependencyChanged(derived2, observable, change) { const info = this._getObservableInfo(derived2); if (info) { info.changedObservables.add(observable); } } _handleDerivedRecomputed(observable, changeInfo) { const info = this._getObservableInfo(observable); if (!info) { return; } const formattedValue = formatValue(changeInfo.newValue, 30); info.updateCount++; info.changedObservables.clear(); info.lastValue = formattedValue; if (info.listenerCount > 0) { this._handleChange({ instances: { [info.instanceId]: { formattedValue, recomputationCount: info.updateCount } } }); } } handleDerivedCleared(observable) { const info = this._getObservableInfo(observable); if (!info) { return; } info.lastValue = void 0; info.changedObservables.clear(); if (info.listenerCount > 0) { this._handleChange({ instances: { [info.instanceId]: { formattedValue: void 0 } } }); } } handleBeginTransaction(transaction2) { this._activeTransactions.add(transaction2); } handleEndTransaction(transaction2) { this._activeTransactions.delete(transaction2); } }; _DevToolsLogger._instance = void 0; let DevToolsLogger = _DevToolsLogger; if (env && env["VSCODE_DEV_DEBUG_OBSERVABLES"]) { addLogger(DevToolsLogger.getInstance()); } const { getWindow, getDocument, getWindows, getWindowsCount, getWindowId, getWindowById, onDidRegisterWindow, onWillUnregisterWindow, onDidUnregisterWindow } = (function() { const windows = /* @__PURE__ */ new Map(); ensureCodeWindow(mainWindow, 1); const mainWindowRegistration = { window: mainWindow, disposables: new DisposableStore() }; windows.set(mainWindow.vscodeWindowId, mainWindowRegistration); const onDidRegisterWindow2 = new Emitter$1(); const onDidUnregisterWindow2 = new Emitter$1(); const onWillUnregisterWindow2 = new Emitter$1(); function getWindowById2(windowId, fallbackToMain) { const window2 = typeof windowId === "number" ? windows.get(windowId) : void 0; return window2 ?? (fallbackToMain ? mainWindowRegistration : void 0); } return { onDidRegisterWindow: onDidRegisterWindow2.event, onWillUnregisterWindow: onWillUnregisterWindow2.event, onDidUnregisterWindow: onDidUnregisterWindow2.event, registerWindow(window2) { if (windows.has(window2.vscodeWindowId)) { return Disposable.None; } const disposables = new DisposableStore(); const registeredWindow = { window: window2, disposables: disposables.add(new DisposableStore()) }; windows.set(window2.vscodeWindowId, registeredWindow); disposables.add(toDisposable(() => { windows.delete(window2.vscodeWindowId); onDidUnregisterWindow2.fire(window2); })); disposables.add(addDisposableListener(window2, EventType$1.BEFORE_UNLOAD, () => { onWillUnregisterWindow2.fire(window2); })); onDidRegisterWindow2.fire(registeredWindow); return disposables; }, getWindows() { return windows.values(); }, getWindowsCount() { return windows.size; }, getWindowId(targetWindow) { return targetWindow.vscodeWindowId; }, hasWindow(windowId) { return windows.has(windowId); }, getWindowById: getWindowById2, getWindow(e) { const candidateNode = e; if (candidateNode?.ownerDocument?.defaultView) { return candidateNode.ownerDocument.defaultView.window; } const candidateEvent = e; if (candidateEvent?.view) { return candidateEvent.view.window; } return mainWindow; }, getDocument(e) { const candidateNode = e; return getWindow(candidateNode).document; } }; })(); function clearNode(node) { while (node.firstChild) { node.firstChild.remove(); } } class DomListener { constructor(node, type, handler, options) { this._node = node; this._type = type; this._handler = handler; this._options = options || false; this._node.addEventListener(this._type, this._handler, this._options); } dispose() { if (!this._handler) { return; } this._node.removeEventListener(this._type, this._handler, this._options); this._node = null; this._handler = null; } } function addDisposableListener(node, type, handler, useCaptureOrOptions) { return new DomListener(node, type, handler, useCaptureOrOptions); } function _wrapAsStandardMouseEvent(targetWindow, handler) { return function(e) { return handler(new StandardMouseEvent(targetWindow, e)); }; } function _wrapAsStandardKeyboardEvent(handler) { return function(e) { return handler(new StandardKeyboardEvent(e)); }; } const addStandardDisposableListener = function addStandardDisposableListener2(node, type, handler, useCapture) { let wrapHandler = handler; if (type === "click" || type === "mousedown" || type === "contextmenu") { wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler); } else if (type === "keydown" || type === "keypress" || type === "keyup") { wrapHandler = _wrapAsStandardKeyboardEvent(handler); } return addDisposableListener(node, type, wrapHandler, useCapture); }; const addStandardDisposableGenericMouseDownListener = function addStandardDisposableListener2(node, handler, useCapture) { const wrapHandler = _wrapAsStandardMouseEvent(getWindow(node), handler); return addDisposableGenericMouseDownListener(node, wrapHandler, useCapture); }; function addDisposableGenericMouseDownListener(node, handler, useCapture) { return addDisposableListener(node, isIOS && BrowserFeatures.pointerEvents ? EventType$1.POINTER_DOWN : EventType$1.MOUSE_DOWN, handler, useCapture); } function addDisposableGenericMouseMoveListener(node, handler, useCapture) { return addDisposableListener(node, isIOS && BrowserFeatures.pointerEvents ? EventType$1.POINTER_MOVE : EventType$1.MOUSE_MOVE, handler, useCapture); } function addDisposableGenericMouseUpListener(node, handler, useCapture) { return addDisposableListener(node, isIOS && BrowserFeatures.pointerEvents ? EventType$1.POINTER_UP : EventType$1.MOUSE_UP, handler, useCapture); } function runWhenWindowIdle(targetWindow, callback, timeout2) { return _runWhenIdle(targetWindow, callback, timeout2); } class WindowIdleValue extends AbstractIdleValue { constructor(targetWindow, executor) { super(targetWindow, executor); } } let runAtThisOrScheduleAtNextAnimationFrame; let scheduleAtNextAnimationFrame; class WindowIntervalTimer extends IntervalTimer { /** * * @param node The optional node from which the target window is determined */ constructor(node) { super(); this.defaultTarget = node && getWindow(node); } cancelAndSet(runner, interval, targetWindow) { return super.cancelAndSet(runner, interval, targetWindow ?? this.defaultTarget); } } class AnimationFrameQueueItem { constructor(runner, priority = 0) { this._runner = runner; this.priority = priority; this._canceled = false; } dispose() { this._canceled = true; } execute() { if (this._canceled) { return; } try { this._runner(); } catch (e) { onUnexpectedError(e); } } // Sort by priority (largest to lowest) static sort(a, b) { return b.priority - a.priority; } } (function() { const NEXT_QUEUE = /* @__PURE__ */ new Map(); const CURRENT_QUEUE = /* @__PURE__ */ new Map(); const animFrameRequested = /* @__PURE__ */ new Map(); const inAnimationFrameRunner = /* @__PURE__ */ new Map(); const animationFrameRunner = (targetWindowId) => { animFrameRequested.set(targetWindowId, false); const currentQueue = NEXT_QUEUE.get(targetWindowId) ?? []; CURRENT_QUEUE.set(targetWindowId, currentQueue); NEXT_QUEUE.set(targetWindowId, []); inAnimationFrameRunner.set(targetWindowId, true); while (currentQueue.length > 0) { currentQueue.sort(AnimationFrameQueueItem.sort); const top = currentQueue.shift(); top.execute(); } inAnimationFrameRunner.set(targetWindowId, false); }; scheduleAtNextAnimationFrame = (targetWindow, runner, priority = 0) => { const targetWindowId = getWindowId(targetWindow); const item = new AnimationFrameQueueItem(runner, priority); let nextQueue = NEXT_QUEUE.get(targetWindowId); if (!nextQueue) { nextQueue = []; NEXT_QUEUE.set(targetWindowId, nextQueue); } nextQueue.push(item); if (!animFrameRequested.get(targetWindowId)) { animFrameRequested.set(targetWindowId, true); targetWindow.requestAnimationFrame(() => animationFrameRunner(targetWindowId)); } return item; }; runAtThisOrScheduleAtNextAnimationFrame = (targetWindow, runner, priority) => { const targetWindowId = getWindowId(targetWindow); if (inAnimationFrameRunner.get(targetWindowId)) { const item = new AnimationFrameQueueItem(runner, priority); let currentQueue = CURRENT_QUEUE.get(targetWindowId); if (!currentQueue) { currentQueue = []; CURRENT_QUEUE.set(targetWindowId, currentQueue); } currentQueue.push(item); return item; } else { return scheduleAtNextAnimationFrame(targetWindow, runner, priority); } }; })(); function getComputedStyle(el) { return getWindow(el).getComputedStyle(el, null); } function getClientArea(element, defaultValue, fallbackElement) { const elWindow = getWindow(element); const elDocument = elWindow.document; if (element !== elDocument.body) { return new Dimension(element.clientWidth, element.clientHeight); } if (isIOS && elWindow?.visualViewport) { return new Dimension(elWindow.visualViewport.width, elWindow.visualViewport.height); } if (elWindow?.innerWidth && elWindow.innerHeight) { return new Dimension(elWindow.innerWidth, elWindow.innerHeight); } if (elDocument.body && elDocument.body.clientWidth && elDocument.body.clientHeight) { return new Dimension(elDocument.body.clientWidth, elDocument.body.clientHeight); } if (elDocument.documentElement && elDocument.documentElement.clientWidth && elDocument.documentElement.clientHeight) { return new Dimension(elDocument.documentElement.clientWidth, elDocument.documentElement.clientHeight); } throw new Error("Unable to figure out browser width and height"); } class SizeUtils { // Adapted from WinJS // Converts a CSS positioning string for the specified element to pixels. static convertToPixels(element, value) { return parseFloat(value) || 0; } static getDimension(element, cssPropertyName) { const computedStyle = getComputedStyle(element); const value = computedStyle ? computedStyle.getPropertyValue(cssPropertyName) : "0"; return SizeUtils.convertToPixels(element, value); } static getBorderLeftWidth(element) { return SizeUtils.getDimension(element, "border-left-width"); } static getBorderRightWidth(element) { return SizeUtils.getDimension(element, "border-right-width"); } static getBorderTopWidth(element) { return SizeUtils.getDimension(element, "border-top-width"); } static getBorderBottomWidth(element) { return SizeUtils.getDimension(element, "border-bottom-width"); } static getPaddingLeft(element) { return SizeUtils.getDimension(element, "padding-left"); } static getPaddingRight(element) { return SizeUtils.getDimension(element, "padding-right"); } static getPaddingTop(element) { return SizeUtils.getDimension(element, "padding-top"); } static getPaddingBottom(element) { return SizeUtils.getDimension(element, "padding-bottom"); } static getMarginLeft(element) { return SizeUtils.getDimension(element, "margin-left"); } static getMarginTop(element) { return SizeUtils.getDimension(element, "margin-top"); } static getMarginRight(element) { return SizeUtils.getDimension(element, "margin-right"); } static getMarginBottom(element) { return SizeUtils.getDimension(element, "margin-bottom"); } } const _Dimension = class _Dimension { constructor(width2, height) { this.width = width2; this.height = height; } with(width2 = this.width, height = this.height) { if (width2 !== this.width || height !== this.height) { return new _Dimension(width2, height); } else { return this; } } static is(obj) { return typeof obj === "object" && typeof obj.height === "number" && typeof obj.width === "number"; } static lift(obj) { if (obj instanceof _Dimension) { return obj; } else { return new _Dimension(obj.width, obj.height); } } static equals(a, b) { if (a === b) { return true; } if (!a || !b) { return false; } return a.width === b.width && a.height === b.height; } }; _Dimension.None = new _Dimension(0, 0); let Dimension = _Dimension; function getTopLeftOffset(element) { let offsetParent = element.offsetParent; let top = element.offsetTop; let left = element.offsetLeft; while ((element = element.parentNode) !== null && element !== element.ownerDocument.body && element !== element.ownerDocument.documentElement) { top -= element.scrollTop; const c = isShadowRoot(element) ? null : getComputedStyle(element); if (c) { left -= c.direction !== "rtl" ? element.scrollLeft : -element.scrollLeft; } if (element === offsetParent) { left += SizeUtils.getBorderLeftWidth(element); top += SizeUtils.getBorderTopWidth(element); top += element.offsetTop; left += element.offsetLeft; offsetParent = element.offsetParent; } } return { left, top }; } function size(element, width2, height) { if (typeof width2 === "number") { element.style.width = `${width2}px`; } if (typeof height === "number") { element.style.height = `${height}px`; } } function getDomNodePagePosition(domNode) { const bb = domNode.getBoundingClientRect(); const window2 = getWindow(domNode); return { left: bb.left + window2.scrollX, top: bb.top + window2.scrollY, width: bb.width, height: bb.height }; } function getDomNodeZoomLevel(domNode) { let testElement = domNode; let zoom = 1; do { const elementZoomLevel = getComputedStyle(testElement).zoom; if (elementZoomLevel !== null && elementZoomLevel !== void 0 && elementZoomLevel !== "1") { zoom *= elementZoomLevel; } testElement = testElement.parentElement; } while (testElement !== null && testElement !== testElement.ownerDocument.documentElement); return zoom; } function getTotalWidth(element) { const margin = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element); return element.offsetWidth + margin; } function getContentWidth(element) { const border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element); const padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element); return element.offsetWidth - border - padding; } function getContentHeight(element) { const border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element); const padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element); return element.offsetHeight - border - padding; } function getTotalHeight(element) { const margin = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element); return element.offsetHeight + margin; } function isAncestor$1(testChild, testAncestor) { return Boolean(testAncestor?.contains(testChild)); } function findParentWithClass(node, clazz, stopAtClazzOrNode) { while (node && node.nodeType === node.ELEMENT_NODE) { if (node.classList.contains(clazz)) { return node; } if (stopAtClazzOrNode) { if (typeof stopAtClazzOrNode === "string") { if (node.classList.contains(stopAtClazzOrNode)) { return null; } } else { if (node === stopAtClazzOrNode) { return null; } } } node = node.parentNode; } return null; } function hasParentWithClass(node, clazz, stopAtClazzOrNode) { return !!findParentWithClass(node, clazz, stopAtClazzOrNode); } function isShadowRoot(node) { return node && !!node.host && !!node.mode; } function isInShadowDOM(domNode) { return !!getShadowRoot(domNode); } function getShadowRoot(domNode) { while (domNode.parentNode) { if (domNode === domNode.ownerDocument?.body) { return null; } domNode = domNode.parentNode; } return isShadowRoot(domNode) ? domNode : null; } function getActiveElement() { let result = getActiveDocument().activeElement; while (result?.shadowRoot) { result = result.shadowRoot.activeElement; } return result; } function isActiveElement(element) { return getActiveElement() === element; } function isAncestorOfActiveElement(ancestor) { return isAncestor$1(getActiveElement(), ancestor); } function getActiveDocument() { if (getWindowsCount() <= 1) { return mainWindow.document; } const documents = Array.from(getWindows()).map(({ window: window2 }) => window2.document); return documents.find((doc) => doc.hasFocus()) ?? mainWindow.document; } function getActiveWindow() { const document2 = getActiveDocument(); return document2.defaultView?.window ?? mainWindow; } const sharedMutationObserver = new class { constructor() { this.mutationObservers = /* @__PURE__ */ new Map(); } observe(target, disposables, options) { let mutationObserversPerTarget = this.mutationObservers.get(target); if (!mutationObserversPerTarget) { mutationObserversPerTarget = /* @__PURE__ */ new Map(); this.mutationObservers.set(target, mutationObserversPerTarget); } const optionsHash = hash(options); let mutationObserverPerOptions = mutationObserversPerTarget.get(optionsHash); if (!mutationObserverPerOptions) { const onDidMutate = new Emitter$1(); const observer = new MutationObserver((mutations) => onDidMutate.fire(mutations)); observer.observe(target, options); const resolvedMutationObserverPerOptions = mutationObserverPerOptions = { users: 1, observer, onDidMutate: onDidMutate.event }; disposables.add(toDisposable(() => { resolvedMutationObserverPerOptions.users -= 1; if (resolvedMutationObserverPerOptions.users === 0) { onDidMutate.dispose(); observer.disconnect(); mutationObserversPerTarget?.delete(optionsHash); if (mutationObserversPerTarget?.size === 0) { this.mutationObservers.delete(target); } } })); mutationObserversPerTarget.set(optionsHash, mutationObserverPerOptions); } else { mutationObserverPerOptions.users += 1; } return mutationObserverPerOptions.onDidMutate; } }(); function isHTMLElement(e) { return e instanceof HTMLElement || e instanceof getWindow(e).HTMLElement; } function isHTMLAnchorElement(e) { return e instanceof HTMLAnchorElement || e instanceof getWindow(e).HTMLAnchorElement; } function isSVGElement(e) { return e instanceof SVGElement || e instanceof getWindow(e).SVGElement; } function isMouseEvent(e) { return e instanceof MouseEvent || e instanceof getWindow(e).MouseEvent; } function isKeyboardEvent(e) { return e instanceof KeyboardEvent || e instanceof getWindow(e).KeyboardEvent; } const EventType$1 = { // Mouse CLICK: "click", AUXCLICK: "auxclick", DBLCLICK: "dblclick", MOUSE_UP: "mouseup", MOUSE_DOWN: "mousedown", MOUSE_OVER: "mouseover", MOUSE_MOVE: "mousemove", MOUSE_OUT: "mouseout", MOUSE_ENTER: "mouseenter", MOUSE_LEAVE: "mouseleave", MOUSE_WHEEL: "wheel", POINTER_UP: "pointerup", POINTER_DOWN: "pointerdown", POINTER_MOVE: "pointermove", POINTER_LEAVE: "pointerleave", CONTEXT_MENU: "contextmenu", // Keyboard KEY_DOWN: "keydown", KEY_UP: "keyup", BEFORE_UNLOAD: "beforeunload", FOCUS: "focus", FOCUS_IN: "focusin", FOCUS_OUT: "focusout", BLUR: "blur", INPUT: "input", // Drag DRAG_START: "dragstart", DRAG: "drag", DRAG_ENTER: "dragenter", DRAG_LEAVE: "dragleave", DRAG_OVER: "dragover", DROP: "drop", DRAG_END: "dragend" }; function isEventLike(obj) { const candidate = obj; return !!(candidate && typeof candidate.preventDefault === "function" && typeof candidate.stopPropagation === "function"); } const EventHelper = { stop: (e, cancelBubble) => { e.preventDefault(); if (cancelBubble) { e.stopPropagation(); } return e; } }; function saveParentsScrollTop(node) { const r = []; for (let i2 = 0; node && node.nodeType === node.ELEMENT_NODE; i2++) { r[i2] = node.scrollTop; node = node.parentNode; } return r; } function restoreParentsScrollTop(node, state) { for (let i2 = 0; node && node.nodeType === node.ELEMENT_NODE; i2++) { if (node.scrollTop !== state[i2]) { node.scrollTop = state[i2]; } node = node.parentNode; } } let FocusTracker$1 = class FocusTracker2 extends Disposable { get onDidFocus() { return this._onDidFocus.event; } get onDidBlur() { return this._onDidBlur.event; } static hasFocusWithin(element) { if (isHTMLElement(element)) { const shadowRoot = getShadowRoot(element); const activeElement = shadowRoot ? shadowRoot.activeElement : element.ownerDocument.activeElement; return isAncestor$1(activeElement, element); } else { const window2 = element; return isAncestor$1(window2.document.activeElement, window2.document); } } constructor(element) { super(); this._onDidFocus = this._register(new Emitter$1()); this._onDidBlur = this._register(new Emitter$1()); let hasFocus = FocusTracker2.hasFocusWithin(element); let loosingFocus = false; const onFocus = () => { loosingFocus = false; if (!hasFocus) { hasFocus = true; this._onDidFocus.fire(); } }; const onBlur = () => { if (hasFocus) { loosingFocus = true; (isHTMLElement(element) ? getWindow(element) : element).setTimeout(() => { if (loosingFocus) { loosingFocus = false; hasFocus = false; this._onDidBlur.fire(); } }, 0); } }; this._refreshStateHandler = () => { const currentNodeHasFocus = FocusTracker2.hasFocusWithin(element); if (currentNodeHasFocus !== hasFocus) { if (hasFocus) { onBlur(); } else { onFocus(); } } }; this._register(addDisposableListener(element, EventType$1.FOCUS, onFocus, true)); this._register(addDisposableListener(element, EventType$1.BLUR, onBlur, true)); if (isHTMLElement(element)) { this._register(addDisposableListener(element, EventType$1.FOCUS_IN, () => this._refreshStateHandler())); this._register(addDisposableListener(element, EventType$1.FOCUS_OUT, () => this._refreshStateHandler())); } } }; function trackFocus(element) { return new FocusTracker$1(element); } function after(sibling, child) { sibling.after(child); return child; } function append$2(parent, ...children) { parent.append(...children); if (children.length === 1 && typeof children[0] !== "string") { return children[0]; } } function prepend$2(parent, child) { parent.insertBefore(child, parent.firstChild); return child; } function reset(parent, ...children) { parent.textContent = ""; append$2(parent, ...children); } const SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/; var Namespace; (function(Namespace2) { Namespace2["HTML"] = "http://www.w3.org/1999/xhtml"; Namespace2["SVG"] = "http://www.w3.org/2000/svg"; })(Namespace || (Namespace = {})); function _$(namespace, description, attrs, ...children) { const match2 = SELECTOR_REGEX.exec(description); if (!match2) { throw new Error("Bad use of emmet"); } const tagName = match2[1] || "div"; let result; if (namespace !== Namespace.HTML) { result = document.createElementNS(namespace, tagName); } else { result = document.createElement(tagName); } if (match2[3]) { result.id = match2[3]; } if (match2[4]) { result.className = match2[4].replace(/\./g, " ").trim(); } if (attrs) { Object.entries(attrs).forEach(([name, value]) => { if (typeof value === "undefined") { return; } if (/^on\w+$/.test(name)) { result[name] = value; } else if (name === "selected") { if (value) { result.setAttribute(name, "true"); } } else { result.setAttribute(name, value); } }); } result.append(...children); return result; } function $$l(description, attrs, ...children) { return _$(Namespace.HTML, description, attrs, ...children); } $$l.SVG = function(description, attrs, ...children) { return _$(Namespace.SVG, description, attrs, ...children); }; function setVisibility(visible, ...elements) { if (visible) { show(...elements); } else { hide(...elements); } } function show(...elements) { for (const element of elements) { element.style.display = ""; element.removeAttribute("aria-hidden"); } } function hide(...elements) { for (const element of elements) { element.style.display = "none"; element.setAttribute("aria-hidden", "true"); } } function computeScreenAwareSize(window2, cssPx) { const screenPx = window2.devicePixelRatio * cssPx; return Math.max(1, Math.floor(screenPx)) / window2.devicePixelRatio; } function windowOpenNoOpener(url) { mainWindow.open(url, "_blank", "noopener"); } function animate(targetWindow, fn) { const step = () => { fn(); stepDisposable = scheduleAtNextAnimationFrame(targetWindow, step); }; let stepDisposable = scheduleAtNextAnimationFrame(targetWindow, step); return toDisposable(() => stepDisposable.dispose()); } RemoteAuthorities.setPreferredWebSchema(/^https:/.test(mainWindow.location.href) ? "https" : "http"); class ModifierKeyEmitter extends Emitter$1 { constructor() { super(); this._subscriptions = new DisposableStore(); this._keyStatus = { altKey: false, shiftKey: false, ctrlKey: false, metaKey: false }; this._subscriptions.add(Event.runAndSubscribe(onDidRegisterWindow, ({ window: window2, disposables }) => this.registerListeners(window2, disposables), { window: mainWindow, disposables: this._subscriptions })); } registerListeners(window2, disposables) { disposables.add(addDisposableListener(window2, "keydown", (e) => { if (e.defaultPrevented) { return; } const event = new StandardKeyboardEvent(e); if (event.keyCode === 6 && e.repeat) { return; } if (e.altKey && !this._keyStatus.altKey) { this._keyStatus.lastKeyPressed = "alt"; } else if (e.ctrlKey && !this._keyStatus.ctrlKey) { this._keyStatus.lastKeyPressed = "ctrl"; } else if (e.metaKey && !this._keyStatus.metaKey) { this._keyStatus.lastKeyPressed = "meta"; } else if (e.shiftKey && !this._keyStatus.shiftKey) { this._keyStatus.lastKeyPressed = "shift"; } else if (event.keyCode !== 6) { this._keyStatus.lastKeyPressed = void 0; } else { return; } this._keyStatus.altKey = e.altKey; this._keyStatus.ctrlKey = e.ctrlKey; this._keyStatus.metaKey = e.metaKey; this._keyStatus.shiftKey = e.shiftKey; if (this._keyStatus.lastKeyPressed) { this._keyStatus.event = e; this.fire(this._keyStatus); } }, true)); disposables.add(addDisposableListener(window2, "keyup", (e) => { if (e.defaultPrevented) { return; } if (!e.altKey && this._keyStatus.altKey) { this._keyStatus.lastKeyReleased = "alt"; } else if (!e.ctrlKey && this._keyStatus.ctrlKey) { this._keyStatus.lastKeyReleased = "ctrl"; } else if (!e.metaKey && this._keyStatus.metaKey) { this._keyStatus.lastKeyReleased = "meta"; } else if (!e.shiftKey && this._keyStatus.shiftKey) { this._keyStatus.lastKeyReleased = "shift"; } else { this._keyStatus.lastKeyReleased = void 0; } if (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) { this._keyStatus.lastKeyPressed = void 0; } this._keyStatus.altKey = e.altKey; this._keyStatus.ctrlKey = e.ctrlKey; this._keyStatus.metaKey = e.metaKey; this._keyStatus.shiftKey = e.shiftKey; if (this._keyStatus.lastKeyReleased) { this._keyStatus.event = e; this.fire(this._keyStatus); } }, true)); disposables.add(addDisposableListener(window2.document.body, "mousedown", () => { this._keyStatus.lastKeyPressed = void 0; }, true)); disposables.add(addDisposableListener(window2.document.body, "mouseup", () => { this._keyStatus.lastKeyPressed = void 0; }, true)); disposables.add(addDisposableListener(window2.document.body, "mousemove", (e) => { if (e.buttons) { this._keyStatus.lastKeyPressed = void 0; } }, true)); disposables.add(addDisposableListener(window2, "blur", () => { this.resetKeyStatus(); })); } get keyStatus() { return this._keyStatus; } /** * Allows to explicitly reset the key status based on more knowledge (#109062) */ resetKeyStatus() { this.doResetKeyStatus(); this.fire(this._keyStatus); } doResetKeyStatus() { this._keyStatus = { altKey: false, shiftKey: false, ctrlKey: false, metaKey: false }; } static getInstance() { if (!ModifierKeyEmitter.instance) { ModifierKeyEmitter.instance = new ModifierKeyEmitter(); } return ModifierKeyEmitter.instance; } dispose() { super.dispose(); this._subscriptions.dispose(); } } class DragAndDropObserver extends Disposable { constructor(element, callbacks) { super(); this.element = element; this.callbacks = callbacks; this.counter = 0; this.dragStartTime = 0; this.registerListeners(); } registerListeners() { if (this.callbacks.onDragStart) { this._register(addDisposableListener(this.element, EventType$1.DRAG_START, (e) => { this.callbacks.onDragStart?.(e); })); } if (this.callbacks.onDrag) { this._register(addDisposableListener(this.element, EventType$1.DRAG, (e) => { this.callbacks.onDrag?.(e); })); } this._register(addDisposableListener(this.element, EventType$1.DRAG_ENTER, (e) => { this.counter++; this.dragStartTime = e.timeStamp; this.callbacks.onDragEnter?.(e); })); this._register(addDisposableListener(this.element, EventType$1.DRAG_OVER, (e) => { e.preventDefault(); this.callbacks.onDragOver?.(e, e.timeStamp - this.dragStartTime); })); this._register(addDisposableListener(this.element, EventType$1.DRAG_LEAVE, (e) => { this.counter--; if (this.counter === 0) { this.dragStartTime = 0; this.callbacks.onDragLeave?.(e); } })); this._register(addDisposableListener(this.element, EventType$1.DRAG_END, (e) => { this.counter = 0; this.dragStartTime = 0; this.callbacks.onDragEnd?.(e); })); this._register(addDisposableListener(this.element, EventType$1.DROP, (e) => { this.counter = 0; this.dragStartTime = 0; this.callbacks.onDrop?.(e); })); } } const H_REGEX = /(?[\w\-]+)?(?:#(?[\w\-]+))?(?(?:\.(?:[\w\-]+))*)(?:@(?(?:[\w\_])+))?/; function h(tag2, ...args) { let attributes; let children; if (Array.isArray(args[0])) { attributes = {}; children = args[0]; } else { attributes = args[0] || {}; children = args[1]; } const match2 = H_REGEX.exec(tag2); if (!match2 || !match2.groups) { throw new Error("Bad use of h"); } const tagName = match2.groups["tag"] || "div"; const el = document.createElement(tagName); if (match2.groups["id"]) { el.id = match2.groups["id"]; } const classNames2 = []; if (match2.groups["class"]) { for (const className2 of match2.groups["class"].split(".")) { if (className2 !== "") { classNames2.push(className2); } } } if (attributes.className !== void 0) { for (const className2 of attributes.className.split(".")) { if (className2 !== "") { classNames2.push(className2); } } } if (classNames2.length > 0) { el.className = classNames2.join(" "); } const result = {}; if (match2.groups["name"]) { result[match2.groups["name"]] = el; } if (children) { for (const c of children) { if (isHTMLElement(c)) { el.appendChild(c); } else if (typeof c === "string") { el.append(c); } else if ("root" in c) { Object.assign(result, c); el.appendChild(c.root); } } } for (const [key, value] of Object.entries(attributes)) { if (key === "className") { continue; } else if (key === "style") { for (const [cssKey, cssValue] of Object.entries(value)) { el.style.setProperty(camelCaseToHyphenCase(cssKey), typeof cssValue === "number" ? cssValue + "px" : "" + cssValue); } } else if (key === "tabIndex") { el.tabIndex = value; } else { el.setAttribute(camelCaseToHyphenCase(key), value.toString()); } } result["root"] = el; return result; } function camelCaseToHyphenCase(str) { return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(); } function isEditableElement(element) { return element.tagName.toLowerCase() === "input" || element.tagName.toLowerCase() === "textarea" || isHTMLElement(element) && !!element.editContext; } var n; (function(n2) { function nodeNs(elementNs = void 0) { return (tag2, attributes, children) => { const className2 = attributes.class; delete attributes.class; const ref2 = attributes.ref; delete attributes.ref; const obsRef = attributes.obsRef; delete attributes.obsRef; return new ObserverNodeWithElement(tag2, ref2, obsRef, elementNs, className2, attributes, children); }; } function node(tag2, elementNs = void 0) { const f = nodeNs(elementNs); return (attributes, children) => { return f(tag2, attributes, children); }; } n2.div = node("div"); n2.elem = nodeNs(void 0); n2.svg = node("svg", "http://www.w3.org/2000/svg"); n2.svgElem = nodeNs("http://www.w3.org/2000/svg"); function ref() { let value = void 0; const result = function(val) { value = val; }; Object.defineProperty(result, "element", { get() { if (!value) { throw new BugIndicatingError("Make sure the ref is set before accessing the element. Maybe wrong initialization order?"); } return value; } }); return result; } n2.ref = ref; })(n || (n = {})); class ObserverNode { constructor(tag2, ref, obsRef, ns, className2, attributes, children) { this._deriveds = []; this._element = ns ? document.createElementNS(ns, tag2) : document.createElement(tag2); if (ref) { ref(this._element); } if (obsRef) { this._deriveds.push(derived((_reader) => { obsRef(this); _reader.store.add({ dispose: () => { obsRef(null); } }); })); } if (className2) { if (hasObservable(className2)) { this._deriveds.push(derived(this, (reader) => { setClassName(this._element, getClassName(className2, reader)); })); } else { setClassName(this._element, getClassName(className2, void 0)); } } for (const [key, value] of Object.entries(attributes)) { if (key === "style") { for (const [cssKey, cssValue] of Object.entries(value)) { const key2 = camelCaseToHyphenCase(cssKey); if (isObservable(cssValue)) { this._deriveds.push(derivedOpts({ owner: this, debugName: () => `set.style.${key2}` }, (reader) => { this._element.style.setProperty(key2, convertCssValue(cssValue.read(reader))); })); } else { this._element.style.setProperty(key2, convertCssValue(cssValue)); } } } else if (key === "tabIndex") { if (isObservable(value)) { this._deriveds.push(derived(this, (reader) => { this._element.tabIndex = value.read(reader); })); } else { this._element.tabIndex = value; } } else if (key.startsWith("on")) { this._element[key] = value; } else { if (isObservable(value)) { this._deriveds.push(derivedOpts({ owner: this, debugName: () => `set.${key}` }, (reader) => { setOrRemoveAttribute(this._element, key, value.read(reader)); })); } else { setOrRemoveAttribute(this._element, key, value); } } } if (children) { let getChildren = function(reader, children2) { if (isObservable(children2)) { return getChildren(reader, children2.read(reader)); } if (Array.isArray(children2)) { return children2.flatMap((c) => getChildren(reader, c)); } if (children2 instanceof ObserverNode) { if (reader) { children2.readEffect(reader); } return [children2._element]; } if (children2) { return [children2]; } return []; }; const d = derived(this, (reader) => { this._element.replaceChildren(...getChildren(reader, children)); }); this._deriveds.push(d); if (!childrenIsObservable(children)) { d.get(); } } } readEffect(reader) { for (const d of this._deriveds) { d.read(reader); } } keepUpdated(store) { derived((reader) => { this.readEffect(reader); }).recomputeInitiallyAndOnChange(store); return this; } /** * Creates a live element that will keep the element updated as long as the returned object is not disposed. */ toDisposableLiveElement() { const store = new DisposableStore(); this.keepUpdated(store); return new LiveElement(this._element, store); } } function setClassName(domNode, className2) { if (isSVGElement(domNode)) { domNode.setAttribute("class", className2); } else { domNode.className = className2; } } function resolve(value, reader, cb) { if (isObservable(value)) { cb(value.read(reader)); return; } if (Array.isArray(value)) { for (const v of value) { resolve(v, reader, cb); } return; } cb(value); } function getClassName(className2, reader) { let result = ""; resolve(className2, reader, (val) => { if (val) { if (result.length === 0) { result = val; } else { result += " " + val; } } }); return result; } function hasObservable(value) { if (isObservable(value)) { return true; } if (Array.isArray(value)) { return value.some((v) => hasObservable(v)); } return false; } function convertCssValue(value) { if (typeof value === "number") { return value + "px"; } return value; } function childrenIsObservable(children) { if (isObservable(children)) { return true; } if (Array.isArray(children)) { return children.some((c) => childrenIsObservable(c)); } return false; } class LiveElement { constructor(element, _disposable) { this.element = element; this._disposable = _disposable; } dispose() { this._disposable.dispose(); } } class ObserverNodeWithElement extends ObserverNode { constructor() { super(...arguments); this._isHovered = void 0; this._didMouseMoveDuringHover = void 0; } get element() { return this._element; } get isHovered() { if (!this._isHovered) { const hovered = observableValue("hovered", false); this._element.addEventListener("mouseenter", (_e2) => hovered.set(true, void 0)); this._element.addEventListener("mouseleave", (_e2) => hovered.set(false, void 0)); this._isHovered = hovered; } return this._isHovered; } get didMouseMoveDuringHover() { if (!this._didMouseMoveDuringHover) { let _hovering = false; const hovered = observableValue("didMouseMoveDuringHover", false); this._element.addEventListener("mouseenter", (_e2) => { _hovering = true; }); this._element.addEventListener("mousemove", (_e2) => { if (_hovering) { hovered.set(true, void 0); } }); this._element.addEventListener("mouseleave", (_e2) => { _hovering = false; hovered.set(false, void 0); }); this._didMouseMoveDuringHover = hovered; } return this._didMouseMoveDuringHover; } } function setOrRemoveAttribute(element, key, value) { if (value === null || value === void 0) { element.removeAttribute(camelCaseToHyphenCase(key)); } else { element.setAttribute(camelCaseToHyphenCase(key), String(value)); } } function isObservable(obj) { return !!obj && obj.read !== void 0 && obj.reportChanges !== void 0; } const MAX_MESSAGE_LENGTH = 2e4; let ariaContainer; let alertContainer; let alertContainer2; let statusContainer; let statusContainer2; function setARIAContainer(parent) { ariaContainer = document.createElement("div"); ariaContainer.className = "monaco-aria-container"; const createAlertContainer = () => { const element = document.createElement("div"); element.className = "monaco-alert"; element.setAttribute("role", "alert"); element.setAttribute("aria-atomic", "true"); ariaContainer.appendChild(element); return element; }; alertContainer = createAlertContainer(); alertContainer2 = createAlertContainer(); const createStatusContainer = () => { const element = document.createElement("div"); element.className = "monaco-status"; element.setAttribute("aria-live", "polite"); element.setAttribute("aria-atomic", "true"); ariaContainer.appendChild(element); return element; }; statusContainer = createStatusContainer(); statusContainer2 = createStatusContainer(); parent.appendChild(ariaContainer); } function alert(msg) { if (!ariaContainer) { return; } if (alertContainer.textContent !== msg) { clearNode(alertContainer2); insertMessage(alertContainer, msg); } else { clearNode(alertContainer); insertMessage(alertContainer2, msg); } } function status(msg) { if (!ariaContainer) { return; } if (statusContainer.textContent !== msg) { clearNode(statusContainer2); insertMessage(statusContainer, msg); } else { clearNode(statusContainer); insertMessage(statusContainer2, msg); } } function insertMessage(target, msg) { clearNode(target); if (msg.length > MAX_MESSAGE_LENGTH) { msg = msg.substr(0, MAX_MESSAGE_LENGTH); } target.textContent = msg; target.style.visibility = "hidden"; target.style.visibility = "visible"; } var _util; (function(_util2) { _util2.serviceIds = /* @__PURE__ */ new Map(); _util2.DI_TARGET = "$di$target"; _util2.DI_DEPENDENCIES = "$di$dependencies"; function getServiceDependencies(ctor) { return ctor[_util2.DI_DEPENDENCIES] || []; } _util2.getServiceDependencies = getServiceDependencies; })(_util || (_util = {})); const IInstantiationService = createDecorator("instantiationService"); function storeServiceDependency(id, target, index) { if (target[_util.DI_TARGET] === target) { target[_util.DI_DEPENDENCIES].push({ id, index }); } else { target[_util.DI_DEPENDENCIES] = [{ id, index }]; target[_util.DI_TARGET] = target; } } function createDecorator(serviceId) { if (_util.serviceIds.has(serviceId)) { return _util.serviceIds.get(serviceId); } const id = function(target, key, index) { if (arguments.length !== 3) { throw new Error("@IServiceName-decorator can only be used to decorate a parameter"); } storeServiceDependency(id, target, index); }; id.toString = () => serviceId; _util.serviceIds.set(serviceId, id); return id; } const ICodeEditorService = createDecorator("codeEditorService"); let Position$1 = class Position2 { constructor(lineNumber, column) { this.lineNumber = lineNumber; this.column = column; } /** * Create a new position from this position. * * @param newLineNumber new line number * @param newColumn new column */ with(newLineNumber = this.lineNumber, newColumn = this.column) { if (newLineNumber === this.lineNumber && newColumn === this.column) { return this; } else { return new Position2(newLineNumber, newColumn); } } /** * Derive a new position from this position. * * @param deltaLineNumber line number delta * @param deltaColumn column delta */ delta(deltaLineNumber = 0, deltaColumn = 0) { return this.with(Math.max(1, this.lineNumber + deltaLineNumber), Math.max(1, this.column + deltaColumn)); } /** * Test if this position equals other position */ equals(other) { return Position2.equals(this, other); } /** * Test if position `a` equals position `b` */ static equals(a, b) { if (!a && !b) { return true; } return !!a && !!b && a.lineNumber === b.lineNumber && a.column === b.column; } /** * Test if this position is before other position. * If the two positions are equal, the result will be false. */ isBefore(other) { return Position2.isBefore(this, other); } /** * Test if position `a` is before position `b`. * If the two positions are equal, the result will be false. */ static isBefore(a, b) { if (a.lineNumber < b.lineNumber) { return true; } if (b.lineNumber < a.lineNumber) { return false; } return a.column < b.column; } /** * Test if this position is before other position. * If the two positions are equal, the result will be true. */ isBeforeOrEqual(other) { return Position2.isBeforeOrEqual(this, other); } /** * Test if position `a` is before position `b`. * If the two positions are equal, the result will be true. */ static isBeforeOrEqual(a, b) { if (a.lineNumber < b.lineNumber) { return true; } if (b.lineNumber < a.lineNumber) { return false; } return a.column <= b.column; } /** * A function that compares positions, useful for sorting */ static compare(a, b) { const aLineNumber = a.lineNumber | 0; const bLineNumber = b.lineNumber | 0; if (aLineNumber === bLineNumber) { const aColumn = a.column | 0; const bColumn = b.column | 0; return aColumn - bColumn; } return aLineNumber - bLineNumber; } /** * Clone this position. */ clone() { return new Position2(this.lineNumber, this.column); } /** * Convert to a human-readable representation. */ toString() { return "(" + this.lineNumber + "," + this.column + ")"; } // --- /** * Create a `Position` from an `IPosition`. */ static lift(pos) { return new Position2(pos.lineNumber, pos.column); } /** * Test if `obj` is an `IPosition`. */ static isIPosition(obj) { return obj && typeof obj.lineNumber === "number" && typeof obj.column === "number"; } toJSON() { return { lineNumber: this.lineNumber, column: this.column }; } }; const IModelService = createDecorator("modelService"); const ITextModelService = createDecorator("textModelService"); class Action extends Disposable { get onDidChange() { return this._onDidChange.event; } constructor(id, label = "", cssClass = "", enabled = true, actionCallback) { super(); this._onDidChange = this._register(new Emitter$1()); this._enabled = true; this._id = id; this._label = label; this._cssClass = cssClass; this._enabled = enabled; this._actionCallback = actionCallback; } get id() { return this._id; } get label() { return this._label; } set label(value) { this._setLabel(value); } _setLabel(value) { if (this._label !== value) { this._label = value; this._onDidChange.fire({ label: value }); } } get tooltip() { return this._tooltip || ""; } set tooltip(value) { this._setTooltip(value); } _setTooltip(value) { if (this._tooltip !== value) { this._tooltip = value; this._onDidChange.fire({ tooltip: value }); } } get class() { return this._cssClass; } set class(value) { this._setClass(value); } _setClass(value) { if (this._cssClass !== value) { this._cssClass = value; this._onDidChange.fire({ class: value }); } } get enabled() { return this._enabled; } set enabled(value) { this._setEnabled(value); } _setEnabled(value) { if (this._enabled !== value) { this._enabled = value; this._onDidChange.fire({ enabled: value }); } } get checked() { return this._checked; } set checked(value) { this._setChecked(value); } _setChecked(value) { if (this._checked !== value) { this._checked = value; this._onDidChange.fire({ checked: value }); } } async run(event, data) { if (this._actionCallback) { await this._actionCallback(event); } } } class ActionRunner extends Disposable { constructor() { super(...arguments); this._onWillRun = this._register(new Emitter$1()); this._onDidRun = this._register(new Emitter$1()); } get onWillRun() { return this._onWillRun.event; } get onDidRun() { return this._onDidRun.event; } async run(action, context) { if (!action.enabled) { return; } this._onWillRun.fire({ action }); let error = void 0; try { await this.runAction(action, context); } catch (e) { error = e; } this._onDidRun.fire({ action, error }); } async runAction(action, context) { await action.run(context); } } const _Separator = class _Separator { constructor() { this.id = _Separator.ID; this.label = ""; this.tooltip = ""; this.class = "separator"; this.enabled = false; this.checked = false; } /** * Joins all non-empty lists of actions with separators. */ static join(...actionLists) { let out = []; for (const list2 of actionLists) { if (!list2.length) ; else if (out.length) { out = [...out, new _Separator(), ...list2]; } else { out = list2; } } return out; } async run() { } }; _Separator.ID = "vs.actions.separator"; let Separator = _Separator; class SubmenuAction { get actions() { return this._actions; } constructor(id, label, actions, cssClass) { this.tooltip = ""; this.enabled = true; this.checked = void 0; this.id = id; this.label = label; this.class = cssClass; this._actions = actions; } async run() { } } const _EmptySubmenuAction = class _EmptySubmenuAction extends Action { constructor() { super(_EmptySubmenuAction.ID, localize(28, "(empty)"), void 0, false); } }; _EmptySubmenuAction.ID = "vs.actions.empty"; let EmptySubmenuAction = _EmptySubmenuAction; function toAction(props) { return { id: props.id, label: props.label, tooltip: props.tooltip ?? props.label, class: props.class, enabled: props.enabled ?? true, checked: props.checked, run: async (...args) => props.run(...args) }; } const _codiconFontCharacters = /* @__PURE__ */ Object.create(null); function register$2(id, fontCharacter) { if (isString$1(fontCharacter)) { const val = _codiconFontCharacters[fontCharacter]; if (val === void 0) { throw new Error(`${id} references an unknown codicon: ${fontCharacter}`); } fontCharacter = val; } _codiconFontCharacters[id] = fontCharacter; return { id }; } function getCodiconFontCharacters() { return _codiconFontCharacters; } const codiconsLibrary = { add: register$2("add", 6e4), plus: register$2("plus", 6e4), gistNew: register$2("gist-new", 6e4), repoCreate: register$2("repo-create", 6e4), lightbulb: register$2("lightbulb", 60001), lightBulb: register$2("light-bulb", 60001), repo: register$2("repo", 60002), repoDelete: register$2("repo-delete", 60002), gistFork: register$2("gist-fork", 60003), repoForked: register$2("repo-forked", 60003), gitPullRequest: register$2("git-pull-request", 60004), gitPullRequestAbandoned: register$2("git-pull-request-abandoned", 60004), recordKeys: register$2("record-keys", 60005), keyboard: register$2("keyboard", 60005), tag: register$2("tag", 60006), gitPullRequestLabel: register$2("git-pull-request-label", 60006), tagAdd: register$2("tag-add", 60006), tagRemove: register$2("tag-remove", 60006), person: register$2("person", 60007), personFollow: register$2("person-follow", 60007), personOutline: register$2("person-outline", 60007), personFilled: register$2("person-filled", 60007), gitBranch: register$2("git-branch", 60008), gitBranchCreate: register$2("git-branch-create", 60008), gitBranchDelete: register$2("git-branch-delete", 60008), sourceControl: register$2("source-control", 60008), mirror: register$2("mirror", 60009), mirrorPublic: register$2("mirror-public", 60009), star: register$2("star", 60010), starAdd: register$2("star-add", 60010), starDelete: register$2("star-delete", 60010), starEmpty: register$2("star-empty", 60010), comment: register$2("comment", 60011), commentAdd: register$2("comment-add", 60011), alert: register$2("alert", 60012), warning: register$2("warning", 60012), search: register$2("search", 60013), searchSave: register$2("search-save", 60013), logOut: register$2("log-out", 60014), signOut: register$2("sign-out", 60014), logIn: register$2("log-in", 60015), signIn: register$2("sign-in", 60015), eye: register$2("eye", 60016), eyeUnwatch: register$2("eye-unwatch", 60016), eyeWatch: register$2("eye-watch", 60016), circleFilled: register$2("circle-filled", 60017), primitiveDot: register$2("primitive-dot", 60017), closeDirty: register$2("close-dirty", 60017), debugBreakpoint: register$2("debug-breakpoint", 60017), debugBreakpointDisabled: register$2("debug-breakpoint-disabled", 60017), debugHint: register$2("debug-hint", 60017), terminalDecorationSuccess: register$2("terminal-decoration-success", 60017), primitiveSquare: register$2("primitive-square", 60018), edit: register$2("edit", 60019), pencil: register$2("pencil", 60019), info: register$2("info", 60020), issueOpened: register$2("issue-opened", 60020), gistPrivate: register$2("gist-private", 60021), gitForkPrivate: register$2("git-fork-private", 60021), lock: register$2("lock", 60021), mirrorPrivate: register$2("mirror-private", 60021), close: register$2("close", 60022), removeClose: register$2("remove-close", 60022), x: register$2("x", 60022), repoSync: register$2("repo-sync", 60023), sync: register$2("sync", 60023), clone: register$2("clone", 60024), desktopDownload: register$2("desktop-download", 60024), beaker: register$2("beaker", 60025), microscope: register$2("microscope", 60025), vm: register$2("vm", 60026), deviceDesktop: register$2("device-desktop", 60026), file: register$2("file", 60027), fileText: register$2("file-text", 60027), more: register$2("more", 60028), ellipsis: register$2("ellipsis", 60028), kebabHorizontal: register$2("kebab-horizontal", 60028), mailReply: register$2("mail-reply", 60029), reply: register$2("reply", 60029), organization: register$2("organization", 60030), organizationFilled: register$2("organization-filled", 60030), organizationOutline: register$2("organization-outline", 60030), newFile: register$2("new-file", 60031), fileAdd: register$2("file-add", 60031), newFolder: register$2("new-folder", 60032), fileDirectoryCreate: register$2("file-directory-create", 60032), trash: register$2("trash", 60033), trashcan: register$2("trashcan", 60033), history: register$2("history", 60034), clock: register$2("clock", 60034), folder: register$2("folder", 60035), fileDirectory: register$2("file-directory", 60035), symbolFolder: register$2("symbol-folder", 60035), logoGithub: register$2("logo-github", 60036), markGithub: register$2("mark-github", 60036), github: register$2("github", 60036), terminal: register$2("terminal", 60037), console: register$2("console", 60037), repl: register$2("repl", 60037), zap: register$2("zap", 60038), symbolEvent: register$2("symbol-event", 60038), error: register$2("error", 60039), stop: register$2("stop", 60039), variable: register$2("variable", 60040), symbolVariable: register$2("symbol-variable", 60040), array: register$2("array", 60042), symbolArray: register$2("symbol-array", 60042), symbolModule: register$2("symbol-module", 60043), symbolPackage: register$2("symbol-package", 60043), symbolNamespace: register$2("symbol-namespace", 60043), symbolObject: register$2("symbol-object", 60043), symbolMethod: register$2("symbol-method", 60044), symbolFunction: register$2("symbol-function", 60044), symbolConstructor: register$2("symbol-constructor", 60044), symbolBoolean: register$2("symbol-boolean", 60047), symbolNull: register$2("symbol-null", 60047), symbolNumeric: register$2("symbol-numeric", 60048), symbolNumber: register$2("symbol-number", 60048), symbolStructure: register$2("symbol-structure", 60049), symbolStruct: register$2("symbol-struct", 60049), symbolParameter: register$2("symbol-parameter", 60050), symbolTypeParameter: register$2("symbol-type-parameter", 60050), symbolKey: register$2("symbol-key", 60051), symbolText: register$2("symbol-text", 60051), symbolReference: register$2("symbol-reference", 60052), goToFile: register$2("go-to-file", 60052), symbolEnum: register$2("symbol-enum", 60053), symbolValue: register$2("symbol-value", 60053), symbolRuler: register$2("symbol-ruler", 60054), symbolUnit: register$2("symbol-unit", 60054), activateBreakpoints: register$2("activate-breakpoints", 60055), archive: register$2("archive", 60056), arrowBoth: register$2("arrow-both", 60057), arrowDown: register$2("arrow-down", 60058), arrowLeft: register$2("arrow-left", 60059), arrowRight: register$2("arrow-right", 60060), arrowSmallDown: register$2("arrow-small-down", 60061), arrowSmallLeft: register$2("arrow-small-left", 60062), arrowSmallRight: register$2("arrow-small-right", 60063), arrowSmallUp: register$2("arrow-small-up", 60064), arrowUp: register$2("arrow-up", 60065), bell: register$2("bell", 60066), bold: register$2("bold", 60067), book: register$2("book", 60068), bookmark: register$2("bookmark", 60069), debugBreakpointConditionalUnverified: register$2("debug-breakpoint-conditional-unverified", 60070), debugBreakpointConditional: register$2("debug-breakpoint-conditional", 60071), debugBreakpointConditionalDisabled: register$2("debug-breakpoint-conditional-disabled", 60071), debugBreakpointDataUnverified: register$2("debug-breakpoint-data-unverified", 60072), debugBreakpointData: register$2("debug-breakpoint-data", 60073), debugBreakpointDataDisabled: register$2("debug-breakpoint-data-disabled", 60073), debugBreakpointLogUnverified: register$2("debug-breakpoint-log-unverified", 60074), debugBreakpointLog: register$2("debug-breakpoint-log", 60075), debugBreakpointLogDisabled: register$2("debug-breakpoint-log-disabled", 60075), briefcase: register$2("briefcase", 60076), broadcast: register$2("broadcast", 60077), browser: register$2("browser", 60078), bug: register$2("bug", 60079), calendar: register$2("calendar", 60080), caseSensitive: register$2("case-sensitive", 60081), check: register$2("check", 60082), checklist: register$2("checklist", 60083), chevronDown: register$2("chevron-down", 60084), chevronLeft: register$2("chevron-left", 60085), chevronRight: register$2("chevron-right", 60086), chevronUp: register$2("chevron-up", 60087), chromeClose: register$2("chrome-close", 60088), chromeMaximize: register$2("chrome-maximize", 60089), chromeMinimize: register$2("chrome-minimize", 60090), chromeRestore: register$2("chrome-restore", 60091), circleOutline: register$2("circle-outline", 60092), circle: register$2("circle", 60092), debugBreakpointUnverified: register$2("debug-breakpoint-unverified", 60092), terminalDecorationIncomplete: register$2("terminal-decoration-incomplete", 60092), circleSlash: register$2("circle-slash", 60093), circuitBoard: register$2("circuit-board", 60094), clearAll: register$2("clear-all", 60095), clippy: register$2("clippy", 60096), closeAll: register$2("close-all", 60097), cloudDownload: register$2("cloud-download", 60098), cloudUpload: register$2("cloud-upload", 60099), code: register$2("code", 60100), collapseAll: register$2("collapse-all", 60101), colorMode: register$2("color-mode", 60102), commentDiscussion: register$2("comment-discussion", 60103), creditCard: register$2("credit-card", 60105), dash: register$2("dash", 60108), dashboard: register$2("dashboard", 60109), database: register$2("database", 60110), debugContinue: register$2("debug-continue", 60111), debugDisconnect: register$2("debug-disconnect", 60112), debugPause: register$2("debug-pause", 60113), debugRestart: register$2("debug-restart", 60114), debugStart: register$2("debug-start", 60115), debugStepInto: register$2("debug-step-into", 60116), debugStepOut: register$2("debug-step-out", 60117), debugStepOver: register$2("debug-step-over", 60118), debugStop: register$2("debug-stop", 60119), debug: register$2("debug", 60120), deviceCameraVideo: register$2("device-camera-video", 60121), deviceCamera: register$2("device-camera", 60122), deviceMobile: register$2("device-mobile", 60123), diffAdded: register$2("diff-added", 60124), diffIgnored: register$2("diff-ignored", 60125), diffModified: register$2("diff-modified", 60126), diffRemoved: register$2("diff-removed", 60127), diffRenamed: register$2("diff-renamed", 60128), diff: register$2("diff", 60129), diffSidebyside: register$2("diff-sidebyside", 60129), discard: register$2("discard", 60130), editorLayout: register$2("editor-layout", 60131), emptyWindow: register$2("empty-window", 60132), exclude: register$2("exclude", 60133), extensions: register$2("extensions", 60134), eyeClosed: register$2("eye-closed", 60135), fileBinary: register$2("file-binary", 60136), fileCode: register$2("file-code", 60137), fileMedia: register$2("file-media", 60138), filePdf: register$2("file-pdf", 60139), fileSubmodule: register$2("file-submodule", 60140), fileSymlinkDirectory: register$2("file-symlink-directory", 60141), fileSymlinkFile: register$2("file-symlink-file", 60142), fileZip: register$2("file-zip", 60143), files: register$2("files", 60144), filter: register$2("filter", 60145), flame: register$2("flame", 60146), foldDown: register$2("fold-down", 60147), foldUp: register$2("fold-up", 60148), fold: register$2("fold", 60149), folderActive: register$2("folder-active", 60150), folderOpened: register$2("folder-opened", 60151), gear: register$2("gear", 60152), gift: register$2("gift", 60153), gistSecret: register$2("gist-secret", 60154), gist: register$2("gist", 60155), gitCommit: register$2("git-commit", 60156), gitCompare: register$2("git-compare", 60157), compareChanges: register$2("compare-changes", 60157), gitMerge: register$2("git-merge", 60158), githubAction: register$2("github-action", 60159), githubAlt: register$2("github-alt", 60160), globe: register$2("globe", 60161), grabber: register$2("grabber", 60162), graph: register$2("graph", 60163), gripper: register$2("gripper", 60164), heart: register$2("heart", 60165), home: register$2("home", 60166), horizontalRule: register$2("horizontal-rule", 60167), hubot: register$2("hubot", 60168), inbox: register$2("inbox", 60169), issueReopened: register$2("issue-reopened", 60171), issues: register$2("issues", 60172), italic: register$2("italic", 60173), jersey: register$2("jersey", 60174), json: register$2("json", 60175), kebabVertical: register$2("kebab-vertical", 60176), key: register$2("key", 60177), law: register$2("law", 60178), lightbulbAutofix: register$2("lightbulb-autofix", 60179), linkExternal: register$2("link-external", 60180), link: register$2("link", 60181), listOrdered: register$2("list-ordered", 60182), listUnordered: register$2("list-unordered", 60183), liveShare: register$2("live-share", 60184), loading: register$2("loading", 60185), location: register$2("location", 60186), mailRead: register$2("mail-read", 60187), mail: register$2("mail", 60188), markdown: register$2("markdown", 60189), megaphone: register$2("megaphone", 60190), mention: register$2("mention", 60191), milestone: register$2("milestone", 60192), gitPullRequestMilestone: register$2("git-pull-request-milestone", 60192), mortarBoard: register$2("mortar-board", 60193), move: register$2("move", 60194), multipleWindows: register$2("multiple-windows", 60195), mute: register$2("mute", 60196), noNewline: register$2("no-newline", 60197), note: register$2("note", 60198), octoface: register$2("octoface", 60199), openPreview: register$2("open-preview", 60200), package: register$2("package", 60201), paintcan: register$2("paintcan", 60202), pin: register$2("pin", 60203), play: register$2("play", 60204), run: register$2("run", 60204), plug: register$2("plug", 60205), preserveCase: register$2("preserve-case", 60206), preview: register$2("preview", 60207), project: register$2("project", 60208), pulse: register$2("pulse", 60209), question: register$2("question", 60210), quote: register$2("quote", 60211), radioTower: register$2("radio-tower", 60212), reactions: register$2("reactions", 60213), references: register$2("references", 60214), refresh: register$2("refresh", 60215), regex: register$2("regex", 60216), remoteExplorer: register$2("remote-explorer", 60217), remote: register$2("remote", 60218), remove: register$2("remove", 60219), replaceAll: register$2("replace-all", 60220), replace: register$2("replace", 60221), repoClone: register$2("repo-clone", 60222), repoForcePush: register$2("repo-force-push", 60223), repoPull: register$2("repo-pull", 60224), repoPush: register$2("repo-push", 60225), report: register$2("report", 60226), requestChanges: register$2("request-changes", 60227), rocket: register$2("rocket", 60228), rootFolderOpened: register$2("root-folder-opened", 60229), rootFolder: register$2("root-folder", 60230), rss: register$2("rss", 60231), ruby: register$2("ruby", 60232), saveAll: register$2("save-all", 60233), saveAs: register$2("save-as", 60234), save: register$2("save", 60235), screenFull: register$2("screen-full", 60236), screenNormal: register$2("screen-normal", 60237), searchStop: register$2("search-stop", 60238), server: register$2("server", 60240), settingsGear: register$2("settings-gear", 60241), settings: register$2("settings", 60242), shield: register$2("shield", 60243), smiley: register$2("smiley", 60244), sortPrecedence: register$2("sort-precedence", 60245), splitHorizontal: register$2("split-horizontal", 60246), splitVertical: register$2("split-vertical", 60247), squirrel: register$2("squirrel", 60248), starFull: register$2("star-full", 60249), starHalf: register$2("star-half", 60250), symbolClass: register$2("symbol-class", 60251), symbolColor: register$2("symbol-color", 60252), symbolConstant: register$2("symbol-constant", 60253), symbolEnumMember: register$2("symbol-enum-member", 60254), symbolField: register$2("symbol-field", 60255), symbolFile: register$2("symbol-file", 60256), symbolInterface: register$2("symbol-interface", 60257), symbolKeyword: register$2("symbol-keyword", 60258), symbolMisc: register$2("symbol-misc", 60259), symbolOperator: register$2("symbol-operator", 60260), symbolProperty: register$2("symbol-property", 60261), wrench: register$2("wrench", 60261), wrenchSubaction: register$2("wrench-subaction", 60261), symbolSnippet: register$2("symbol-snippet", 60262), tasklist: register$2("tasklist", 60263), telescope: register$2("telescope", 60264), textSize: register$2("text-size", 60265), threeBars: register$2("three-bars", 60266), thumbsdown: register$2("thumbsdown", 60267), thumbsup: register$2("thumbsup", 60268), tools: register$2("tools", 60269), triangleDown: register$2("triangle-down", 60270), triangleLeft: register$2("triangle-left", 60271), triangleRight: register$2("triangle-right", 60272), triangleUp: register$2("triangle-up", 60273), twitter: register$2("twitter", 60274), unfold: register$2("unfold", 60275), unlock: register$2("unlock", 60276), unmute: register$2("unmute", 60277), unverified: register$2("unverified", 60278), verified: register$2("verified", 60279), versions: register$2("versions", 60280), vmActive: register$2("vm-active", 60281), vmOutline: register$2("vm-outline", 60282), vmRunning: register$2("vm-running", 60283), watch: register$2("watch", 60284), whitespace: register$2("whitespace", 60285), wholeWord: register$2("whole-word", 60286), window: register$2("window", 60287), wordWrap: register$2("word-wrap", 60288), zoomIn: register$2("zoom-in", 60289), zoomOut: register$2("zoom-out", 60290), listFilter: register$2("list-filter", 60291), listFlat: register$2("list-flat", 60292), listSelection: register$2("list-selection", 60293), selection: register$2("selection", 60293), listTree: register$2("list-tree", 60294), debugBreakpointFunctionUnverified: register$2("debug-breakpoint-function-unverified", 60295), debugBreakpointFunction: register$2("debug-breakpoint-function", 60296), debugBreakpointFunctionDisabled: register$2("debug-breakpoint-function-disabled", 60296), debugStackframeActive: register$2("debug-stackframe-active", 60297), circleSmallFilled: register$2("circle-small-filled", 60298), debugStackframeDot: register$2("debug-stackframe-dot", 60298), terminalDecorationMark: register$2("terminal-decoration-mark", 60298), debugStackframe: register$2("debug-stackframe", 60299), debugStackframeFocused: register$2("debug-stackframe-focused", 60299), debugBreakpointUnsupported: register$2("debug-breakpoint-unsupported", 60300), symbolString: register$2("symbol-string", 60301), debugReverseContinue: register$2("debug-reverse-continue", 60302), debugStepBack: register$2("debug-step-back", 60303), debugRestartFrame: register$2("debug-restart-frame", 60304), debugAlt: register$2("debug-alt", 60305), callIncoming: register$2("call-incoming", 60306), callOutgoing: register$2("call-outgoing", 60307), menu: register$2("menu", 60308), expandAll: register$2("expand-all", 60309), feedback: register$2("feedback", 60310), gitPullRequestReviewer: register$2("git-pull-request-reviewer", 60310), groupByRefType: register$2("group-by-ref-type", 60311), ungroupByRefType: register$2("ungroup-by-ref-type", 60312), account: register$2("account", 60313), gitPullRequestAssignee: register$2("git-pull-request-assignee", 60313), bellDot: register$2("bell-dot", 60314), debugConsole: register$2("debug-console", 60315), library: register$2("library", 60316), output: register$2("output", 60317), runAll: register$2("run-all", 60318), syncIgnored: register$2("sync-ignored", 60319), pinned: register$2("pinned", 60320), githubInverted: register$2("github-inverted", 60321), serverProcess: register$2("server-process", 60322), serverEnvironment: register$2("server-environment", 60323), pass: register$2("pass", 60324), issueClosed: register$2("issue-closed", 60324), stopCircle: register$2("stop-circle", 60325), playCircle: register$2("play-circle", 60326), record: register$2("record", 60327), debugAltSmall: register$2("debug-alt-small", 60328), vmConnect: register$2("vm-connect", 60329), cloud: register$2("cloud", 60330), merge: register$2("merge", 60331), export: register$2("export", 60332), graphLeft: register$2("graph-left", 60333), magnet: register$2("magnet", 60334), notebook: register$2("notebook", 60335), redo: register$2("redo", 60336), checkAll: register$2("check-all", 60337), pinnedDirty: register$2("pinned-dirty", 60338), passFilled: register$2("pass-filled", 60339), circleLargeFilled: register$2("circle-large-filled", 60340), circleLarge: register$2("circle-large", 60341), circleLargeOutline: register$2("circle-large-outline", 60341), combine: register$2("combine", 60342), gather: register$2("gather", 60342), table: register$2("table", 60343), variableGroup: register$2("variable-group", 60344), typeHierarchy: register$2("type-hierarchy", 60345), typeHierarchySub: register$2("type-hierarchy-sub", 60346), typeHierarchySuper: register$2("type-hierarchy-super", 60347), gitPullRequestCreate: register$2("git-pull-request-create", 60348), runAbove: register$2("run-above", 60349), runBelow: register$2("run-below", 60350), notebookTemplate: register$2("notebook-template", 60351), debugRerun: register$2("debug-rerun", 60352), workspaceTrusted: register$2("workspace-trusted", 60353), workspaceUntrusted: register$2("workspace-untrusted", 60354), workspaceUnknown: register$2("workspace-unknown", 60355), terminalCmd: register$2("terminal-cmd", 60356), terminalDebian: register$2("terminal-debian", 60357), terminalLinux: register$2("terminal-linux", 60358), terminalPowershell: register$2("terminal-powershell", 60359), terminalTmux: register$2("terminal-tmux", 60360), terminalUbuntu: register$2("terminal-ubuntu", 60361), terminalBash: register$2("terminal-bash", 60362), arrowSwap: register$2("arrow-swap", 60363), copy: register$2("copy", 60364), personAdd: register$2("person-add", 60365), filterFilled: register$2("filter-filled", 60366), wand: register$2("wand", 60367), debugLineByLine: register$2("debug-line-by-line", 60368), inspect: register$2("inspect", 60369), layers: register$2("layers", 60370), layersDot: register$2("layers-dot", 60371), layersActive: register$2("layers-active", 60372), compass: register$2("compass", 60373), compassDot: register$2("compass-dot", 60374), compassActive: register$2("compass-active", 60375), azure: register$2("azure", 60376), issueDraft: register$2("issue-draft", 60377), gitPullRequestClosed: register$2("git-pull-request-closed", 60378), gitPullRequestDraft: register$2("git-pull-request-draft", 60379), debugAll: register$2("debug-all", 60380), debugCoverage: register$2("debug-coverage", 60381), runErrors: register$2("run-errors", 60382), folderLibrary: register$2("folder-library", 60383), debugContinueSmall: register$2("debug-continue-small", 60384), beakerStop: register$2("beaker-stop", 60385), graphLine: register$2("graph-line", 60386), graphScatter: register$2("graph-scatter", 60387), pieChart: register$2("pie-chart", 60388), bracket: register$2("bracket", 60175), bracketDot: register$2("bracket-dot", 60389), bracketError: register$2("bracket-error", 60390), lockSmall: register$2("lock-small", 60391), azureDevops: register$2("azure-devops", 60392), verifiedFilled: register$2("verified-filled", 60393), newline: register$2("newline", 60394), layout: register$2("layout", 60395), layoutActivitybarLeft: register$2("layout-activitybar-left", 60396), layoutActivitybarRight: register$2("layout-activitybar-right", 60397), layoutPanelLeft: register$2("layout-panel-left", 60398), layoutPanelCenter: register$2("layout-panel-center", 60399), layoutPanelJustify: register$2("layout-panel-justify", 60400), layoutPanelRight: register$2("layout-panel-right", 60401), layoutPanel: register$2("layout-panel", 60402), layoutSidebarLeft: register$2("layout-sidebar-left", 60403), layoutSidebarRight: register$2("layout-sidebar-right", 60404), layoutStatusbar: register$2("layout-statusbar", 60405), layoutMenubar: register$2("layout-menubar", 60406), layoutCentered: register$2("layout-centered", 60407), target: register$2("target", 60408), indent: register$2("indent", 60409), recordSmall: register$2("record-small", 60410), errorSmall: register$2("error-small", 60411), terminalDecorationError: register$2("terminal-decoration-error", 60411), arrowCircleDown: register$2("arrow-circle-down", 60412), arrowCircleLeft: register$2("arrow-circle-left", 60413), arrowCircleRight: register$2("arrow-circle-right", 60414), arrowCircleUp: register$2("arrow-circle-up", 60415), layoutSidebarRightOff: register$2("layout-sidebar-right-off", 60416), layoutPanelOff: register$2("layout-panel-off", 60417), layoutSidebarLeftOff: register$2("layout-sidebar-left-off", 60418), blank: register$2("blank", 60419), heartFilled: register$2("heart-filled", 60420), map: register$2("map", 60421), mapHorizontal: register$2("map-horizontal", 60421), foldHorizontal: register$2("fold-horizontal", 60421), mapFilled: register$2("map-filled", 60422), mapHorizontalFilled: register$2("map-horizontal-filled", 60422), foldHorizontalFilled: register$2("fold-horizontal-filled", 60422), circleSmall: register$2("circle-small", 60423), bellSlash: register$2("bell-slash", 60424), bellSlashDot: register$2("bell-slash-dot", 60425), commentUnresolved: register$2("comment-unresolved", 60426), gitPullRequestGoToChanges: register$2("git-pull-request-go-to-changes", 60427), gitPullRequestNewChanges: register$2("git-pull-request-new-changes", 60428), searchFuzzy: register$2("search-fuzzy", 60429), commentDraft: register$2("comment-draft", 60430), send: register$2("send", 60431), sparkle: register$2("sparkle", 60432), insert: register$2("insert", 60433), mic: register$2("mic", 60434), thumbsdownFilled: register$2("thumbsdown-filled", 60435), thumbsupFilled: register$2("thumbsup-filled", 60436), coffee: register$2("coffee", 60437), snake: register$2("snake", 60438), game: register$2("game", 60439), vr: register$2("vr", 60440), chip: register$2("chip", 60441), piano: register$2("piano", 60442), music: register$2("music", 60443), micFilled: register$2("mic-filled", 60444), repoFetch: register$2("repo-fetch", 60445), copilot: register$2("copilot", 60446), lightbulbSparkle: register$2("lightbulb-sparkle", 60447), robot: register$2("robot", 60448), sparkleFilled: register$2("sparkle-filled", 60449), diffSingle: register$2("diff-single", 60450), diffMultiple: register$2("diff-multiple", 60451), surroundWith: register$2("surround-with", 60452), share: register$2("share", 60453), gitStash: register$2("git-stash", 60454), gitStashApply: register$2("git-stash-apply", 60455), gitStashPop: register$2("git-stash-pop", 60456), vscode: register$2("vscode", 60457), vscodeInsiders: register$2("vscode-insiders", 60458), codeOss: register$2("code-oss", 60459), runCoverage: register$2("run-coverage", 60460), runAllCoverage: register$2("run-all-coverage", 60461), coverage: register$2("coverage", 60462), githubProject: register$2("github-project", 60463), mapVertical: register$2("map-vertical", 60464), foldVertical: register$2("fold-vertical", 60464), mapVerticalFilled: register$2("map-vertical-filled", 60465), foldVerticalFilled: register$2("fold-vertical-filled", 60465), goToSearch: register$2("go-to-search", 60466), percentage: register$2("percentage", 60467), sortPercentage: register$2("sort-percentage", 60467), attach: register$2("attach", 60468), goToEditingSession: register$2("go-to-editing-session", 60469), editSession: register$2("edit-session", 60470), codeReview: register$2("code-review", 60471), copilotWarning: register$2("copilot-warning", 60472), python: register$2("python", 60473), copilotLarge: register$2("copilot-large", 60474), copilotWarningLarge: register$2("copilot-warning-large", 60475), keyboardTab: register$2("keyboard-tab", 60476), copilotBlocked: register$2("copilot-blocked", 60477), copilotNotConnected: register$2("copilot-not-connected", 60478), flag: register$2("flag", 60479), lightbulbEmpty: register$2("lightbulb-empty", 60480), symbolMethodArrow: register$2("symbol-method-arrow", 60481), copilotUnavailable: register$2("copilot-unavailable", 60482), repoPinned: register$2("repo-pinned", 60483), keyboardTabAbove: register$2("keyboard-tab-above", 60484), keyboardTabBelow: register$2("keyboard-tab-below", 60485), gitPullRequestDone: register$2("git-pull-request-done", 60486), mcp: register$2("mcp", 60487), extensionsLarge: register$2("extensions-large", 60488), layoutPanelDock: register$2("layout-panel-dock", 60489), layoutSidebarLeftDock: register$2("layout-sidebar-left-dock", 60490), layoutSidebarRightDock: register$2("layout-sidebar-right-dock", 60491), copilotInProgress: register$2("copilot-in-progress", 60492), copilotError: register$2("copilot-error", 60493), copilotSuccess: register$2("copilot-success", 60494), chatSparkle: register$2("chat-sparkle", 60495), searchSparkle: register$2("search-sparkle", 60496), editSparkle: register$2("edit-sparkle", 60497), copilotSnooze: register$2("copilot-snooze", 60498), sendToRemoteAgent: register$2("send-to-remote-agent", 60499), commentDiscussionSparkle: register$2("comment-discussion-sparkle", 60500), chatSparkleWarning: register$2("chat-sparkle-warning", 60501), chatSparkleError: register$2("chat-sparkle-error", 60502), collection: register$2("collection", 60503), newCollection: register$2("new-collection", 60504), thinking: register$2("thinking", 60505) }; const codiconsDerived = { dialogError: register$2("dialog-error", "error"), dialogWarning: register$2("dialog-warning", "warning"), dialogInfo: register$2("dialog-info", "info"), dialogClose: register$2("dialog-close", "close"), treeItemExpanded: register$2("tree-item-expanded", "chevron-down"), // collapsed is done with rotation treeFilterOnTypeOn: register$2("tree-filter-on-type-on", "list-filter"), treeFilterOnTypeOff: register$2("tree-filter-on-type-off", "list-selection"), treeFilterClear: register$2("tree-filter-clear", "close"), treeItemLoading: register$2("tree-item-loading", "loading"), menuSelection: register$2("menu-selection", "check"), menuSubmenu: register$2("menu-submenu", "chevron-right"), menuBarMore: register$2("menubar-more", "more"), scrollbarButtonLeft: register$2("scrollbar-button-left", "triangle-left"), scrollbarButtonRight: register$2("scrollbar-button-right", "triangle-right"), scrollbarButtonUp: register$2("scrollbar-button-up", "triangle-up"), scrollbarButtonDown: register$2("scrollbar-button-down", "triangle-down"), toolBarMore: register$2("toolbar-more", "more"), quickInputBack: register$2("quick-input-back", "arrow-left"), dropDownButton: register$2("drop-down-button", 60084), symbolCustomColor: register$2("symbol-customcolor", 60252), exportIcon: register$2("export", 60332), workspaceUnspecified: register$2("workspace-unspecified", 60355), newLine: register$2("newline", 60394), thumbsDownFilled: register$2("thumbsdown-filled", 60435), thumbsUpFilled: register$2("thumbsup-filled", 60436), gitFetch: register$2("git-fetch", 60445), lightbulbSparkleAutofix: register$2("lightbulb-sparkle-autofix", 60447), debugBreakpointPending: register$2("debug-breakpoint-pending", 60377) }; const Codicon = { ...codiconsLibrary, ...codiconsDerived }; var ThemeColor; (function(ThemeColor2) { function isThemeColor(obj) { return !!obj && typeof obj === "object" && typeof obj.id === "string"; } ThemeColor2.isThemeColor = isThemeColor; })(ThemeColor || (ThemeColor = {})); var ThemeIcon; (function(ThemeIcon2) { ThemeIcon2.iconNameSegment = "[A-Za-z0-9]+"; ThemeIcon2.iconNameExpression = "[A-Za-z0-9-]+"; ThemeIcon2.iconModifierExpression = "~[A-Za-z]+"; ThemeIcon2.iconNameCharacter = "[A-Za-z0-9~-]"; const ThemeIconIdRegex = new RegExp(`^(${ThemeIcon2.iconNameExpression})(${ThemeIcon2.iconModifierExpression})?$`); function asClassNameArray(icon) { const match2 = ThemeIconIdRegex.exec(icon.id); if (!match2) { return asClassNameArray(Codicon.error); } const [, id, modifier] = match2; const classNames2 = ["codicon", "codicon-" + id]; if (modifier) { classNames2.push("codicon-modifier-" + modifier.substring(1)); } return classNames2; } ThemeIcon2.asClassNameArray = asClassNameArray; function asClassName(icon) { return asClassNameArray(icon).join(" "); } ThemeIcon2.asClassName = asClassName; function asCSSSelector(icon) { return "." + asClassNameArray(icon).join("."); } ThemeIcon2.asCSSSelector = asCSSSelector; function isThemeIcon(obj) { return !!obj && typeof obj === "object" && typeof obj.id === "string" && (typeof obj.color === "undefined" || ThemeColor.isThemeColor(obj.color)); } ThemeIcon2.isThemeIcon = isThemeIcon; const _regexFromString = new RegExp(`^\\$\\((${ThemeIcon2.iconNameExpression}(?:${ThemeIcon2.iconModifierExpression})?)\\)$`); function fromString(str) { const match2 = _regexFromString.exec(str); if (!match2) { return void 0; } const [, name] = match2; return { id: name }; } ThemeIcon2.fromString = fromString; function fromId(id) { return { id }; } ThemeIcon2.fromId = fromId; function modify(icon, modifier) { let id = icon.id; const tildeIndex = id.lastIndexOf("~"); if (tildeIndex !== -1) { id = id.substring(0, tildeIndex); } if (modifier) { id = `${id}~${modifier}`; } return { id }; } ThemeIcon2.modify = modify; function getModifier(icon) { const tildeIndex = icon.id.lastIndexOf("~"); if (tildeIndex !== -1) { return icon.id.substring(tildeIndex + 1); } return void 0; } ThemeIcon2.getModifier = getModifier; function isEqual2(ti1, ti2) { return ti1.id === ti2.id && ti1.color?.id === ti2.color?.id; } ThemeIcon2.isEqual = isEqual2; })(ThemeIcon || (ThemeIcon = {})); const ICommandService = createDecorator("commandService"); const CommandsRegistry = new class { constructor() { this._commands = /* @__PURE__ */ new Map(); this._onDidRegisterCommand = new Emitter$1(); this.onDidRegisterCommand = this._onDidRegisterCommand.event; } registerCommand(idOrCommand, handler) { if (!idOrCommand) { throw new Error(`invalid command`); } if (typeof idOrCommand === "string") { if (!handler) { throw new Error(`invalid command`); } return this.registerCommand({ id: idOrCommand, handler }); } if (idOrCommand.metadata && Array.isArray(idOrCommand.metadata.args)) { const constraints = []; for (const arg of idOrCommand.metadata.args) { constraints.push(arg.constraint); } const actualHandler = idOrCommand.handler; idOrCommand.handler = function(accessor, ...args) { validateConstraints(args, constraints); return actualHandler(accessor, ...args); }; } const { id } = idOrCommand; let commands = this._commands.get(id); if (!commands) { commands = new LinkedList(); this._commands.set(id, commands); } const removeFn = commands.unshift(idOrCommand); const ret = toDisposable(() => { removeFn(); const command = this._commands.get(id); if (command?.isEmpty()) { this._commands.delete(id); } }); this._onDidRegisterCommand.fire(id); return markAsSingleton(ret); } registerCommandAlias(oldId, newId) { return CommandsRegistry.registerCommand(oldId, (accessor, ...args) => accessor.get(ICommandService).executeCommand(newId, ...args)); } getCommand(id) { const list2 = this._commands.get(id); if (!list2 || list2.isEmpty()) { return void 0; } return Iterable.first(list2); } getCommands() { const result = /* @__PURE__ */ new Map(); for (const key of this._commands.keys()) { const command = this.getCommand(key); if (command) { result.set(key, command); } } return result; } }(); CommandsRegistry.registerCommand("noop", () => { }); function hintDidYouMean(...meant) { switch (meant.length) { case 1: return localize(1678, "Did you mean {0}?", meant[0]); case 2: return localize(1679, "Did you mean {0} or {1}?", meant[0], meant[1]); case 3: return localize(1680, "Did you mean {0}, {1} or {2}?", meant[0], meant[1], meant[2]); default: return void 0; } } const hintDidYouForgetToOpenOrCloseQuote = localize(1681, "Did you forget to open or close the quote?"); const hintDidYouForgetToEscapeSlash = localize(1682, "Did you forget to escape the '/' (slash) character? Put two backslashes before it to escape, e.g., '\\\\/'."); let Scanner$1 = (_b2 = class { constructor() { this._input = ""; this._start = 0; this._current = 0; this._tokens = []; this._errors = []; this.stringRe = /[a-zA-Z0-9_<>\-\./\\:\*\?\+\[\]\^,#@;"%\$\p{L}-]+/uy; } static getLexeme(token) { switch (token.type) { case 0: return "("; case 1: return ")"; case 2: return "!"; case 3: return token.isTripleEq ? "===" : "=="; case 4: return token.isTripleEq ? "!==" : "!="; case 5: return "<"; case 6: return "<="; case 7: return ">="; case 8: return ">="; case 9: return "=~"; case 10: return token.lexeme; case 11: return "true"; case 12: return "false"; case 13: return "in"; case 14: return "not"; case 15: return "&&"; case 16: return "||"; case 17: return token.lexeme; case 18: return token.lexeme; case 19: return token.lexeme; case 20: return "EOF"; default: throw illegalState(`unhandled token type: ${JSON.stringify(token)}; have you forgotten to add a case?`); } } reset(value) { this._input = value; this._start = 0; this._current = 0; this._tokens = []; this._errors = []; return this; } scan() { while (!this._isAtEnd()) { this._start = this._current; const ch = this._advance(); switch (ch) { case 40: this._addToken( 0 /* TokenType.LParen */ ); break; case 41: this._addToken( 1 /* TokenType.RParen */ ); break; case 33: if (this._match( 61 /* CharCode.Equals */ )) { const isTripleEq = this._match( 61 /* CharCode.Equals */ ); this._tokens.push({ type: 4, offset: this._start, isTripleEq }); } else { this._addToken( 2 /* TokenType.Neg */ ); } break; case 39: this._quotedString(); break; case 47: this._regex(); break; case 61: if (this._match( 61 /* CharCode.Equals */ )) { const isTripleEq = this._match( 61 /* CharCode.Equals */ ); this._tokens.push({ type: 3, offset: this._start, isTripleEq }); } else if (this._match( 126 /* CharCode.Tilde */ )) { this._addToken( 9 /* TokenType.RegexOp */ ); } else { this._error(hintDidYouMean("==", "=~")); } break; case 60: this._addToken( this._match( 61 /* CharCode.Equals */ ) ? 6 : 5 /* TokenType.Lt */ ); break; case 62: this._addToken( this._match( 61 /* CharCode.Equals */ ) ? 8 : 7 /* TokenType.Gt */ ); break; case 38: if (this._match( 38 /* CharCode.Ampersand */ )) { this._addToken( 15 /* TokenType.And */ ); } else { this._error(hintDidYouMean("&&")); } break; case 124: if (this._match( 124 /* CharCode.Pipe */ )) { this._addToken( 16 /* TokenType.Or */ ); } else { this._error(hintDidYouMean("||")); } break; // TODO@ulugbekna: 1) rewrite using a regex 2) reconsider what characters are considered whitespace, including unicode, nbsp, etc. case 32: case 13: case 9: case 10: case 160: break; default: this._string(); } } this._start = this._current; this._addToken( 20 /* TokenType.EOF */ ); return Array.from(this._tokens); } _match(expected) { if (this._isAtEnd()) { return false; } if (this._input.charCodeAt(this._current) !== expected) { return false; } this._current++; return true; } _advance() { return this._input.charCodeAt(this._current++); } _peek() { return this._isAtEnd() ? 0 : this._input.charCodeAt(this._current); } _addToken(type) { this._tokens.push({ type, offset: this._start }); } _error(additional) { const offset = this._start; const lexeme = this._input.substring(this._start, this._current); const errToken = { type: 19, offset: this._start, lexeme }; this._errors.push({ offset, lexeme, additionalInfo: additional }); this._tokens.push(errToken); } _string() { this.stringRe.lastIndex = this._start; const match2 = this.stringRe.exec(this._input); if (match2) { this._current = this._start + match2[0].length; const lexeme = this._input.substring(this._start, this._current); const keyword = _b2._keywords.get(lexeme); if (keyword) { this._addToken(keyword); } else { this._tokens.push({ type: 17, lexeme, offset: this._start }); } } } // captures the lexeme without the leading and trailing ' _quotedString() { while (this._peek() !== 39 && !this._isAtEnd()) { this._advance(); } if (this._isAtEnd()) { this._error(hintDidYouForgetToOpenOrCloseQuote); return; } this._advance(); this._tokens.push({ type: 18, lexeme: this._input.substring(this._start + 1, this._current - 1), offset: this._start + 1 }); } /* * Lexing a regex expression: /.../[igsmyu]* * Based on https://github.com/microsoft/TypeScript/blob/9247ef115e617805983740ba795d7a8164babf89/src/compiler/scanner.ts#L2129-L2181 * * Note that we want slashes within a regex to be escaped, e.g., /file:\\/\\/\\// should match `file:///` */ _regex() { let p = this._current; let inEscape = false; let inCharacterClass = false; while (true) { if (p >= this._input.length) { this._current = p; this._error(hintDidYouForgetToEscapeSlash); return; } const ch = this._input.charCodeAt(p); if (inEscape) { inEscape = false; } else if (ch === 47 && !inCharacterClass) { p++; break; } else if (ch === 91) { inCharacterClass = true; } else if (ch === 92) { inEscape = true; } else if (ch === 93) { inCharacterClass = false; } p++; } while (p < this._input.length && _b2._regexFlags.has(this._input.charCodeAt(p))) { p++; } this._current = p; const lexeme = this._input.substring(this._start, this._current); this._tokens.push({ type: 10, lexeme, offset: this._start }); } _isAtEnd() { return this._current >= this._input.length; } }, _b2._regexFlags = new Set(["i", "g", "s", "m", "y", "u"].map((ch) => ch.charCodeAt(0))), _b2._keywords = /* @__PURE__ */ new Map([ [ "not", 14 /* TokenType.Not */ ], [ "in", 13 /* TokenType.In */ ], [ "false", 12 /* TokenType.False */ ], [ "true", 11 /* TokenType.True */ ] ]), _b2); const CONSTANT_VALUES = /* @__PURE__ */ new Map(); CONSTANT_VALUES.set("false", false); CONSTANT_VALUES.set("true", true); CONSTANT_VALUES.set("isMac", isMacintosh); CONSTANT_VALUES.set("isLinux", isLinux); CONSTANT_VALUES.set("isWindows", isWindows); CONSTANT_VALUES.set("isWeb", isWeb); CONSTANT_VALUES.set("isMacNative", isMacintosh && !isWeb); CONSTANT_VALUES.set("isEdge", isEdge); CONSTANT_VALUES.set("isFirefox", isFirefox); CONSTANT_VALUES.set("isChrome", isChrome); CONSTANT_VALUES.set("isSafari", isSafari); const hasOwnProperty$1 = Object.prototype.hasOwnProperty; const defaultConfig = { regexParsingWithErrorRecovery: true }; const errorEmptyString = localize(1660, "Empty context key expression"); const hintEmptyString = localize(1661, "Did you forget to write an expression? You can also put 'false' or 'true' to always evaluate to false or true, respectively."); const errorNoInAfterNot = localize(1662, "'in' after 'not'."); const errorClosingParenthesis = localize(1663, "closing parenthesis ')'"); const errorUnexpectedToken = localize(1664, "Unexpected token"); const hintUnexpectedToken = localize(1665, "Did you forget to put && or || before the token?"); const errorUnexpectedEOF = localize(1666, "Unexpected end of expression"); const hintUnexpectedEOF = localize(1667, "Did you forget to put a context key?"); let Parser$1 = (_c2 = class { constructor(_config = defaultConfig) { this._config = _config; this._scanner = new Scanner$1(); this._tokens = []; this._current = 0; this._parsingErrors = []; this._flagsGYRe = /g|y/g; } /** * Parse a context key expression. * * @param input the expression to parse * @returns the parsed expression or `undefined` if there's an error - call `lexingErrors` and `parsingErrors` to see the errors */ parse(input) { if (input === "") { this._parsingErrors.push({ message: errorEmptyString, offset: 0, lexeme: "", additionalInfo: hintEmptyString }); return void 0; } this._tokens = this._scanner.reset(input).scan(); this._current = 0; this._parsingErrors = []; try { const expr = this._expr(); if (!this._isAtEnd()) { const peek = this._peek(); const additionalInfo = peek.type === 17 ? hintUnexpectedToken : void 0; this._parsingErrors.push({ message: errorUnexpectedToken, offset: peek.offset, lexeme: Scanner$1.getLexeme(peek), additionalInfo }); throw _c2._parseError; } return expr; } catch (e) { if (!(e === _c2._parseError)) { throw e; } return void 0; } } _expr() { return this._or(); } _or() { const expr = [this._and()]; while (this._matchOne( 16 /* TokenType.Or */ )) { const right = this._and(); expr.push(right); } return expr.length === 1 ? expr[0] : ContextKeyExpr.or(...expr); } _and() { const expr = [this._term()]; while (this._matchOne( 15 /* TokenType.And */ )) { const right = this._term(); expr.push(right); } return expr.length === 1 ? expr[0] : ContextKeyExpr.and(...expr); } _term() { if (this._matchOne( 2 /* TokenType.Neg */ )) { const peek = this._peek(); switch (peek.type) { case 11: this._advance(); return ContextKeyFalseExpr.INSTANCE; case 12: this._advance(); return ContextKeyTrueExpr.INSTANCE; case 0: { this._advance(); const expr = this._expr(); this._consume(1, errorClosingParenthesis); return expr?.negate(); } case 17: this._advance(); return ContextKeyNotExpr.create(peek.lexeme); default: throw this._errExpectedButGot(`KEY | true | false | '(' expression ')'`, peek); } } return this._primary(); } _primary() { const peek = this._peek(); switch (peek.type) { case 11: this._advance(); return ContextKeyExpr.true(); case 12: this._advance(); return ContextKeyExpr.false(); case 0: { this._advance(); const expr = this._expr(); this._consume(1, errorClosingParenthesis); return expr; } case 17: { const key = peek.lexeme; this._advance(); if (this._matchOne( 9 /* TokenType.RegexOp */ )) { const expr = this._peek(); if (!this._config.regexParsingWithErrorRecovery) { this._advance(); if (expr.type !== 10) { throw this._errExpectedButGot(`REGEX`, expr); } const regexLexeme = expr.lexeme; const closingSlashIndex = regexLexeme.lastIndexOf("/"); const flags = closingSlashIndex === regexLexeme.length - 1 ? void 0 : this._removeFlagsGY(regexLexeme.substring(closingSlashIndex + 1)); let regexp; try { regexp = new RegExp(regexLexeme.substring(1, closingSlashIndex), flags); } catch (e) { throw this._errExpectedButGot(`REGEX`, expr); } return ContextKeyRegexExpr.create(key, regexp); } switch (expr.type) { case 10: case 19: { const lexemeReconstruction = [expr.lexeme]; this._advance(); let followingToken = this._peek(); let parenBalance = 0; for (let i2 = 0; i2 < expr.lexeme.length; i2++) { if (expr.lexeme.charCodeAt(i2) === 40) { parenBalance++; } else if (expr.lexeme.charCodeAt(i2) === 41) { parenBalance--; } } while (!this._isAtEnd() && followingToken.type !== 15 && followingToken.type !== 16) { switch (followingToken.type) { case 0: parenBalance++; break; case 1: parenBalance--; break; case 10: case 18: for (let i2 = 0; i2 < followingToken.lexeme.length; i2++) { if (followingToken.lexeme.charCodeAt(i2) === 40) { parenBalance++; } else if (expr.lexeme.charCodeAt(i2) === 41) { parenBalance--; } } } if (parenBalance < 0) { break; } lexemeReconstruction.push(Scanner$1.getLexeme(followingToken)); this._advance(); followingToken = this._peek(); } const regexLexeme = lexemeReconstruction.join(""); const closingSlashIndex = regexLexeme.lastIndexOf("/"); const flags = closingSlashIndex === regexLexeme.length - 1 ? void 0 : this._removeFlagsGY(regexLexeme.substring(closingSlashIndex + 1)); let regexp; try { regexp = new RegExp(regexLexeme.substring(1, closingSlashIndex), flags); } catch (e) { throw this._errExpectedButGot(`REGEX`, expr); } return ContextKeyExpr.regex(key, regexp); } case 18: { const serializedValue = expr.lexeme; this._advance(); let regex = null; if (!isFalsyOrWhitespace(serializedValue)) { const start = serializedValue.indexOf("/"); const end = serializedValue.lastIndexOf("/"); if (start !== end && start >= 0) { const value = serializedValue.slice(start + 1, end); const caseIgnoreFlag = serializedValue[end + 1] === "i" ? "i" : ""; try { regex = new RegExp(value, caseIgnoreFlag); } catch (_e2) { throw this._errExpectedButGot(`REGEX`, expr); } } } if (regex === null) { throw this._errExpectedButGot("REGEX", expr); } return ContextKeyRegexExpr.create(key, regex); } default: throw this._errExpectedButGot("REGEX", this._peek()); } } if (this._matchOne( 14 /* TokenType.Not */ )) { this._consume(13, errorNoInAfterNot); const right = this._value(); return ContextKeyExpr.notIn(key, right); } const maybeOp = this._peek().type; switch (maybeOp) { case 3: { this._advance(); const right = this._value(); if (this._previous().type === 18) { return ContextKeyExpr.equals(key, right); } switch (right) { case "true": return ContextKeyExpr.has(key); case "false": return ContextKeyExpr.not(key); default: return ContextKeyExpr.equals(key, right); } } case 4: { this._advance(); const right = this._value(); if (this._previous().type === 18) { return ContextKeyExpr.notEquals(key, right); } switch (right) { case "true": return ContextKeyExpr.not(key); case "false": return ContextKeyExpr.has(key); default: return ContextKeyExpr.notEquals(key, right); } } // TODO: ContextKeyExpr.smaller(key, right) accepts only `number` as `right` AND during eval of this node, we just eval to `false` if `right` is not a number // consequently, package.json linter should _warn_ the user if they're passing undesired things to ops case 5: this._advance(); return ContextKeySmallerExpr.create(key, this._value()); case 6: this._advance(); return ContextKeySmallerEqualsExpr.create(key, this._value()); case 7: this._advance(); return ContextKeyGreaterExpr.create(key, this._value()); case 8: this._advance(); return ContextKeyGreaterEqualsExpr.create(key, this._value()); case 13: this._advance(); return ContextKeyExpr.in(key, this._value()); default: return ContextKeyExpr.has(key); } } case 20: this._parsingErrors.push({ message: errorUnexpectedEOF, offset: peek.offset, lexeme: "", additionalInfo: hintUnexpectedEOF }); throw _c2._parseError; default: throw this._errExpectedButGot(`true | false | KEY | KEY '=~' REGEX | KEY ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not' 'in') value`, this._peek()); } } _value() { const token = this._peek(); switch (token.type) { case 17: case 18: this._advance(); return token.lexeme; case 11: this._advance(); return "true"; case 12: this._advance(); return "false"; case 13: this._advance(); return "in"; default: return ""; } } _removeFlagsGY(flags) { return flags.replaceAll(this._flagsGYRe, ""); } // careful: this can throw if current token is the initial one (ie index = 0) _previous() { return this._tokens[this._current - 1]; } _matchOne(token) { if (this._check(token)) { this._advance(); return true; } return false; } _advance() { if (!this._isAtEnd()) { this._current++; } return this._previous(); } _consume(type, message) { if (this._check(type)) { return this._advance(); } throw this._errExpectedButGot(message, this._peek()); } _errExpectedButGot(expected, got, additionalInfo) { const message = localize(1668, "Expected: {0}\nReceived: '{1}'.", expected, Scanner$1.getLexeme(got)); const offset = got.offset; const lexeme = Scanner$1.getLexeme(got); this._parsingErrors.push({ message, offset, lexeme, additionalInfo }); return _c2._parseError; } _check(type) { return this._peek().type === type; } _peek() { return this._tokens[this._current]; } _isAtEnd() { return this._peek().type === 20; } }, _c2._parseError = new Error(), _c2); const _ContextKeyExpr = class _ContextKeyExpr { static false() { return ContextKeyFalseExpr.INSTANCE; } static true() { return ContextKeyTrueExpr.INSTANCE; } static has(key) { return ContextKeyDefinedExpr.create(key); } static equals(key, value) { return ContextKeyEqualsExpr.create(key, value); } static notEquals(key, value) { return ContextKeyNotEqualsExpr.create(key, value); } static regex(key, value) { return ContextKeyRegexExpr.create(key, value); } static in(key, value) { return ContextKeyInExpr.create(key, value); } static notIn(key, value) { return ContextKeyNotInExpr.create(key, value); } static not(key) { return ContextKeyNotExpr.create(key); } static and(...expr) { return ContextKeyAndExpr.create(expr, null, true); } static or(...expr) { return ContextKeyOrExpr.create(expr, null, true); } static deserialize(serialized) { if (serialized === void 0 || serialized === null) { return void 0; } const expr = this._parser.parse(serialized); return expr; } }; _ContextKeyExpr._parser = new Parser$1({ regexParsingWithErrorRecovery: false }); let ContextKeyExpr = _ContextKeyExpr; function expressionsAreEqualWithConstantSubstitution(a, b) { const aExpr = a ? a.substituteConstants() : void 0; const bExpr = b ? b.substituteConstants() : void 0; if (!aExpr && !bExpr) { return true; } if (!aExpr || !bExpr) { return false; } return aExpr.equals(bExpr); } function cmp(a, b) { return a.cmp(b); } const _ContextKeyFalseExpr = class _ContextKeyFalseExpr { constructor() { this.type = 0; } cmp(other) { return this.type - other.type; } equals(other) { return other.type === this.type; } substituteConstants() { return this; } evaluate(context) { return false; } serialize() { return "false"; } keys() { return []; } negate() { return ContextKeyTrueExpr.INSTANCE; } }; _ContextKeyFalseExpr.INSTANCE = new _ContextKeyFalseExpr(); let ContextKeyFalseExpr = _ContextKeyFalseExpr; const _ContextKeyTrueExpr = class _ContextKeyTrueExpr { constructor() { this.type = 1; } cmp(other) { return this.type - other.type; } equals(other) { return other.type === this.type; } substituteConstants() { return this; } evaluate(context) { return true; } serialize() { return "true"; } keys() { return []; } negate() { return ContextKeyFalseExpr.INSTANCE; } }; _ContextKeyTrueExpr.INSTANCE = new _ContextKeyTrueExpr(); let ContextKeyTrueExpr = _ContextKeyTrueExpr; class ContextKeyDefinedExpr { static create(key, negated = null) { const constantValue = CONSTANT_VALUES.get(key); if (typeof constantValue === "boolean") { return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE; } return new ContextKeyDefinedExpr(key, negated); } constructor(key, negated) { this.key = key; this.negated = negated; this.type = 2; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp1(this.key, other.key); } equals(other) { if (other.type === this.type) { return this.key === other.key; } return false; } substituteConstants() { const constantValue = CONSTANT_VALUES.get(this.key); if (typeof constantValue === "boolean") { return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE; } return this; } evaluate(context) { return !!context.getValue(this.key); } serialize() { return this.key; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyNotExpr.create(this.key, this); } return this.negated; } } class ContextKeyEqualsExpr { static create(key, value, negated = null) { if (typeof value === "boolean") { return value ? ContextKeyDefinedExpr.create(key, negated) : ContextKeyNotExpr.create(key, negated); } const constantValue = CONSTANT_VALUES.get(key); if (typeof constantValue === "boolean") { const trueValue = constantValue ? "true" : "false"; return value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE; } return new ContextKeyEqualsExpr(key, value, negated); } constructor(key, value, negated) { this.key = key; this.value = value; this.negated = negated; this.type = 4; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } equals(other) { if (other.type === this.type) { return this.key === other.key && this.value === other.value; } return false; } substituteConstants() { const constantValue = CONSTANT_VALUES.get(this.key); if (typeof constantValue === "boolean") { const trueValue = constantValue ? "true" : "false"; return this.value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE; } return this; } evaluate(context) { return context.getValue(this.key) == this.value; } serialize() { return `${this.key} == '${this.value}'`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyNotEqualsExpr.create(this.key, this.value, this); } return this.negated; } } class ContextKeyInExpr { static create(key, valueKey) { return new ContextKeyInExpr(key, valueKey); } constructor(key, valueKey) { this.key = key; this.valueKey = valueKey; this.type = 10; this.negated = null; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.valueKey, other.key, other.valueKey); } equals(other) { if (other.type === this.type) { return this.key === other.key && this.valueKey === other.valueKey; } return false; } substituteConstants() { return this; } evaluate(context) { const source = context.getValue(this.valueKey); const item = context.getValue(this.key); if (Array.isArray(source)) { return source.includes(item); } if (typeof item === "string" && typeof source === "object" && source !== null) { return hasOwnProperty$1.call(source, item); } return false; } serialize() { return `${this.key} in '${this.valueKey}'`; } keys() { return [this.key, this.valueKey]; } negate() { if (!this.negated) { this.negated = ContextKeyNotInExpr.create(this.key, this.valueKey); } return this.negated; } } class ContextKeyNotInExpr { static create(key, valueKey) { return new ContextKeyNotInExpr(key, valueKey); } constructor(key, valueKey) { this.key = key; this.valueKey = valueKey; this.type = 11; this._negated = ContextKeyInExpr.create(key, valueKey); } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return this._negated.cmp(other._negated); } equals(other) { if (other.type === this.type) { return this._negated.equals(other._negated); } return false; } substituteConstants() { return this; } evaluate(context) { return !this._negated.evaluate(context); } serialize() { return `${this.key} not in '${this.valueKey}'`; } keys() { return this._negated.keys(); } negate() { return this._negated; } } class ContextKeyNotEqualsExpr { static create(key, value, negated = null) { if (typeof value === "boolean") { if (value) { return ContextKeyNotExpr.create(key, negated); } return ContextKeyDefinedExpr.create(key, negated); } const constantValue = CONSTANT_VALUES.get(key); if (typeof constantValue === "boolean") { const falseValue = constantValue ? "true" : "false"; return value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE; } return new ContextKeyNotEqualsExpr(key, value, negated); } constructor(key, value, negated) { this.key = key; this.value = value; this.negated = negated; this.type = 5; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } equals(other) { if (other.type === this.type) { return this.key === other.key && this.value === other.value; } return false; } substituteConstants() { const constantValue = CONSTANT_VALUES.get(this.key); if (typeof constantValue === "boolean") { const falseValue = constantValue ? "true" : "false"; return this.value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE; } return this; } evaluate(context) { return context.getValue(this.key) != this.value; } serialize() { return `${this.key} != '${this.value}'`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyEqualsExpr.create(this.key, this.value, this); } return this.negated; } } class ContextKeyNotExpr { static create(key, negated = null) { const constantValue = CONSTANT_VALUES.get(key); if (typeof constantValue === "boolean") { return constantValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE; } return new ContextKeyNotExpr(key, negated); } constructor(key, negated) { this.key = key; this.negated = negated; this.type = 3; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp1(this.key, other.key); } equals(other) { if (other.type === this.type) { return this.key === other.key; } return false; } substituteConstants() { const constantValue = CONSTANT_VALUES.get(this.key); if (typeof constantValue === "boolean") { return constantValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE; } return this; } evaluate(context) { return !context.getValue(this.key); } serialize() { return `!${this.key}`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyDefinedExpr.create(this.key, this); } return this.negated; } } function withFloatOrStr(value, callback) { if (typeof value === "string") { const n2 = parseFloat(value); if (!isNaN(n2)) { value = n2; } } if (typeof value === "string" || typeof value === "number") { return callback(value); } return ContextKeyFalseExpr.INSTANCE; } class ContextKeyGreaterExpr { static create(key, _value, negated = null) { return withFloatOrStr(_value, (value) => new ContextKeyGreaterExpr(key, value, negated)); } constructor(key, value, negated) { this.key = key; this.value = value; this.negated = negated; this.type = 12; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } equals(other) { if (other.type === this.type) { return this.key === other.key && this.value === other.value; } return false; } substituteConstants() { return this; } evaluate(context) { if (typeof this.value === "string") { return false; } return parseFloat(context.getValue(this.key)) > this.value; } serialize() { return `${this.key} > ${this.value}`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeySmallerEqualsExpr.create(this.key, this.value, this); } return this.negated; } } class ContextKeyGreaterEqualsExpr { static create(key, _value, negated = null) { return withFloatOrStr(_value, (value) => new ContextKeyGreaterEqualsExpr(key, value, negated)); } constructor(key, value, negated) { this.key = key; this.value = value; this.negated = negated; this.type = 13; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } equals(other) { if (other.type === this.type) { return this.key === other.key && this.value === other.value; } return false; } substituteConstants() { return this; } evaluate(context) { if (typeof this.value === "string") { return false; } return parseFloat(context.getValue(this.key)) >= this.value; } serialize() { return `${this.key} >= ${this.value}`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeySmallerExpr.create(this.key, this.value, this); } return this.negated; } } class ContextKeySmallerExpr { static create(key, _value, negated = null) { return withFloatOrStr(_value, (value) => new ContextKeySmallerExpr(key, value, negated)); } constructor(key, value, negated) { this.key = key; this.value = value; this.negated = negated; this.type = 14; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } equals(other) { if (other.type === this.type) { return this.key === other.key && this.value === other.value; } return false; } substituteConstants() { return this; } evaluate(context) { if (typeof this.value === "string") { return false; } return parseFloat(context.getValue(this.key)) < this.value; } serialize() { return `${this.key} < ${this.value}`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyGreaterEqualsExpr.create(this.key, this.value, this); } return this.negated; } } class ContextKeySmallerEqualsExpr { static create(key, _value, negated = null) { return withFloatOrStr(_value, (value) => new ContextKeySmallerEqualsExpr(key, value, negated)); } constructor(key, value, negated) { this.key = key; this.value = value; this.negated = negated; this.type = 15; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return cmp2(this.key, this.value, other.key, other.value); } equals(other) { if (other.type === this.type) { return this.key === other.key && this.value === other.value; } return false; } substituteConstants() { return this; } evaluate(context) { if (typeof this.value === "string") { return false; } return parseFloat(context.getValue(this.key)) <= this.value; } serialize() { return `${this.key} <= ${this.value}`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyGreaterExpr.create(this.key, this.value, this); } return this.negated; } } class ContextKeyRegexExpr { static create(key, regexp) { return new ContextKeyRegexExpr(key, regexp); } constructor(key, regexp) { this.key = key; this.regexp = regexp; this.type = 7; this.negated = null; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } if (this.key < other.key) { return -1; } if (this.key > other.key) { return 1; } const thisSource = this.regexp ? this.regexp.source : ""; const otherSource = other.regexp ? other.regexp.source : ""; if (thisSource < otherSource) { return -1; } if (thisSource > otherSource) { return 1; } return 0; } equals(other) { if (other.type === this.type) { const thisSource = this.regexp ? this.regexp.source : ""; const otherSource = other.regexp ? other.regexp.source : ""; return this.key === other.key && thisSource === otherSource; } return false; } substituteConstants() { return this; } evaluate(context) { const value = context.getValue(this.key); return this.regexp ? this.regexp.test(value) : false; } serialize() { const value = this.regexp ? `/${this.regexp.source}/${this.regexp.flags}` : "/invalid/"; return `${this.key} =~ ${value}`; } keys() { return [this.key]; } negate() { if (!this.negated) { this.negated = ContextKeyNotRegexExpr.create(this); } return this.negated; } } class ContextKeyNotRegexExpr { static create(actual) { return new ContextKeyNotRegexExpr(actual); } constructor(_actual) { this._actual = _actual; this.type = 8; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } return this._actual.cmp(other._actual); } equals(other) { if (other.type === this.type) { return this._actual.equals(other._actual); } return false; } substituteConstants() { return this; } evaluate(context) { return !this._actual.evaluate(context); } serialize() { return `!(${this._actual.serialize()})`; } keys() { return this._actual.keys(); } negate() { return this._actual; } } function eliminateConstantsInArray(arr) { let newArr = null; for (let i2 = 0, len = arr.length; i2 < len; i2++) { const newExpr = arr[i2].substituteConstants(); if (arr[i2] !== newExpr) { if (newArr === null) { newArr = []; for (let j = 0; j < i2; j++) { newArr[j] = arr[j]; } } } if (newArr !== null) { newArr[i2] = newExpr; } } if (newArr === null) { return arr; } return newArr; } class ContextKeyAndExpr { static create(_expr, negated, extraRedundantCheck) { return ContextKeyAndExpr._normalizeArr(_expr, negated, extraRedundantCheck); } constructor(expr, negated) { this.expr = expr; this.negated = negated; this.type = 6; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } if (this.expr.length < other.expr.length) { return -1; } if (this.expr.length > other.expr.length) { return 1; } for (let i2 = 0, len = this.expr.length; i2 < len; i2++) { const r = cmp(this.expr[i2], other.expr[i2]); if (r !== 0) { return r; } } return 0; } equals(other) { if (other.type === this.type) { if (this.expr.length !== other.expr.length) { return false; } for (let i2 = 0, len = this.expr.length; i2 < len; i2++) { if (!this.expr[i2].equals(other.expr[i2])) { return false; } } return true; } return false; } substituteConstants() { const exprArr = eliminateConstantsInArray(this.expr); if (exprArr === this.expr) { return this; } return ContextKeyAndExpr.create(exprArr, this.negated, false); } evaluate(context) { for (let i2 = 0, len = this.expr.length; i2 < len; i2++) { if (!this.expr[i2].evaluate(context)) { return false; } } return true; } static _normalizeArr(arr, negated, extraRedundantCheck) { const expr = []; let hasTrue = false; for (const e of arr) { if (!e) { continue; } if (e.type === 1) { hasTrue = true; continue; } if (e.type === 0) { return ContextKeyFalseExpr.INSTANCE; } if (e.type === 6) { expr.push(...e.expr); continue; } expr.push(e); } if (expr.length === 0 && hasTrue) { return ContextKeyTrueExpr.INSTANCE; } if (expr.length === 0) { return void 0; } if (expr.length === 1) { return expr[0]; } expr.sort(cmp); for (let i2 = 1; i2 < expr.length; i2++) { if (expr[i2 - 1].equals(expr[i2])) { expr.splice(i2, 1); i2--; } } if (expr.length === 1) { return expr[0]; } while (expr.length > 1) { const lastElement = expr[expr.length - 1]; if (lastElement.type !== 9) { break; } expr.pop(); const secondToLastElement = expr.pop(); const isFinished = expr.length === 0; const resultElement = ContextKeyOrExpr.create(lastElement.expr.map((el) => ContextKeyAndExpr.create([el, secondToLastElement], null, extraRedundantCheck)), null, isFinished); if (resultElement) { expr.push(resultElement); expr.sort(cmp); } } if (expr.length === 1) { return expr[0]; } if (extraRedundantCheck) { for (let i2 = 0; i2 < expr.length; i2++) { for (let j = i2 + 1; j < expr.length; j++) { if (expr[i2].negate().equals(expr[j])) { return ContextKeyFalseExpr.INSTANCE; } } } if (expr.length === 1) { return expr[0]; } } return new ContextKeyAndExpr(expr, negated); } serialize() { return this.expr.map((e) => e.serialize()).join(" && "); } keys() { const result = []; for (const expr of this.expr) { result.push(...expr.keys()); } return result; } negate() { if (!this.negated) { const result = []; for (const expr of this.expr) { result.push(expr.negate()); } this.negated = ContextKeyOrExpr.create(result, this, true); } return this.negated; } } class ContextKeyOrExpr { static create(_expr, negated, extraRedundantCheck) { return ContextKeyOrExpr._normalizeArr(_expr, negated, extraRedundantCheck); } constructor(expr, negated) { this.expr = expr; this.negated = negated; this.type = 9; } cmp(other) { if (other.type !== this.type) { return this.type - other.type; } if (this.expr.length < other.expr.length) { return -1; } if (this.expr.length > other.expr.length) { return 1; } for (let i2 = 0, len = this.expr.length; i2 < len; i2++) { const r = cmp(this.expr[i2], other.expr[i2]); if (r !== 0) { return r; } } return 0; } equals(other) { if (other.type === this.type) { if (this.expr.length !== other.expr.length) { return false; } for (let i2 = 0, len = this.expr.length; i2 < len; i2++) { if (!this.expr[i2].equals(other.expr[i2])) { return false; } } return true; } return false; } substituteConstants() { const exprArr = eliminateConstantsInArray(this.expr); if (exprArr === this.expr) { return this; } return ContextKeyOrExpr.create(exprArr, this.negated, false); } evaluate(context) { for (let i2 = 0, len = this.expr.length; i2 < len; i2++) { if (this.expr[i2].evaluate(context)) { return true; } } return false; } static _normalizeArr(arr, negated, extraRedundantCheck) { let expr = []; let hasFalse = false; if (arr) { for (let i2 = 0, len = arr.length; i2 < len; i2++) { const e = arr[i2]; if (!e) { continue; } if (e.type === 0) { hasFalse = true; continue; } if (e.type === 1) { return ContextKeyTrueExpr.INSTANCE; } if (e.type === 9) { expr = expr.concat(e.expr); continue; } expr.push(e); } if (expr.length === 0 && hasFalse) { return ContextKeyFalseExpr.INSTANCE; } expr.sort(cmp); } if (expr.length === 0) { return void 0; } if (expr.length === 1) { return expr[0]; } for (let i2 = 1; i2 < expr.length; i2++) { if (expr[i2 - 1].equals(expr[i2])) { expr.splice(i2, 1); i2--; } } if (expr.length === 1) { return expr[0]; } if (extraRedundantCheck) { for (let i2 = 0; i2 < expr.length; i2++) { for (let j = i2 + 1; j < expr.length; j++) { if (expr[i2].negate().equals(expr[j])) { return ContextKeyTrueExpr.INSTANCE; } } } if (expr.length === 1) { return expr[0]; } } return new ContextKeyOrExpr(expr, negated); } serialize() { return this.expr.map((e) => e.serialize()).join(" || "); } keys() { const result = []; for (const expr of this.expr) { result.push(...expr.keys()); } return result; } negate() { if (!this.negated) { const result = []; for (const expr of this.expr) { result.push(expr.negate()); } while (result.length > 1) { const LEFT = result.shift(); const RIGHT = result.shift(); const all = []; for (const left of getTerminals(LEFT)) { for (const right of getTerminals(RIGHT)) { all.push(ContextKeyAndExpr.create([left, right], null, false)); } } result.unshift(ContextKeyOrExpr.create(all, null, false)); } this.negated = ContextKeyOrExpr.create(result, this, true); } return this.negated; } } const _RawContextKey = class _RawContextKey extends ContextKeyDefinedExpr { static all() { return _RawContextKey._info.values(); } constructor(key, defaultValue, metaOrHide) { super(key, null); this._defaultValue = defaultValue; if (typeof metaOrHide === "object") { _RawContextKey._info.push({ ...metaOrHide, key }); } else if (metaOrHide !== true) { _RawContextKey._info.push({ key, description: metaOrHide, type: defaultValue !== null && defaultValue !== void 0 ? typeof defaultValue : void 0 }); } } bindTo(target) { return target.createKey(this.key, this._defaultValue); } getValue(target) { return target.getContextKeyValue(this.key); } toNegated() { return this.negate(); } isEqualTo(value) { return ContextKeyEqualsExpr.create(this.key, value); } }; _RawContextKey._info = []; let RawContextKey = _RawContextKey; const IContextKeyService = createDecorator("contextKeyService"); function cmp1(key1, key2) { if (key1 < key2) { return -1; } if (key1 > key2) { return 1; } return 0; } function cmp2(key1, value1, key2, value2) { if (key1 < key2) { return -1; } if (key1 > key2) { return 1; } if (value1 < value2) { return -1; } if (value1 > value2) { return 1; } return 0; } function implies(p, q) { if (p.type === 0 || q.type === 1) { return true; } if (p.type === 9) { if (q.type === 9) { return allElementsIncluded(p.expr, q.expr); } return false; } if (q.type === 9) { for (const element of q.expr) { if (implies(p, element)) { return true; } } return false; } if (p.type === 6) { if (q.type === 6) { return allElementsIncluded(q.expr, p.expr); } for (const element of p.expr) { if (implies(element, q)) { return true; } } return false; } return p.equals(q); } function allElementsIncluded(p, q) { let pIndex = 0; let qIndex = 0; while (pIndex < p.length && qIndex < q.length) { const cmp3 = p[pIndex].cmp(q[qIndex]); if (cmp3 < 0) { return false; } else if (cmp3 === 0) { pIndex++; qIndex++; } else { qIndex++; } } return pIndex === p.length; } function getTerminals(node) { if (node.type === 9) { return node.expr; } return [node]; } class RegistryImpl { constructor() { this.data = /* @__PURE__ */ new Map(); } add(id, data) { ok(isString$1(id)); ok(isObject(data)); ok(!this.data.has(id), "There is already an extension with this id"); this.data.set(id, data); } as(id) { return this.data.get(id) || null; } dispose() { this.data.forEach((value) => { if (isFunction(value.dispose)) { value.dispose(); } }); this.data.clear(); } } const Registry = new RegistryImpl(); class KeybindingsRegistryImpl { constructor() { this._coreKeybindings = new LinkedList(); this._extensionKeybindings = []; this._cachedMergedKeybindings = null; } /** * Take current platform into account and reduce to primary & secondary. */ static bindToCurrentPlatform(kb) { if (OS === 1) { if (kb && kb.win) { return kb.win; } } else if (OS === 2) { if (kb && kb.mac) { return kb.mac; } } else { if (kb && kb.linux) { return kb.linux; } } return kb; } registerKeybindingRule(rule) { const actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule); const result = new DisposableStore(); if (actualKb && actualKb.primary) { const kk = decodeKeybinding(actualKb.primary, OS); if (kk) { result.add(this._registerDefaultKeybinding(kk, rule.id, rule.args, rule.weight, 0, rule.when)); } } if (actualKb && Array.isArray(actualKb.secondary)) { for (let i2 = 0, len = actualKb.secondary.length; i2 < len; i2++) { const k = actualKb.secondary[i2]; const kk = decodeKeybinding(k, OS); if (kk) { result.add(this._registerDefaultKeybinding(kk, rule.id, rule.args, rule.weight, -i2 - 1, rule.when)); } } } return result; } registerCommandAndKeybindingRule(desc) { return combinedDisposable(this.registerKeybindingRule(desc), CommandsRegistry.registerCommand(desc)); } _registerDefaultKeybinding(keybinding, commandId, commandArgs, weight1, weight2, when) { const remove = this._coreKeybindings.push({ keybinding, command: commandId, commandArgs, when, weight1, weight2, extensionId: null, isBuiltinExtension: false }); this._cachedMergedKeybindings = null; return toDisposable(() => { remove(); this._cachedMergedKeybindings = null; }); } getDefaultKeybindings() { if (!this._cachedMergedKeybindings) { this._cachedMergedKeybindings = Array.from(this._coreKeybindings).concat(this._extensionKeybindings); this._cachedMergedKeybindings.sort(sorter); } return this._cachedMergedKeybindings.slice(0); } } const KeybindingsRegistry = new KeybindingsRegistryImpl(); const Extensions$9 = { EditorModes: "platform.keybindingsRegistry" }; Registry.add(Extensions$9.EditorModes, KeybindingsRegistry); function sorter(a, b) { if (a.weight1 !== b.weight1) { return a.weight1 - b.weight1; } if (a.command && b.command) { if (a.command < b.command) { return -1; } if (a.command > b.command) { return 1; } } return a.weight2 - b.weight2; } var __decorate$35 = function(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d = decorators[i2]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param$2_ = function(paramIndex, decorator) { return function(target, key) { decorator(target, key, paramIndex); }; }; var MenuItemAction_1; function isIMenuItem(item) { return item.command !== void 0; } function isISubmenuItem(item) { return item.submenu !== void 0; } const _MenuId = class _MenuId { /** * Create a new `MenuId` with the unique identifier. Will throw if a menu * with the identifier already exists, use `MenuId.for(ident)` or a unique * identifier */ constructor(identifier) { if (_MenuId._instances.has(identifier)) { throw new TypeError(`MenuId with identifier '${identifier}' already exists. Use MenuId.for(ident) or a unique identifier`); } _MenuId._instances.set(identifier, this); this.id = identifier; } }; _MenuId._instances = /* @__PURE__ */ new Map(); _MenuId.CommandPalette = new _MenuId("CommandPalette"); _MenuId.DebugBreakpointsContext = new _MenuId("DebugBreakpointsContext"); _MenuId.DebugCallStackContext = new _MenuId("DebugCallStackContext"); _MenuId.DebugConsoleContext = new _MenuId("DebugConsoleContext"); _MenuId.DebugVariablesContext = new _MenuId("DebugVariablesContext"); _MenuId.NotebookVariablesContext = new _MenuId("NotebookVariablesContext"); _MenuId.DebugHoverContext = new _MenuId("DebugHoverContext"); _MenuId.DebugWatchContext = new _MenuId("DebugWatchContext"); _MenuId.DebugToolBar = new _MenuId("DebugToolBar"); _MenuId.DebugToolBarStop = new _MenuId("DebugToolBarStop"); _MenuId.DebugDisassemblyContext = new _MenuId("DebugDisassemblyContext"); _MenuId.DebugCallStackToolbar = new _MenuId("DebugCallStackToolbar"); _MenuId.DebugCreateConfiguration = new _MenuId("DebugCreateConfiguration"); _MenuId.EditorContext = new _MenuId("EditorContext"); _MenuId.SimpleEditorContext = new _MenuId("SimpleEditorContext"); _MenuId.EditorContent = new _MenuId("EditorContent"); _MenuId.EditorLineNumberContext = new _MenuId("EditorLineNumberContext"); _MenuId.EditorContextCopy = new _MenuId("EditorContextCopy"); _MenuId.EditorContextPeek = new _MenuId("EditorContextPeek"); _MenuId.EditorContextShare = new _MenuId("EditorContextShare"); _MenuId.EditorTitle = new _MenuId("EditorTitle"); _MenuId.CompactWindowEditorTitle = new _MenuId("CompactWindowEditorTitle"); _MenuId.EditorTitleRun = new _MenuId("EditorTitleRun"); _MenuId.EditorTitleContext = new _MenuId("EditorTitleContext"); _MenuId.EditorTitleContextShare = new _MenuId("EditorTitleContextShare"); _MenuId.EmptyEditorGroup = new _MenuId("EmptyEditorGroup"); _MenuId.EmptyEditorGroupContext = new _MenuId("EmptyEditorGroupContext"); _MenuId.EditorTabsBarContext = new _MenuId("EditorTabsBarContext"); _MenuId.EditorTabsBarShowTabsSubmenu = new _MenuId("EditorTabsBarShowTabsSubmenu"); _MenuId.EditorTabsBarShowTabsZenModeSubmenu = new _MenuId("EditorTabsBarShowTabsZenModeSubmenu"); _MenuId.EditorActionsPositionSubmenu = new _MenuId("EditorActionsPositionSubmenu"); _MenuId.EditorSplitMoveSubmenu = new _MenuId("EditorSplitMoveSubmenu"); _MenuId.ExplorerContext = new _MenuId("ExplorerContext"); _MenuId.ExplorerContextShare = new _MenuId("ExplorerContextShare"); _MenuId.ExtensionContext = new _MenuId("ExtensionContext"); _MenuId.ExtensionEditorContextMenu = new _MenuId("ExtensionEditorContextMenu"); _MenuId.GlobalActivity = new _MenuId("GlobalActivity"); _MenuId.CommandCenter = new _MenuId("CommandCenter"); _MenuId.CommandCenterCenter = new _MenuId("CommandCenterCenter"); _MenuId.LayoutControlMenuSubmenu = new _MenuId("LayoutControlMenuSubmenu"); _MenuId.LayoutControlMenu = new _MenuId("LayoutControlMenu"); _MenuId.MenubarMainMenu = new _MenuId("MenubarMainMenu"); _MenuId.MenubarAppearanceMenu = new _MenuId("MenubarAppearanceMenu"); _MenuId.MenubarDebugMenu = new _MenuId("MenubarDebugMenu"); _MenuId.MenubarEditMenu = new _MenuId("MenubarEditMenu"); _MenuId.MenubarCopy = new _MenuId("MenubarCopy"); _MenuId.MenubarFileMenu = new _MenuId("MenubarFileMenu"); _MenuId.MenubarGoMenu = new _MenuId("MenubarGoMenu"); _MenuId.MenubarHelpMenu = new _MenuId("MenubarHelpMenu"); _MenuId.MenubarLayoutMenu = new _MenuId("MenubarLayoutMenu"); _MenuId.MenubarNewBreakpointMenu = new _MenuId("MenubarNewBreakpointMenu"); _MenuId.PanelAlignmentMenu = new _MenuId("PanelAlignmentMenu"); _MenuId.PanelPositionMenu = new _MenuId("PanelPositionMenu"); _MenuId.ActivityBarPositionMenu = new _MenuId("ActivityBarPositionMenu"); _MenuId.MenubarPreferencesMenu = new _MenuId("MenubarPreferencesMenu"); _MenuId.MenubarRecentMenu = new _MenuId("MenubarRecentMenu"); _MenuId.MenubarSelectionMenu = new _MenuId("MenubarSelectionMenu"); _MenuId.MenubarShare = new _MenuId("MenubarShare"); _MenuId.MenubarSwitchEditorMenu = new _MenuId("MenubarSwitchEditorMenu"); _MenuId.MenubarSwitchGroupMenu = new _MenuId("MenubarSwitchGroupMenu"); _MenuId.MenubarTerminalMenu = new _MenuId("MenubarTerminalMenu"); _MenuId.MenubarTerminalSuggestStatusMenu = new _MenuId("MenubarTerminalSuggestStatusMenu"); _MenuId.MenubarViewMenu = new _MenuId("MenubarViewMenu"); _MenuId.MenubarHomeMenu = new _MenuId("MenubarHomeMenu"); _MenuId.OpenEditorsContext = new _MenuId("OpenEditorsContext"); _MenuId.OpenEditorsContextShare = new _MenuId("OpenEditorsContextShare"); _MenuId.ProblemsPanelContext = new _MenuId("ProblemsPanelContext"); _MenuId.SCMInputBox = new _MenuId("SCMInputBox"); _MenuId.SCMChangeContext = new _MenuId("SCMChangeContext"); _MenuId.SCMResourceContext = new _MenuId("SCMResourceContext"); _MenuId.SCMResourceContextShare = new _MenuId("SCMResourceContextShare"); _MenuId.SCMResourceFolderContext = new _MenuId("SCMResourceFolderContext"); _MenuId.SCMResourceGroupContext = new _MenuId("SCMResourceGroupContext"); _MenuId.SCMSourceControl = new _MenuId("SCMSourceControl"); _MenuId.SCMSourceControlInline = new _MenuId("SCMSourceControlInline"); _MenuId.SCMSourceControlTitle = new _MenuId("SCMSourceControlTitle"); _MenuId.SCMHistoryTitle = new _MenuId("SCMHistoryTitle"); _MenuId.SCMHistoryItemContext = new _MenuId("SCMHistoryItemContext"); _MenuId.SCMHistoryItemChangeContext = new _MenuId("SCMHistoryItemChangeContext"); _MenuId.SCMHistoryItemHover = new _MenuId("SCMHistoryItemHover"); _MenuId.SCMHistoryItemRefContext = new _MenuId("SCMHistoryItemRefContext"); _MenuId.SCMQuickDiffDecorations = new _MenuId("SCMQuickDiffDecorations"); _MenuId.SCMTitle = new _MenuId("SCMTitle"); _MenuId.SearchContext = new _MenuId("SearchContext"); _MenuId.SearchActionMenu = new _MenuId("SearchActionContext"); _MenuId.StatusBarWindowIndicatorMenu = new _MenuId("StatusBarWindowIndicatorMenu"); _MenuId.StatusBarRemoteIndicatorMenu = new _MenuId("StatusBarRemoteIndicatorMenu"); _MenuId.StickyScrollContext = new _MenuId("StickyScrollContext"); _MenuId.TestItem = new _MenuId("TestItem"); _MenuId.TestItemGutter = new _MenuId("TestItemGutter"); _MenuId.TestProfilesContext = new _MenuId("TestProfilesContext"); _MenuId.TestMessageContext = new _MenuId("TestMessageContext"); _MenuId.TestMessageContent = new _MenuId("TestMessageContent"); _MenuId.TestPeekElement = new _MenuId("TestPeekElement"); _MenuId.TestPeekTitle = new _MenuId("TestPeekTitle"); _MenuId.TestCallStack = new _MenuId("TestCallStack"); _MenuId.TestCoverageFilterItem = new _MenuId("TestCoverageFilterItem"); _MenuId.TouchBarContext = new _MenuId("TouchBarContext"); _MenuId.TitleBar = new _MenuId("TitleBar"); _MenuId.TitleBarContext = new _MenuId("TitleBarContext"); _MenuId.TitleBarTitleContext = new _MenuId("TitleBarTitleContext"); _MenuId.TunnelContext = new _MenuId("TunnelContext"); _MenuId.TunnelPrivacy = new _MenuId("TunnelPrivacy"); _MenuId.TunnelProtocol = new _MenuId("TunnelProtocol"); _MenuId.TunnelPortInline = new _MenuId("TunnelInline"); _MenuId.TunnelTitle = new _MenuId("TunnelTitle"); _MenuId.TunnelLocalAddressInline = new _MenuId("TunnelLocalAddressInline"); _MenuId.TunnelOriginInline = new _MenuId("TunnelOriginInline"); _MenuId.ViewItemContext = new _MenuId("ViewItemContext"); _MenuId.ViewContainerTitle = new _MenuId("ViewContainerTitle"); _MenuId.ViewContainerTitleContext = new _MenuId("ViewContainerTitleContext"); _MenuId.ViewTitle = new _MenuId("ViewTitle"); _MenuId.ViewTitleContext = new _MenuId("ViewTitleContext"); _MenuId.CommentEditorActions = new _MenuId("CommentEditorActions"); _MenuId.CommentThreadTitle = new _MenuId("CommentThreadTitle"); _MenuId.CommentThreadActions = new _MenuId("CommentThreadActions"); _MenuId.CommentThreadAdditionalActions = new _MenuId("CommentThreadAdditionalActions"); _MenuId.CommentThreadTitleContext = new _MenuId("CommentThreadTitleContext"); _MenuId.CommentThreadCommentContext = new _MenuId("CommentThreadCommentContext"); _MenuId.CommentTitle = new _MenuId("CommentTitle"); _MenuId.CommentActions = new _MenuId("CommentActions"); _MenuId.CommentsViewThreadActions = new _MenuId("CommentsViewThreadActions"); _MenuId.InteractiveToolbar = new _MenuId("InteractiveToolbar"); _MenuId.InteractiveCellTitle = new _MenuId("InteractiveCellTitle"); _MenuId.InteractiveCellDelete = new _MenuId("InteractiveCellDelete"); _MenuId.InteractiveCellExecute = new _MenuId("InteractiveCellExecute"); _MenuId.InteractiveInputExecute = new _MenuId("InteractiveInputExecute"); _MenuId.InteractiveInputConfig = new _MenuId("InteractiveInputConfig"); _MenuId.ReplInputExecute = new _MenuId("ReplInputExecute"); _MenuId.IssueReporter = new _MenuId("IssueReporter"); _MenuId.NotebookToolbar = new _MenuId("NotebookToolbar"); _MenuId.NotebookToolbarContext = new _MenuId("NotebookToolbarContext"); _MenuId.NotebookStickyScrollContext = new _MenuId("NotebookStickyScrollContext"); _MenuId.NotebookCellTitle = new _MenuId("NotebookCellTitle"); _MenuId.NotebookCellDelete = new _MenuId("NotebookCellDelete"); _MenuId.NotebookCellInsert = new _MenuId("NotebookCellInsert"); _MenuId.NotebookCellBetween = new _MenuId("NotebookCellBetween"); _MenuId.NotebookCellListTop = new _MenuId("NotebookCellTop"); _MenuId.NotebookCellExecute = new _MenuId("NotebookCellExecute"); _MenuId.NotebookCellExecuteGoTo = new _MenuId("NotebookCellExecuteGoTo"); _MenuId.NotebookCellExecutePrimary = new _MenuId("NotebookCellExecutePrimary"); _MenuId.NotebookDiffCellInputTitle = new _MenuId("NotebookDiffCellInputTitle"); _MenuId.NotebookDiffDocumentMetadata = new _MenuId("NotebookDiffDocumentMetadata"); _MenuId.NotebookDiffCellMetadataTitle = new _MenuId("NotebookDiffCellMetadataTitle"); _MenuId.NotebookDiffCellOutputsTitle = new _MenuId("NotebookDiffCellOutputsTitle"); _MenuId.NotebookOutputToolbar = new _MenuId("NotebookOutputToolbar"); _MenuId.NotebookOutlineFilter = new _MenuId("NotebookOutlineFilter"); _MenuId.NotebookOutlineActionMenu = new _MenuId("NotebookOutlineActionMenu"); _MenuId.NotebookEditorLayoutConfigure = new _MenuId("NotebookEditorLayoutConfigure"); _MenuId.NotebookKernelSource = new _MenuId("NotebookKernelSource"); _MenuId.BulkEditTitle = new _MenuId("BulkEditTitle"); _MenuId.BulkEditContext = new _MenuId("BulkEditContext"); _MenuId.TimelineItemContext = new _MenuId("TimelineItemContext"); _MenuId.TimelineTitle = new _MenuId("TimelineTitle"); _MenuId.TimelineTitleContext = new _MenuId("TimelineTitleContext"); _MenuId.TimelineFilterSubMenu = new _MenuId("TimelineFilterSubMenu"); _MenuId.AccountsContext = new _MenuId("AccountsContext"); _MenuId.SidebarTitle = new _MenuId("SidebarTitle"); _MenuId.PanelTitle = new _MenuId("PanelTitle"); _MenuId.AuxiliaryBarTitle = new _MenuId("AuxiliaryBarTitle"); _MenuId.TerminalInstanceContext = new _MenuId("TerminalInstanceContext"); _MenuId.TerminalEditorInstanceContext = new _MenuId("TerminalEditorInstanceContext"); _MenuId.TerminalNewDropdownContext = new _MenuId("TerminalNewDropdownContext"); _MenuId.TerminalTabContext = new _MenuId("TerminalTabContext"); _MenuId.TerminalTabEmptyAreaContext = new _MenuId("TerminalTabEmptyAreaContext"); _MenuId.TerminalStickyScrollContext = new _MenuId("TerminalStickyScrollContext"); _MenuId.WebviewContext = new _MenuId("WebviewContext"); _MenuId.InlineCompletionsActions = new _MenuId("InlineCompletionsActions"); _MenuId.InlineEditsActions = new _MenuId("InlineEditsActions"); _MenuId.NewFile = new _MenuId("NewFile"); _MenuId.MergeInput1Toolbar = new _MenuId("MergeToolbar1Toolbar"); _MenuId.MergeInput2Toolbar = new _MenuId("MergeToolbar2Toolbar"); _MenuId.MergeBaseToolbar = new _MenuId("MergeBaseToolbar"); _MenuId.MergeInputResultToolbar = new _MenuId("MergeToolbarResultToolbar"); _MenuId.InlineSuggestionToolbar = new _MenuId("InlineSuggestionToolbar"); _MenuId.InlineEditToolbar = new _MenuId("InlineEditToolbar"); _MenuId.ChatContext = new _MenuId("ChatContext"); _MenuId.ChatCodeBlock = new _MenuId("ChatCodeblock"); _MenuId.ChatCompareBlock = new _MenuId("ChatCompareBlock"); _MenuId.ChatMessageTitle = new _MenuId("ChatMessageTitle"); _MenuId.ChatHistory = new _MenuId("ChatHistory"); _MenuId.ChatWelcomeHistoryContext = new _MenuId("ChatWelcomeHistoryContext"); _MenuId.ChatMessageFooter = new _MenuId("ChatMessageFooter"); _MenuId.ChatExecute = new _MenuId("ChatExecute"); _MenuId.ChatExecuteSecondary = new _MenuId("ChatExecuteSecondary"); _MenuId.ChatInput = new _MenuId("ChatInput"); _MenuId.ChatInputSide = new _MenuId("ChatInputSide"); _MenuId.ChatModePicker = new _MenuId("ChatModePicker"); _MenuId.ChatEditingWidgetToolbar = new _MenuId("ChatEditingWidgetToolbar"); _MenuId.ChatEditingEditorContent = new _MenuId("ChatEditingEditorContent"); _MenuId.ChatEditingEditorHunk = new _MenuId("ChatEditingEditorHunk"); _MenuId.ChatEditingDeletedNotebookCell = new _MenuId("ChatEditingDeletedNotebookCell"); _MenuId.ChatInputAttachmentToolbar = new _MenuId("ChatInputAttachmentToolbar"); _MenuId.ChatEditingWidgetModifiedFilesToolbar = new _MenuId("ChatEditingWidgetModifiedFilesToolbar"); _MenuId.ChatInputResourceAttachmentContext = new _MenuId("ChatInputResourceAttachmentContext"); _MenuId.ChatInputSymbolAttachmentContext = new _MenuId("ChatInputSymbolAttachmentContext"); _MenuId.ChatInlineResourceAnchorContext = new _MenuId("ChatInlineResourceAnchorContext"); _MenuId.ChatInlineSymbolAnchorContext = new _MenuId("ChatInlineSymbolAnchorContext"); _MenuId.ChatMessageCheckpoint = new _MenuId("ChatMessageCheckpoint"); _MenuId.ChatMessageRestoreCheckpoint = new _MenuId("ChatMessageRestoreCheckpoint"); _MenuId.ChatEditingCodeBlockContext = new _MenuId("ChatEditingCodeBlockContext"); _MenuId.ChatTitleBarMenu = new _MenuId("ChatTitleBarMenu"); _MenuId.ChatAttachmentsContext = new _MenuId("ChatAttachmentsContext"); _MenuId.ChatToolOutputResourceToolbar = new _MenuId("ChatToolOutputResourceToolbar"); _MenuId.ChatTextEditorMenu = new _MenuId("ChatTextEditorMenu"); _MenuId.ChatToolOutputResourceContext = new _MenuId("ChatToolOutputResourceContext"); _MenuId.ChatMultiDiffContext = new _MenuId("ChatMultiDiffContext"); _MenuId.ChatSessionsMenu = new _MenuId("ChatSessionsMenu"); _MenuId.ChatConfirmationMenu = new _MenuId("ChatConfirmationMenu"); _MenuId.AccessibleView = new _MenuId("AccessibleView"); _MenuId.MultiDiffEditorFileToolbar = new _MenuId("MultiDiffEditorFileToolbar"); _MenuId.DiffEditorHunkToolbar = new _MenuId("DiffEditorHunkToolbar"); _MenuId.DiffEditorSelectionToolbar = new _MenuId("DiffEditorSelectionToolbar"); let MenuId = _MenuId; const IMenuService = createDecorator("menuService"); const _MenuRegistryChangeEvent = class _MenuRegistryChangeEvent { static for(id) { let value = this._all.get(id); if (!value) { value = new _MenuRegistryChangeEvent(id); this._all.set(id, value); } return value; } static merge(events) { const ids = /* @__PURE__ */ new Set(); for (const item of events) { if (item instanceof _MenuRegistryChangeEvent) { ids.add(item.id); } } return ids; } constructor(id) { this.id = id; this.has = (candidate) => candidate === id; } }; _MenuRegistryChangeEvent._all = /* @__PURE__ */ new Map(); let MenuRegistryChangeEvent = _MenuRegistryChangeEvent; const MenuRegistry = new class { constructor() { this._commands = /* @__PURE__ */ new Map(); this._menuItems = /* @__PURE__ */ new Map(); this._onDidChangeMenu = new MicrotaskEmitter({ merge: MenuRegistryChangeEvent.merge }); this.onDidChangeMenu = this._onDidChangeMenu.event; } addCommand(command) { this._commands.set(command.id, command); this._onDidChangeMenu.fire(MenuRegistryChangeEvent.for(MenuId.CommandPalette)); return markAsSingleton(toDisposable(() => { if (this._commands.delete(command.id)) { this._onDidChangeMenu.fire(MenuRegistryChangeEvent.for(MenuId.CommandPalette)); } })); } getCommand(id) { return this._commands.get(id); } getCommands() { const map = /* @__PURE__ */ new Map(); this._commands.forEach((value, key) => map.set(key, value)); return map; } appendMenuItem(id, item) { let list2 = this._menuItems.get(id); if (!list2) { list2 = new LinkedList(); this._menuItems.set(id, list2); } const rm = list2.push(item); this._onDidChangeMenu.fire(MenuRegistryChangeEvent.for(id)); return markAsSingleton(toDisposable(() => { rm(); this._onDidChangeMenu.fire(MenuRegistryChangeEvent.for(id)); })); } appendMenuItems(items) { const result = new DisposableStore(); for (const { id, item } of items) { result.add(this.appendMenuItem(id, item)); } return result; } getMenuItems(id) { let result; if (this._menuItems.has(id)) { result = [...this._menuItems.get(id)]; } else { result = []; } if (id === MenuId.CommandPalette) { this._appendImplicitItems(result); } return result; } _appendImplicitItems(result) { const set = /* @__PURE__ */ new Set(); for (const item of result) { if (isIMenuItem(item)) { set.add(item.command.id); if (item.alt) { set.add(item.alt.id); } } } this._commands.forEach((command, id) => { if (!set.has(id)) { result.push({ command }); } }); } }(); class SubmenuItemAction extends SubmenuAction { constructor(item, hideActions, actions) { super(`submenuitem.${item.submenu.id}`, typeof item.title === "string" ? item.title : item.title.value, actions, "submenu"); this.item = item; this.hideActions = hideActions; } } let MenuItemAction = MenuItemAction_1 = class MenuItemAction { static label(action, options) { return options?.renderShortTitle && action.shortTitle ? typeof action.shortTitle === "string" ? action.shortTitle : action.shortTitle.value : typeof action.title === "string" ? action.title : action.title.value; } constructor(item, alt, options, hideActions, menuKeybinding, contextKeyService, _commandService) { this.hideActions = hideActions; this.menuKeybinding = menuKeybinding; this._commandService = _commandService; this.id = item.id; this.label = MenuItemAction_1.label(item, options); this.tooltip = (typeof item.tooltip === "string" ? item.tooltip : item.tooltip?.value) ?? ""; this.enabled = !item.precondition || contextKeyService.contextMatchesRules(item.precondition); this.checked = void 0; let icon; if (item.toggled) { const toggled = item.toggled.condition ? item.toggled : { condition: item.toggled }; this.checked = contextKeyService.contextMatchesRules(toggled.condition); if (this.checked && toggled.tooltip) { this.tooltip = typeof toggled.tooltip === "string" ? toggled.tooltip : toggled.tooltip.value; } if (this.checked && ThemeIcon.isThemeIcon(toggled.icon)) { icon = toggled.icon; } if (this.checked && toggled.title) { this.label = typeof toggled.title === "string" ? toggled.title : toggled.title.value; } } if (!icon) { icon = ThemeIcon.isThemeIcon(item.icon) ? item.icon : void 0; } this.item = item; this.alt = alt ? new MenuItemAction_1(alt, void 0, options, hideActions, void 0, contextKeyService, _commandService) : void 0; this._options = options; this.class = icon && ThemeIcon.asClassName(icon); } run(...args) { let runArgs = []; if (this._options?.arg) { runArgs = [...runArgs, this._options.arg]; } if (this._options?.shouldForwardArgs) { runArgs = [...runArgs, ...args]; } return this._commandService.executeCommand(this.id, ...runArgs); } }; MenuItemAction = MenuItemAction_1 = __decorate$35([ __param$2_(5, IContextKeyService), __param$2_(6, ICommandService) ], MenuItemAction); class Action2 { constructor(desc) { this.desc = desc; } } function registerAction2(ctor) { const disposables = []; const action = new ctor(); const { f1, menu, keybinding, ...command } = action.desc; if (CommandsRegistry.getCommand(command.id)) { throw new Error(`Cannot register two commands with the same id: ${command.id}`); } disposables.push(CommandsRegistry.registerCommand({ id: command.id, handler: (accessor, ...args) => action.run(accessor, ...args), metadata: command.metadata ?? { description: action.desc.title } })); if (Array.isArray(menu)) { for (const item of menu) { disposables.push(MenuRegistry.appendMenuItem(item.id, { command: { ...command, precondition: item.precondition === null ? void 0 : command.precondition }, ...item })); } } else if (menu) { disposables.push(MenuRegistry.appendMenuItem(menu.id, { command: { ...command, precondition: menu.precondition === null ? void 0 : command.precondition }, ...menu })); } if (f1) { disposables.push(MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command, when: command.precondition })); disposables.push(MenuRegistry.addCommand(command)); } if (Array.isArray(keybinding)) { for (const item of keybinding) { disposables.push(KeybindingsRegistry.registerKeybindingRule({ ...item, id: command.id, when: command.precondition ? ContextKeyExpr.and(command.precondition, item.when) : item.when })); } } else if (keybinding) { disposables.push(KeybindingsRegistry.registerKeybindingRule({ ...keybinding, id: command.id, when: command.precondition ? ContextKeyExpr.and(command.precondition, keybinding.when) : keybinding.when })); } return { dispose() { dispose(disposables); } }; } const ITelemetryService = createDecorator("telemetryService"); var _a$1, _b, _c; class ResourceMapEntry { constructor(uri, value) { this.uri = uri; this.value = value; } } function isEntries(arg) { return Array.isArray(arg); } const _ResourceMap = class _ResourceMap { constructor(arg, toKey) { this[_a$1] = "ResourceMap"; if (arg instanceof _ResourceMap) { this.map = new Map(arg.map); this.toKey = toKey ?? _ResourceMap.defaultToKey; } else if (isEntries(arg)) { this.map = /* @__PURE__ */ new Map(); this.toKey = toKey ?? _ResourceMap.defaultToKey; for (const [resource, value] of arg) { this.set(resource, value); } } else { this.map = /* @__PURE__ */ new Map(); this.toKey = arg ?? _ResourceMap.defaultToKey; } } set(resource, value) { this.map.set(this.toKey(resource), new ResourceMapEntry(resource, value)); return this; } get(resource) { return this.map.get(this.toKey(resource))?.value; } has(resource) { return this.map.has(this.toKey(resource)); } get size() { return this.map.size; } clear() { this.map.clear(); } delete(resource) { return this.map.delete(this.toKey(resource)); } forEach(clb, thisArg) { if (typeof thisArg !== "undefined") { clb = clb.bind(thisArg); } for (const [_, entry] of this.map) { clb(entry.value, entry.uri, this); } } *values() { for (const entry of this.map.values()) { yield entry.value; } } *keys() { for (const entry of this.map.values()) { yield entry.uri; } } *entries() { for (const entry of this.map.values()) { yield [entry.uri, entry.value]; } } *[(_a$1 = Symbol.toStringTag, Symbol.iterator)]() { for (const [, entry] of this.map) { yield [entry.uri, entry.value]; } } }; _ResourceMap.defaultToKey = (resource) => resource.toString(); let ResourceMap = _ResourceMap; class ResourceSet { constructor(entriesOrKey, toKey) { this[_b] = "ResourceSet"; if (!entriesOrKey || typeof entriesOrKey === "function") { this._map = new ResourceMap(entriesOrKey); } else { this._map = new ResourceMap(toKey); entriesOrKey.forEach(this.add, this); } } get size() { return this._map.size; } add(value) { this._map.set(value, value); return this; } clear() { this._map.clear(); } delete(value) { return this._map.delete(value); } forEach(callbackfn, thisArg) { this._map.forEach((_value, key) => callbackfn.call(thisArg, key, key, this)); } has(value) { return this._map.has(value); } entries() { return this._map.entries(); } keys() { return this._map.keys(); } values() { return this._map.keys(); } [(_b = Symbol.toStringTag, Symbol.iterator)]() { return this.keys(); } } class LinkedMap { constructor() { this[_c] = "LinkedMap"; this._map = /* @__PURE__ */ new Map(); this._head = void 0; this._tail = void 0; this._size = 0; this._state = 0; } clear() { this._map.clear(); this._head = void 0; this._tail = void 0; this._size = 0; this._state++; } isEmpty() { return !this._head && !this._tail; } get size() { return this._size; } get first() { return this._head?.value; } get last() { return this._tail?.value; } has(key) { return this._map.has(key); } get(key, touch = 0) { const item = this._map.get(key); if (!item) { return void 0; } if (touch !== 0) { this.touch(item, touch); } return item.value; } set(key, value, touch = 0) { let item = this._map.get(key); if (item) { item.value = value; if (touch !== 0) { this.touch(item, touch); } } else { item = { key, value, next: void 0, previous: void 0 }; switch (touch) { case 0: this.addItemLast(item); break; case 1: this.addItemFirst(item); break; case 2: this.addItemLast(item); break; default: this.addItemLast(item); break; } this._map.set(key, item); this._size++; } return this; } delete(key) { return !!this.remove(key); } remove(key) { const item = this._map.get(key); if (!item) { return void 0; } this._map.delete(key); this.removeItem(item); this._size--; return item.value; } shift() { if (!this._head && !this._tail) { return void 0; } if (!this._head || !this._tail) { throw new Error("Invalid list"); } const item = this._head; this._map.delete(item.key); this.removeItem(item); this._size--; return item.value; } forEach(callbackfn, thisArg) { const state = this._state; let current = this._head; while (current) { if (thisArg) { callbackfn.bind(thisArg)(current.value, current.key, this); } else { callbackfn(current.value, current.key, this); } if (this._state !== state) { throw new Error(`LinkedMap got modified during iteration.`); } current = current.next; } } keys() { const map = this; const state = this._state; let current = this._head; const iterator = { [Symbol.iterator]() { return iterator; }, next() { if (map._state !== state) { throw new Error(`LinkedMap got modified during iteration.`); } if (current) { const result = { value: current.key, done: false }; current = current.next; return result; } else { return { value: void 0, done: true }; } } }; return iterator; } values() { const map = this; const state = this._state; let current = this._head; const iterator = { [Symbol.iterator]() { return iterator; }, next() { if (map._state !== state) { throw new Error(`LinkedMap got modified during iteration.`); } if (current) { const result = { value: current.value, done: false }; current = current.next; return result; } else { return { value: void 0, done: true }; } } }; return iterator; } entries() { const map = this; const state = this._state; let current = this._head; const iterator = { [Symbol.iterator]() { return iterator; }, next() { if (map._state !== state) { throw new Error(`LinkedMap got modified during iteration.`); } if (current) { const result = { value: [current.key, current.value], done: false }; current = current.next; return result; } else { return { value: void 0, done: true }; } } }; return iterator; } [(_c = Symbol.toStringTag, Symbol.iterator)]() { return this.entries(); } trimOld(newSize) { if (newSize >= this.size) { return; } if (newSize === 0) { this.clear(); return; } let current = this._head; let currentSize = this.size; while (current && currentSize > newSize) { this._map.delete(current.key); current = current.next; currentSize--; } this._head = current; this._size = currentSize; if (current) { current.previous = void 0; } this._state++; } trimNew(newSize) { if (newSize >= this.size) { return; } if (newSize === 0) { this.clear(); return; } let current = this._tail; let currentSize = this.size; while (current && currentSize > newSize) { this._map.delete(current.key); current = current.previous; currentSize--; } this._tail = current; this._size = currentSize; if (current) { current.next = void 0; } this._state++; } addItemFirst(item) { if (!this._head && !this._tail) { this._tail = item; } else if (!this._head) { throw new Error("Invalid list"); } else { item.next = this._head; this._head.previous = item; } this._head = item; this._state++; } addItemLast(item) { if (!this._head && !this._tail) { this._head = item; } else if (!this._tail) { throw new Error("Invalid list"); } else { item.previous = this._tail; this._tail.next = item; } this._tail = item; this._state++; } removeItem(item) { if (item === this._head && item === this._tail) { this._head = void 0; this._tail = void 0; } else if (item === this._head) { if (!item.next) { throw new Error("Invalid list"); } item.next.previous = void 0; this._head = item.next; } else if (item === this._tail) { if (!item.previous) { throw new Error("Invalid list"); } item.previous.next = void 0; this._tail = item.previous; } else { const next = item.next; const previous = item.previous; if (!next || !previous) { throw new Error("Invalid list"); } next.previous = previous; previous.next = next; } item.next = void 0; item.previous = void 0; this._state++; } touch(item, touch) { if (!this._head || !this._tail) { throw new Error("Invalid list"); } if (touch !== 1 && touch !== 2) { return; } if (touch === 1) { if (item === this._head) { return; } const next = item.next; const previous = item.previous; if (item === this._tail) { previous.next = void 0; this._tail = previous; } else { next.previous = previous; previous.next = next; } item.previous = void 0; item.next = this._head; this._head.previous = item; this._head = item; this._state++; } else if (touch === 2) { if (item === this._tail) { return; } const next = item.next; const previous = item.previous; if (item === this._head) { next.previous = void 0; this._head = next; } else { next.previous = previous; previous.next = next; } item.next = void 0; item.previous = this._tail; this._tail.next = item; this._tail = item; this._state++; } } toJSON() { const data = []; this.forEach((value, key) => { data.push([key, value]); }); return data; } fromJSON(data) { this.clear(); for (const [key, value] of data) { this.set(key, value); } } } class Cache extends LinkedMap { constructor(limit, ratio = 1) { super(); this._limit = limit; this._ratio = Math.min(Math.max(0, ratio), 1); } get limit() { return this._limit; } set limit(limit) { this._limit = limit; this.checkTrim(); } get(key, touch = 2) { return super.get(key, touch); } peek(key) { return super.get( key, 0 /* Touch.None */ ); } set(key, value) { super.set( key, value, 2 /* Touch.AsNew */ ); return this; } checkTrim() { if (this.size > this._limit) { this.trim(Math.round(this._limit * this._ratio)); } } } class LRUCache extends Cache { constructor(limit, ratio = 1) { super(limit, ratio); } trim(newSize) { this.trimOld(newSize); } set(key, value) { super.set(key, value); this.checkTrim(); return this; } } class BidirectionalMap { constructor(entries2) { this._m1 = /* @__PURE__ */ new Map(); this._m2 = /* @__PURE__ */ new Map(); if (entries2) { for (const [key, value] of entries2) { this.set(key, value); } } } clear() { this._m1.clear(); this._m2.clear(); } set(key, value) { this._m1.set(key, value); this._m2.set(value, key); } get(key) { return this._m1.get(key); } getKey(value) { return this._m2.get(value); } delete(key) { const value = this._m1.get(key); if (value === void 0) { return false; } this._m1.delete(key); this._m2.delete(value); return true; } keys() { return this._m1.keys(); } values() { return this._m1.values(); } } class SetMap { constructor() { this.map = /* @__PURE__ */ new Map(); } add(key, value) { let values = this.map.get(key); if (!values) { values = /* @__PURE__ */ new Set(); this.map.set(key, values); } values.add(value); } delete(key, value) { const values = this.map.get(key); if (!values) { return; } values.delete(value); if (values.size === 0) { this.map.delete(key); } } forEach(key, fn) { const values = this.map.get(key); if (!values) { return; } values.forEach(fn); } } class NKeyMap { constructor() { this._data = /* @__PURE__ */ new Map(); } /** * Sets a value on the map. Note that unlike a standard `Map`, the first argument is the value. * This is because the spread operator is used for the keys and must be last.. * @param value The value to set. * @param keys The keys for the value. */ set(value, ...keys) { let currentMap = this._data; for (let i2 = 0; i2 < keys.length - 1; i2++) { if (!currentMap.has(keys[i2])) { currentMap.set(keys[i2], /* @__PURE__ */ new Map()); } currentMap = currentMap.get(keys[i2]); } currentMap.set(keys[keys.length - 1], value); } get(...keys) { let currentMap = this._data; for (let i2 = 0; i2 < keys.length - 1; i2++) { if (!currentMap.has(keys[i2])) { return void 0; } currentMap = currentMap.get(keys[i2]); } return currentMap.get(keys[keys.length - 1]); } clear() { this._data.clear(); } /** * Get a textual representation of the map for debugging purposes. */ toString() { const printMap = (map, depth) => { let result = ""; for (const [key, value] of map) { result += `${" ".repeat(depth)}${key}: `; if (value instanceof Map) { result += "\n" + printMap(value, depth + 1); } else { result += `${value} `; } } return result; }; return printMap(this._data, 0); } } function isPathSeparator(code) { return code === 47 || code === 92; } function toSlashes(osPath) { return osPath.replace(/[\\/]/g, posix.sep); } function toPosixPath(osPath) { if (osPath.indexOf("/") === -1) { osPath = toSlashes(osPath); } if (/^[a-zA-Z]:(\/|$)/.test(osPath)) { osPath = "/" + osPath; } return osPath; } function getRoot(path, sep2 = posix.sep) { if (!path) { return ""; } const len = path.length; const firstLetter = path.charCodeAt(0); if (isPathSeparator(firstLetter)) { if (isPathSeparator(path.charCodeAt(1))) { if (!isPathSeparator(path.charCodeAt(2))) { let pos2 = 3; const start = pos2; for (; pos2 < len; pos2++) { if (isPathSeparator(path.charCodeAt(pos2))) { break; } } if (start !== pos2 && !isPathSeparator(path.charCodeAt(pos2 + 1))) { pos2 += 1; for (; pos2 < len; pos2++) { if (isPathSeparator(path.charCodeAt(pos2))) { return path.slice(0, pos2 + 1).replace(/[\\/]/g, sep2); } } } } } return sep2; } else if (isWindowsDriveLetter(firstLetter)) { if (path.charCodeAt(1) === 58) { if (isPathSeparator(path.charCodeAt(2))) { return path.slice(0, 2) + sep2; } else { return path.slice(0, 2); } } } let pos = path.indexOf("://"); if (pos !== -1) { pos += 3; for (; pos < len; pos++) { if (isPathSeparator(path.charCodeAt(pos))) { return path.slice(0, pos + 1); } } } return ""; } function isEqualOrParent(base, parentCandidate, ignoreCase, separator2 = sep) { if (base === parentCandidate) { return true; } if (!base || !parentCandidate) { return false; } if (parentCandidate.length > base.length) { return false; } if (ignoreCase) { const beginsWith = startsWithIgnoreCase(base, parentCandidate); if (!beginsWith) { return false; } if (parentCandidate.length === base.length) { return true; } let sepOffset = parentCandidate.length; if (parentCandidate.charAt(parentCandidate.length - 1) === separator2) { sepOffset--; } return base.charAt(sepOffset) === separator2; } if (parentCandidate.charAt(parentCandidate.length - 1) !== separator2) { parentCandidate += separator2; } return base.indexOf(parentCandidate) === 0; } function isWindowsDriveLetter(char0) { return char0 >= 65 && char0 <= 90 || char0 >= 97 && char0 <= 122; } function hasDriveLetter(path, isWindowsOS = isWindows) { if (isWindowsOS) { return isWindowsDriveLetter(path.charCodeAt(0)) && path.charCodeAt(1) === 58; } return false; } function originalFSPath(uri) { return uriToFsPath(uri, true); } class ExtUri { constructor(_ignorePathCasing) { this._ignorePathCasing = _ignorePathCasing; } compare(uri1, uri2, ignoreFragment = false) { if (uri1 === uri2) { return 0; } return compare(this.getComparisonKey(uri1, ignoreFragment), this.getComparisonKey(uri2, ignoreFragment)); } isEqual(uri1, uri2, ignoreFragment = false) { if (uri1 === uri2) { return true; } if (!uri1 || !uri2) { return false; } return this.getComparisonKey(uri1, ignoreFragment) === this.getComparisonKey(uri2, ignoreFragment); } getComparisonKey(uri, ignoreFragment = false) { return uri.with({ path: this._ignorePathCasing(uri) ? uri.path.toLowerCase() : void 0, fragment: ignoreFragment ? null : void 0 }).toString(); } isEqualOrParent(base, parentCandidate, ignoreFragment = false) { if (base.scheme === parentCandidate.scheme) { if (base.scheme === Schemas.file) { return isEqualOrParent(originalFSPath(base), originalFSPath(parentCandidate), this._ignorePathCasing(base)) && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment); } if (isEqualAuthority(base.authority, parentCandidate.authority)) { return isEqualOrParent(base.path, parentCandidate.path, this._ignorePathCasing(base), "/") && base.query === parentCandidate.query && (ignoreFragment || base.fragment === parentCandidate.fragment); } } return false; } // --- path math joinPath(resource, ...pathFragment) { return URI.joinPath(resource, ...pathFragment); } basenameOrAuthority(resource) { return basename(resource) || resource.authority; } basename(resource) { return posix.basename(resource.path); } extname(resource) { return posix.extname(resource.path); } dirname(resource) { if (resource.path.length === 0) { return resource; } let dirname2; if (resource.scheme === Schemas.file) { dirname2 = URI.file(dirname$1(originalFSPath(resource))).path; } else { dirname2 = posix.dirname(resource.path); if (resource.authority && dirname2.length && dirname2.charCodeAt(0) !== 47) { console.error(`dirname("${resource.toString})) resulted in a relative path`); dirname2 = "/"; } } return resource.with({ path: dirname2 }); } normalizePath(resource) { if (!resource.path.length) { return resource; } let normalizedPath; if (resource.scheme === Schemas.file) { normalizedPath = URI.file(normalize(originalFSPath(resource))).path; } else { normalizedPath = posix.normalize(resource.path); } return resource.with({ path: normalizedPath }); } relativePath(from, to) { if (from.scheme !== to.scheme || !isEqualAuthority(from.authority, to.authority)) { return void 0; } if (from.scheme === Schemas.file) { const relativePath2 = relative(originalFSPath(from), originalFSPath(to)); return isWindows ? toSlashes(relativePath2) : relativePath2; } let fromPath = from.path || "/"; const toPath = to.path || "/"; if (this._ignorePathCasing(from)) { let i2 = 0; for (const len = Math.min(fromPath.length, toPath.length); i2 < len; i2++) { if (fromPath.charCodeAt(i2) !== toPath.charCodeAt(i2)) { if (fromPath.charAt(i2).toLowerCase() !== toPath.charAt(i2).toLowerCase()) { break; } } } fromPath = toPath.substr(0, i2) + fromPath.substr(i2); } return posix.relative(fromPath, toPath); } resolvePath(base, path) { if (base.scheme === Schemas.file) { const newURI = URI.file(resolve$1(originalFSPath(base), path)); return base.with({ authority: newURI.authority, path: newURI.path }); } path = toPosixPath(path); return base.with({ path: posix.resolve(base.path, path) }); } // --- misc isAbsolutePath(resource) { return !!resource.path && resource.path[0] === "/"; } isEqualAuthority(a1, a2) { return a1 === a2 || a1 !== void 0 && a2 !== void 0 && equalsIgnoreCase(a1, a2); } hasTrailingPathSeparator(resource, sep$1 = sep) { if (resource.scheme === Schemas.file) { const fsp = originalFSPath(resource); return fsp.length > getRoot(fsp).length && fsp[fsp.length - 1] === sep$1; } else { const p = resource.path; return p.length > 1 && p.charCodeAt(p.length - 1) === 47 && !/^[a-zA-Z]:(\/$|\\$)/.test(resource.fsPath); } } removeTrailingPathSeparator(resource, sep$1 = sep) { if (hasTrailingPathSeparator(resource, sep$1)) { return resource.with({ path: resource.path.substr(0, resource.path.length - 1) }); } return resource; } addTrailingPathSeparator(resource, sep$1 = sep) { let isRootSep = false; if (resource.scheme === Schemas.file) { const fsp = originalFSPath(resource); isRootSep = fsp !== void 0 && fsp.length === getRoot(fsp).length && fsp[fsp.length - 1] === sep$1; } else { sep$1 = "/"; const p = resource.path; isRootSep = p.length === 1 && p.charCodeAt(p.length - 1) === 47; } if (!isRootSep && !hasTrailingPathSeparator(resource, sep$1)) { return resource.with({ path: resource.path + "/" }); } return resource; } } const extUri = new ExtUri(() => false); const isEqual = extUri.isEqual.bind(extUri); extUri.isEqualOrParent.bind(extUri); extUri.getComparisonKey.bind(extUri); const basenameOrAuthority = extUri.basenameOrAuthority.bind(extUri); const basename = extUri.basename.bind(extUri); const extname = extUri.extname.bind(extUri); const dirname = extUri.dirname.bind(extUri); const joinPath = extUri.joinPath.bind(extUri); const normalizePath = extUri.normalizePath.bind(extUri); const relativePath = extUri.relativePath.bind(extUri); const resolvePath = extUri.resolvePath.bind(extUri); extUri.isAbsolutePath.bind(extUri); const isEqualAuthority = extUri.isEqualAuthority.bind(extUri); const hasTrailingPathSeparator = extUri.hasTrailingPathSeparator.bind(extUri); extUri.removeTrailingPathSeparator.bind(extUri); extUri.addTrailingPathSeparator.bind(extUri); var DataUri; (function(DataUri2) { DataUri2.META_DATA_LABEL = "label"; DataUri2.META_DATA_DESCRIPTION = "description"; DataUri2.META_DATA_SIZE = "size"; DataUri2.META_DATA_MIME = "mime"; function parseMetaData(dataUri) { const metadata = /* @__PURE__ */ new Map(); const meta = dataUri.path.substring(dataUri.path.indexOf(";") + 1, dataUri.path.lastIndexOf(";")); meta.split(";").forEach((property) => { const [key, value] = property.split(":"); if (key && value) { metadata.set(key, value); } }); const mime = dataUri.path.substring(0, dataUri.path.indexOf(";")); if (mime) { metadata.set(DataUri2.META_DATA_MIME, mime); } return metadata; } DataUri2.parseMetaData = parseMetaData; })(DataUri || (DataUri = {})); const ILogService = createDecorator("logService"); const ILoggerService = createDecorator("loggerService"); var LogLevel; (function(LogLevel2) { LogLevel2[LogLevel2["Off"] = 0] = "Off"; LogLevel2[LogLevel2["Trace"] = 1] = "Trace"; LogLevel2[LogLevel2["Debug"] = 2] = "Debug"; LogLevel2[LogLevel2["Info"] = 3] = "Info"; LogLevel2[LogLevel2["Warning"] = 4] = "Warning"; LogLevel2[LogLevel2["Error"] = 5] = "Error"; })(LogLevel || (LogLevel = {})); const DEFAULT_LOG_LEVEL = LogLevel.Info; function canLog(loggerLevel, messageLevel) { return loggerLevel !== LogLevel.Off && loggerLevel <= messageLevel; } class AbstractLogger extends Disposable { constructor() { super(...arguments); this.level = DEFAULT_LOG_LEVEL; this._onDidChangeLogLevel = this._register(new Emitter$1()); } get onDidChangeLogLevel() { return this._onDidChangeLogLevel.event; } setLevel(level) { if (this.level !== level) { this.level = level; this._onDidChangeLogLevel.fire(this.level); } } getLevel() { return this.level; } checkLogLevel(level) { return canLog(this.level, level); } canLog(level) { if (this._store.isDisposed) { return false; } return this.checkLogLevel(level); } } class ConsoleLogger extends AbstractLogger { constructor(logLevel = DEFAULT_LOG_LEVEL, useColors = true) { super(); this.useColors = useColors; this.setLevel(logLevel); } trace(message, ...args) { if (this.canLog(LogLevel.Trace)) { if (this.useColors) { console.log("%cTRACE", "color: #888", message, ...args); } else { console.log(message, ...args); } } } debug(message, ...args) { if (this.canLog(LogLevel.Debug)) { if (this.useColors) { console.log("%cDEBUG", "background: #eee; color: #888", message, ...args); } else { console.log(message, ...args); } } } info(message, ...args) { if (this.canLog(LogLevel.Info)) { if (this.useColors) { console.log("%c INFO", "color: #33f", message, ...args); } else { console.log(message, ...args); } } } warn(message, ...args) { if (this.canLog(LogLevel.Warning)) { if (this.useColors) { console.warn("%c WARN", "color: #993", message, ...args); } else { console.log(message, ...args); } } } error(message, ...args) { if (this.canLog(LogLevel.Error)) { if (this.useColors) { console.error("%c ERR", "color: #f33", message, ...args); } else { console.error(message, ...args); } } } } class MultiplexLogger extends AbstractLogger { constructor(loggers) { super(); this.loggers = loggers; if (loggers.length) { this.setLevel(loggers[0].getLevel()); } } setLevel(level) { for (const logger of this.loggers) { logger.setLevel(level); } super.setLevel(level); } trace(message, ...args) { for (const logger of this.loggers) { logger.trace(message, ...args); } } debug(message, ...args) { for (const logger of this.loggers) { logger.debug(message, ...args); } } info(message, ...args) { for (const logger of this.loggers) { logger.info(message, ...args); } } warn(message, ...args) { for (const logger of this.loggers) { logger.warn(message, ...args); } } error(message, ...args) { for (const logger of this.loggers) { logger.error(message, ...args); } } dispose() { for (const logger of this.loggers) { logger.dispose(); } super.dispose(); } } class AbstractLoggerService extends Disposable { constructor(logLevel, logsHome, loggerResources) { super(); this.logLevel = logLevel; this.logsHome = logsHome; this._loggers = new ResourceMap(); this._onDidChangeLoggers = this._register(new Emitter$1()); this._onDidChangeVisibility = this._register(new Emitter$1()); if (loggerResources) { for (const loggerResource of loggerResources) { this._loggers.set(loggerResource.resource, { logger: void 0, info: loggerResource }); } } } getLoggerEntry(resourceOrId) { if (isString$1(resourceOrId)) { return [...this._loggers.values()].find((logger) => logger.info.id === resourceOrId); } return this._loggers.get(resourceOrId); } createLogger(idOrResource, options) { const resource = this.toResource(idOrResource); const id = isString$1(idOrResource) ? idOrResource : options?.id ?? hash(resource.toString()).toString(16); let logger = this._loggers.get(resource)?.logger; const logLevel = options?.logLevel === "always" ? LogLevel.Trace : options?.logLevel; if (!logger) { logger = this.doCreateLogger(resource, logLevel ?? this.getLogLevel(resource) ?? this.logLevel, { ...options, id }); } const loggerEntry = { logger, info: { resource, id, logLevel, name: options?.name, hidden: options?.hidden, group: options?.group, extensionId: options?.extensionId, when: options?.when } }; this.registerLogger(loggerEntry.info); this._loggers.set(resource, loggerEntry); return logger; } toResource(idOrResource) { return isString$1(idOrResource) ? joinPath(this.logsHome, `${idOrResource}.log`) : idOrResource; } setVisibility(resourceOrId, visibility) { const logger = this.getLoggerEntry(resourceOrId); if (logger && visibility !== !logger.info.hidden) { logger.info.hidden = !visibility; this._loggers.set(logger.info.resource, logger); this._onDidChangeVisibility.fire([logger.info.resource, visibility]); } } getLogLevel(resource) { let logLevel; if (resource) { logLevel = this._loggers.get(resource)?.info.logLevel; } return logLevel ?? this.logLevel; } registerLogger(resource) { const existing = this._loggers.get(resource.resource); if (existing) { if (existing.info.hidden !== resource.hidden) { this.setVisibility(resource.resource, !resource.hidden); } } else { this._loggers.set(resource.resource, { info: resource, logger: void 0 }); this._onDidChangeLoggers.fire({ added: [resource], removed: [] }); } } dispose() { this._loggers.forEach((logger) => logger.logger?.dispose()); this._loggers.clear(); super.dispose(); } } class NullLogger { constructor() { this.onDidChangeLogLevel = new Emitter$1().event; } setLevel(level) { } getLevel() { return LogLevel.Info; } trace(message, ...args) { } debug(message, ...args) { } info(message, ...args) { } warn(message, ...args) { } error(message, ...args) { } dispose() { } } class NullLoggerService extends AbstractLoggerService { constructor() { super(LogLevel.Off, URI.parse("log:///log")); } doCreateLogger(resource, logLevel, options) { return new NullLogger(); } } function LogLevelToString(logLevel) { switch (logLevel) { case LogLevel.Trace: return "trace"; case LogLevel.Debug: return "debug"; case LogLevel.Info: return "info"; case LogLevel.Warning: return "warn"; case LogLevel.Error: return "error"; case LogLevel.Off: return "off"; } } new RawContextKey("logLevel", LogLevelToString(LogLevel.Info)); let Command$1 = class Command { constructor(opts) { this.id = opts.id; this.precondition = opts.precondition; this._kbOpts = opts.kbOpts; this._menuOpts = opts.menuOpts; this.metadata = opts.metadata; } register() { if (Array.isArray(this._menuOpts)) { this._menuOpts.forEach(this._registerMenuItem, this); } else if (this._menuOpts) { this._registerMenuItem(this._menuOpts); } if (this._kbOpts) { const kbOptsArr = Array.isArray(this._kbOpts) ? this._kbOpts : [this._kbOpts]; for (const kbOpts of kbOptsArr) { let kbWhen = kbOpts.kbExpr; if (this.precondition) { if (kbWhen) { kbWhen = ContextKeyExpr.and(kbWhen, this.precondition); } else { kbWhen = this.precondition; } } const desc = { id: this.id, weight: kbOpts.weight, args: kbOpts.args, when: kbWhen, primary: kbOpts.primary, secondary: kbOpts.secondary, win: kbOpts.win, linux: kbOpts.linux, mac: kbOpts.mac }; KeybindingsRegistry.registerKeybindingRule(desc); } } CommandsRegistry.registerCommand({ id: this.id, handler: (accessor, args) => this.runCommand(accessor, args), metadata: this.metadata }); } _registerMenuItem(item) { MenuRegistry.appendMenuItem(item.menuId, { group: item.group, command: { id: this.id, title: item.title, icon: item.icon, precondition: this.precondition }, when: item.when, order: item.order }); } }; class MultiCommand extends Command$1 { constructor() { super(...arguments); this._implementations = []; } /** * A higher priority gets to be looked at first */ addImplementation(priority, name, implementation, when) { this._implementations.push({ priority, name, implementation, when }); this._implementations.sort((a, b) => b.priority - a.priority); return { dispose: () => { for (let i2 = 0; i2 < this._implementations.length; i2++) { if (this._implementations[i2].implementation === implementation) { this._implementations.splice(i2, 1); return; } } } }; } runCommand(accessor, args) { const logService = accessor.get(ILogService); const contextKeyService = accessor.get(IContextKeyService); logService.trace(`Executing Command '${this.id}' which has ${this._implementations.length} bound.`); for (const impl of this._implementations) { if (impl.when) { const context = contextKeyService.getContext(getActiveElement()); const value = impl.when.evaluate(context); if (!value) { continue; } } const result = impl.implementation(accessor, args); if (result) { logService.trace(`Command '${this.id}' was handled by '${impl.name}'.`); if (typeof result === "boolean") { return; } return result; } } logService.trace(`The Command '${this.id}' was not handled by any implementation.`); } } class ProxyCommand extends Command$1 { constructor(command, opts) { super(opts); this.command = command; } runCommand(accessor, args) { return this.command.runCommand(accessor, args); } } class EditorCommand extends Command$1 { /** * Create a command class that is bound to a certain editor contribution. */ static bindToContribution(controllerGetter) { return class EditorControllerCommandImpl extends EditorCommand { constructor(opts) { super(opts); this._callback = opts.handler; } runEditorCommand(accessor, editor2, args) { const controller = controllerGetter(editor2); if (controller) { this._callback(controller, args); } } }; } static runEditorCommand(accessor, args, precondition, runner) { const codeEditorService = accessor.get(ICodeEditorService); const editor2 = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor(); if (!editor2) { return; } return editor2.invokeWithinContext((editorAccessor) => { const kbService = editorAccessor.get(IContextKeyService); if (!kbService.contextMatchesRules(precondition ?? void 0)) { return; } return runner(editorAccessor, editor2, args); }); } runCommand(accessor, args) { return EditorCommand.runEditorCommand(accessor, args, this.precondition, (accessor2, editor2, args2) => this.runEditorCommand(accessor2, editor2, args2)); } } class EditorAction extends EditorCommand { static convertOptions(opts) { let menuOpts; if (Array.isArray(opts.menuOpts)) { menuOpts = opts.menuOpts; } else if (opts.menuOpts) { menuOpts = [opts.menuOpts]; } else { menuOpts = []; } function withDefaults(item) { if (!item.menuId) { item.menuId = MenuId.EditorContext; } if (!item.title) { item.title = typeof opts.label === "string" ? opts.label : opts.label.value; } item.when = ContextKeyExpr.and(opts.precondition, item.when); return item; } if (Array.isArray(opts.contextMenuOpts)) { menuOpts.push(...opts.contextMenuOpts.map(withDefaults)); } else if (opts.contextMenuOpts) { menuOpts.push(withDefaults(opts.contextMenuOpts)); } opts.menuOpts = menuOpts; return opts; } constructor(opts) { super(EditorAction.convertOptions(opts)); if (typeof opts.label === "string") { this.label = opts.label; this.alias = opts.alias ?? opts.label; } else { this.label = opts.label.value; this.alias = opts.alias ?? opts.label.original; } } runEditorCommand(accessor, editor2, args) { this.reportTelemetry(accessor, editor2); return this.run(accessor, editor2, args || {}); } reportTelemetry(accessor, editor2) { accessor.get(ITelemetryService).publicLog2("editorActionInvoked", { name: this.label, id: this.id }); } } class MultiEditorAction extends EditorAction { constructor() { super(...arguments); this._implementations = []; } /** * A higher priority gets to be looked at first */ addImplementation(priority, implementation) { this._implementations.push([priority, implementation]); this._implementations.sort((a, b) => b[0] - a[0]); return { dispose: () => { for (let i2 = 0; i2 < this._implementations.length; i2++) { if (this._implementations[i2][1] === implementation) { this._implementations.splice(i2, 1); return; } } } }; } run(accessor, editor2, args) { for (const impl of this._implementations) { const result = impl[1](accessor, editor2, args); if (result) { if (typeof result === "boolean") { return; } return result; } } } } class EditorAction2 extends Action2 { run(accessor, ...args) { const codeEditorService = accessor.get(ICodeEditorService); const editor2 = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor(); if (!editor2) { return; } return editor2.invokeWithinContext((editorAccessor) => { const kbService = editorAccessor.get(IContextKeyService); const logService = editorAccessor.get(ILogService); const enabled = kbService.contextMatchesRules(this.desc.precondition ?? void 0); if (!enabled) { logService.debug(`[EditorAction2] NOT running command because its precondition is FALSE`, this.desc.id, this.desc.precondition?.serialize()); return; } return this.runEditorCommand(editorAccessor, editor2, ...args); }); } } function registerModelAndPositionCommand(id, handler) { CommandsRegistry.registerCommand(id, function(accessor, ...args) { const instaService = accessor.get(IInstantiationService); const [resource, position] = args; assertType(URI.isUri(resource)); assertType(Position$1.isIPosition(position)); const model = accessor.get(IModelService).getModel(resource); if (model) { const editorPosition = Position$1.lift(position); return instaService.invokeFunction(handler, model, editorPosition, ...args.slice(2)); } return accessor.get(ITextModelService).createModelReference(resource).then((reference) => { return new Promise((resolve2, reject) => { try { const result = instaService.invokeFunction(handler, reference.object.textEditorModel, Position$1.lift(position), args.slice(2)); resolve2(result); } catch (err) { reject(err); } }).finally(() => { reference.dispose(); }); }); }); } function registerEditorCommand(editorCommand) { EditorContributionRegistry.INSTANCE.registerEditorCommand(editorCommand); return editorCommand; } function registerEditorAction(ctor) { const action = new ctor(); EditorContributionRegistry.INSTANCE.registerEditorAction(action); return action; } function registerMultiEditorAction(action) { EditorContributionRegistry.INSTANCE.registerEditorAction(action); return action; } function registerInstantiatedEditorAction(editorAction) { EditorContributionRegistry.INSTANCE.registerEditorAction(editorAction); } function registerEditorContribution(id, ctor, instantiation) { EditorContributionRegistry.INSTANCE.registerEditorContribution(id, ctor, instantiation); } var EditorExtensionsRegistry; (function(EditorExtensionsRegistry2) { function getEditorCommand(commandId) { return EditorContributionRegistry.INSTANCE.getEditorCommand(commandId); } EditorExtensionsRegistry2.getEditorCommand = getEditorCommand; function getEditorActions() { return EditorContributionRegistry.INSTANCE.getEditorActions(); } EditorExtensionsRegistry2.getEditorActions = getEditorActions; function getEditorContributions() { return EditorContributionRegistry.INSTANCE.getEditorContributions(); } EditorExtensionsRegistry2.getEditorContributions = getEditorContributions; function getSomeEditorContributions(ids) { return EditorContributionRegistry.INSTANCE.getEditorContributions().filter((c) => ids.indexOf(c.id) >= 0); } EditorExtensionsRegistry2.getSomeEditorContributions = getSomeEditorContributions; function getDiffEditorContributions() { return EditorContributionRegistry.INSTANCE.getDiffEditorContributions(); } EditorExtensionsRegistry2.getDiffEditorContributions = getDiffEditorContributions; })(EditorExtensionsRegistry || (EditorExtensionsRegistry = {})); const Extensions$8 = { EditorCommonContributions: "editor.contributions" }; const _EditorContributionRegistry = class _EditorContributionRegistry { constructor() { this.editorContributions = []; this.diffEditorContributions = []; this.editorActions = []; this.editorCommands = /* @__PURE__ */ Object.create(null); } registerEditorContribution(id, ctor, instantiation) { this.editorContributions.push({ id, ctor, instantiation }); } getEditorContributions() { return this.editorContributions.slice(0); } getDiffEditorContributions() { return this.diffEditorContributions.slice(0); } registerEditorAction(action) { action.register(); this.editorActions.push(action); } getEditorActions() { return this.editorActions; } registerEditorCommand(editorCommand) { editorCommand.register(); this.editorCommands[editorCommand.id] = editorCommand; } getEditorCommand(commandId) { return this.editorCommands[commandId] || null; } }; _EditorContributionRegistry.INSTANCE = new _EditorContributionRegistry(); let EditorContributionRegistry = _EditorContributionRegistry; Registry.add(Extensions$8.EditorCommonContributions, EditorContributionRegistry.INSTANCE); function registerCommand$3(command) { command.register(); return command; } const UndoCommand = registerCommand$3(new MultiCommand({ id: "undo", precondition: void 0, kbOpts: { weight: 0, primary: 2048 | 56 /* KeyCode.KeyZ */ }, menuOpts: [{ menuId: MenuId.MenubarEditMenu, group: "1_do", title: localize(64, "&&Undo"), order: 1 }, { menuId: MenuId.CommandPalette, group: "", title: localize(65, "Undo"), order: 1 }, { menuId: MenuId.SimpleEditorContext, group: "1_do", title: localize(66, "Undo"), order: 1 }] })); registerCommand$3(new ProxyCommand(UndoCommand, { id: "default:undo", precondition: void 0 })); const RedoCommand = registerCommand$3(new MultiCommand({ id: "redo", precondition: void 0, kbOpts: { weight: 0, primary: 2048 | 55, secondary: [ 2048 | 1024 | 56 /* KeyCode.KeyZ */ ], mac: { primary: 2048 | 1024 | 56 /* KeyCode.KeyZ */ } }, menuOpts: [{ menuId: MenuId.MenubarEditMenu, group: "1_do", title: localize(67, "&&Redo"), order: 2 }, { menuId: MenuId.CommandPalette, group: "", title: localize(68, "Redo"), order: 1 }, { menuId: MenuId.SimpleEditorContext, group: "1_do", title: localize(69, "Redo"), order: 2 }] })); registerCommand$3(new ProxyCommand(RedoCommand, { id: "default:redo", precondition: void 0 })); const SelectAllCommand = registerCommand$3(new MultiCommand({ id: "editor.action.selectAll", precondition: void 0, kbOpts: { weight: 0, kbExpr: null, primary: 2048 | 31 /* KeyCode.KeyA */ }, menuOpts: [{ menuId: MenuId.MenubarSelectionMenu, group: "1_basic", title: localize(70, "&&Select All"), order: 1 }, { menuId: MenuId.CommandPalette, group: "", title: localize(71, "Select All"), order: 1 }, { menuId: MenuId.SimpleEditorContext, group: "9_select", title: localize(72, "Select All"), order: 1 }] })); let Range$2 = class Range2 { constructor(startLineNumber, startColumn, endLineNumber, endColumn) { if (startLineNumber > endLineNumber || startLineNumber === endLineNumber && startColumn > endColumn) { this.startLineNumber = endLineNumber; this.startColumn = endColumn; this.endLineNumber = startLineNumber; this.endColumn = startColumn; } else { this.startLineNumber = startLineNumber; this.startColumn = startColumn; this.endLineNumber = endLineNumber; this.endColumn = endColumn; } } /** * Test if this range is empty. */ isEmpty() { return Range2.isEmpty(this); } /** * Test if `range` is empty. */ static isEmpty(range2) { return range2.startLineNumber === range2.endLineNumber && range2.startColumn === range2.endColumn; } /** * Test if position is in this range. If the position is at the edges, will return true. */ containsPosition(position) { return Range2.containsPosition(this, position); } /** * Test if `position` is in `range`. If the position is at the edges, will return true. */ static containsPosition(range2, position) { if (position.lineNumber < range2.startLineNumber || position.lineNumber > range2.endLineNumber) { return false; } if (position.lineNumber === range2.startLineNumber && position.column < range2.startColumn) { return false; } if (position.lineNumber === range2.endLineNumber && position.column > range2.endColumn) { return false; } return true; } /** * Test if `position` is in `range`. If the position is at the edges, will return false. * @internal */ static strictContainsPosition(range2, position) { if (position.lineNumber < range2.startLineNumber || position.lineNumber > range2.endLineNumber) { return false; } if (position.lineNumber === range2.startLineNumber && position.column <= range2.startColumn) { return false; } if (position.lineNumber === range2.endLineNumber && position.column >= range2.endColumn) { return false; } return true; } /** * Test if range is in this range. If the range is equal to this range, will return true. */ containsRange(range2) { return Range2.containsRange(this, range2); } /** * Test if `otherRange` is in `range`. If the ranges are equal, will return true. */ static containsRange(range2, otherRange) { if (otherRange.startLineNumber < range2.startLineNumber || otherRange.endLineNumber < range2.startLineNumber) { return false; } if (otherRange.startLineNumber > range2.endLineNumber || otherRange.endLineNumber > range2.endLineNumber) { return false; } if (otherRange.startLineNumber === range2.startLineNumber && otherRange.startColumn < range2.startColumn) { return false; } if (otherRange.endLineNumber === range2.endLineNumber && otherRange.endColumn > range2.endColumn) { return false; } return true; } /** * Test if `range` is strictly in this range. `range` must start after and end before this range for the result to be true. */ strictContainsRange(range2) { return Range2.strictContainsRange(this, range2); } /** * Test if `otherRange` is strictly in `range` (must start after, and end before). If the ranges are equal, will return false. */ static strictContainsRange(range2, otherRange) { if (otherRange.startLineNumber < range2.startLineNumber || otherRange.endLineNumber < range2.startLineNumber) { return false; } if (otherRange.startLineNumber > range2.endLineNumber || otherRange.endLineNumber > range2.endLineNumber) { return false; } if (otherRange.startLineNumber === range2.startLineNumber && otherRange.startColumn <= range2.startColumn) { return false; } if (otherRange.endLineNumber === range2.endLineNumber && otherRange.endColumn >= range2.endColumn) { return false; } return true; } /** * A reunion of the two ranges. * The smallest position will be used as the start point, and the largest one as the end point. */ plusRange(range2) { return Range2.plusRange(this, range2); } /** * A reunion of the two ranges. * The smallest position will be used as the start point, and the largest one as the end point. */ static plusRange(a, b) { let startLineNumber; let startColumn; let endLineNumber; let endColumn; if (b.startLineNumber < a.startLineNumber) { startLineNumber = b.startLineNumber; startColumn = b.startColumn; } else if (b.startLineNumber === a.startLineNumber) { startLineNumber = b.startLineNumber; startColumn = Math.min(b.startColumn, a.startColumn); } else { startLineNumber = a.startLineNumber; startColumn = a.startColumn; } if (b.endLineNumber > a.endLineNumber) { endLineNumber = b.endLineNumber; endColumn = b.endColumn; } else if (b.endLineNumber === a.endLineNumber) { endLineNumber = b.endLineNumber; endColumn = Math.max(b.endColumn, a.endColumn); } else { endLineNumber = a.endLineNumber; endColumn = a.endColumn; } return new Range2(startLineNumber, startColumn, endLineNumber, endColumn); } /** * A intersection of the two ranges. */ intersectRanges(range2) { return Range2.intersectRanges(this, range2); } /** * A intersection of the two ranges. */ static intersectRanges(a, b) { let resultStartLineNumber = a.startLineNumber; let resultStartColumn = a.startColumn; let resultEndLineNumber = a.endLineNumber; let resultEndColumn = a.endColumn; const otherStartLineNumber = b.startLineNumber; const otherStartColumn = b.startColumn; const otherEndLineNumber = b.endLineNumber; const otherEndColumn = b.endColumn; if (resultStartLineNumber < otherStartLineNumber) { resultStartLineNumber = otherStartLineNumber; resultStartColumn = otherStartColumn; } else if (resultStartLineNumber === otherStartLineNumber) { resultStartColumn = Math.max(resultStartColumn, otherStartColumn); } if (resultEndLineNumber > otherEndLineNumber) { resultEndLineNumber = otherEndLineNumber; resultEndColumn = otherEndColumn; } else if (resultEndLineNumber === otherEndLineNumber) { resultEndColumn = Math.min(resultEndColumn, otherEndColumn); } if (resultStartLineNumber > resultEndLineNumber) { return null; } if (resultStartLineNumber === resultEndLineNumber && resultStartColumn > resultEndColumn) { return null; } return new Range2(resultStartLineNumber, resultStartColumn, resultEndLineNumber, resultEndColumn); } /** * Test if this range equals other. */ equalsRange(other) { return Range2.equalsRange(this, other); } /** * Test if range `a` equals `b`. */ static equalsRange(a, b) { if (!a && !b) { return true; } return !!a && !!b && a.startLineNumber === b.startLineNumber && a.startColumn === b.startColumn && a.endLineNumber === b.endLineNumber && a.endColumn === b.endColumn; } /** * Return the end position (which will be after or equal to the start position) */ getEndPosition() { return Range2.getEndPosition(this); } /** * Return the end position (which will be after or equal to the start position) */ static getEndPosition(range2) { return new Position$1(range2.endLineNumber, range2.endColumn); } /** * Return the start position (which will be before or equal to the end position) */ getStartPosition() { return Range2.getStartPosition(this); } /** * Return the start position (which will be before or equal to the end position) */ static getStartPosition(range2) { return new Position$1(range2.startLineNumber, range2.startColumn); } /** * Transform to a user presentable string representation. */ toString() { return "[" + this.startLineNumber + "," + this.startColumn + " -> " + this.endLineNumber + "," + this.endColumn + "]"; } /** * Create a new range using this range's start position, and using endLineNumber and endColumn as the end position. */ setEndPosition(endLineNumber, endColumn) { return new Range2(this.startLineNumber, this.startColumn, endLineNumber, endColumn); } /** * Create a new range using this range's end position, and using startLineNumber and startColumn as the start position. */ setStartPosition(startLineNumber, startColumn) { return new Range2(startLineNumber, startColumn, this.endLineNumber, this.endColumn); } /** * Create a new empty range using this range's start position. */ collapseToStart() { return Range2.collapseToStart(this); } /** * Create a new empty range using this range's start position. */ static collapseToStart(range2) { return new Range2(range2.startLineNumber, range2.startColumn, range2.startLineNumber, range2.startColumn); } /** * Create a new empty range using this range's end position. */ collapseToEnd() { return Range2.collapseToEnd(this); } /** * Create a new empty range using this range's end position. */ static collapseToEnd(range2) { return new Range2(range2.endLineNumber, range2.endColumn, range2.endLineNumber, range2.endColumn); } /** * Moves the range by the given amount of lines. */ delta(lineCount) { return new Range2(this.startLineNumber + lineCount, this.startColumn, this.endLineNumber + lineCount, this.endColumn); } isSingleLine() { return this.startLineNumber === this.endLineNumber; } // --- static fromPositions(start, end = start) { return new Range2(start.lineNumber, start.column, end.lineNumber, end.column); } static lift(range2) { if (!range2) { return null; } return new Range2(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn); } /** * Test if `obj` is an `IRange`. */ static isIRange(obj) { return obj && typeof obj.startLineNumber === "number" && typeof obj.startColumn === "number" && typeof obj.endLineNumber === "number" && typeof obj.endColumn === "number"; } /** * Test if the two ranges are touching in any way. */ static areIntersectingOrTouching(a, b) { if (a.endLineNumber < b.startLineNumber || a.endLineNumber === b.startLineNumber && a.endColumn < b.startColumn) { return false; } if (b.endLineNumber < a.startLineNumber || b.endLineNumber === a.startLineNumber && b.endColumn < a.startColumn) { return false; } return true; } /** * Test if the two ranges are intersecting. If the ranges are touching it returns true. */ static areIntersecting(a, b) { if (a.endLineNumber < b.startLineNumber || a.endLineNumber === b.startLineNumber && a.endColumn <= b.startColumn) { return false; } if (b.endLineNumber < a.startLineNumber || b.endLineNumber === a.startLineNumber && b.endColumn <= a.startColumn) { return false; } return true; } /** * Test if the two ranges are intersecting, but not touching at all. */ static areOnlyIntersecting(a, b) { if (a.endLineNumber < b.startLineNumber - 1 || a.endLineNumber === b.startLineNumber && a.endColumn < b.startColumn - 1) { return false; } if (b.endLineNumber < a.startLineNumber - 1 || b.endLineNumber === a.startLineNumber && b.endColumn < a.startColumn - 1) { return false; } return true; } /** * A function that compares ranges, useful for sorting ranges * It will first compare ranges on the startPosition and then on the endPosition */ static compareRangesUsingStarts(a, b) { if (a && b) { const aStartLineNumber = a.startLineNumber | 0; const bStartLineNumber = b.startLineNumber | 0; if (aStartLineNumber === bStartLineNumber) { const aStartColumn = a.startColumn | 0; const bStartColumn = b.startColumn | 0; if (aStartColumn === bStartColumn) { const aEndLineNumber = a.endLineNumber | 0; const bEndLineNumber = b.endLineNumber | 0; if (aEndLineNumber === bEndLineNumber) { const aEndColumn = a.endColumn | 0; const bEndColumn = b.endColumn | 0; return aEndColumn - bEndColumn; } return aEndLineNumber - bEndLineNumber; } return aStartColumn - bStartColumn; } return aStartLineNumber - bStartLineNumber; } const aExists = a ? 1 : 0; const bExists = b ? 1 : 0; return aExists - bExists; } /** * A function that compares ranges, useful for sorting ranges * It will first compare ranges on the endPosition and then on the startPosition */ static compareRangesUsingEnds(a, b) { if (a.endLineNumber === b.endLineNumber) { if (a.endColumn === b.endColumn) { if (a.startLineNumber === b.startLineNumber) { return a.startColumn - b.startColumn; } return a.startLineNumber - b.startLineNumber; } return a.endColumn - b.endColumn; } return a.endLineNumber - b.endLineNumber; } /** * Test if the range spans multiple lines. */ static spansMultipleLines(range2) { return range2.endLineNumber > range2.startLineNumber; } toJSON() { return this; } }; let Selection$1 = class Selection2 extends Range$2 { constructor(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn) { super(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn); this.selectionStartLineNumber = selectionStartLineNumber; this.selectionStartColumn = selectionStartColumn; this.positionLineNumber = positionLineNumber; this.positionColumn = positionColumn; } /** * Transform to a human-readable representation. */ toString() { return "[" + this.selectionStartLineNumber + "," + this.selectionStartColumn + " -> " + this.positionLineNumber + "," + this.positionColumn + "]"; } /** * Test if equals other selection. */ equalsSelection(other) { return Selection2.selectionsEqual(this, other); } /** * Test if the two selections are equal. */ static selectionsEqual(a, b) { return a.selectionStartLineNumber === b.selectionStartLineNumber && a.selectionStartColumn === b.selectionStartColumn && a.positionLineNumber === b.positionLineNumber && a.positionColumn === b.positionColumn; } /** * Get directions (LTR or RTL). */ getDirection() { if (this.selectionStartLineNumber === this.startLineNumber && this.selectionStartColumn === this.startColumn) { return 0; } return 1; } /** * Create a new selection with a different `positionLineNumber` and `positionColumn`. */ setEndPosition(endLineNumber, endColumn) { if (this.getDirection() === 0) { return new Selection2(this.startLineNumber, this.startColumn, endLineNumber, endColumn); } return new Selection2(endLineNumber, endColumn, this.startLineNumber, this.startColumn); } /** * Get the position at `positionLineNumber` and `positionColumn`. */ getPosition() { return new Position$1(this.positionLineNumber, this.positionColumn); } /** * Get the position at the start of the selection. */ getSelectionStart() { return new Position$1(this.selectionStartLineNumber, this.selectionStartColumn); } /** * Create a new selection with a different `selectionStartLineNumber` and `selectionStartColumn`. */ setStartPosition(startLineNumber, startColumn) { if (this.getDirection() === 0) { return new Selection2(startLineNumber, startColumn, this.endLineNumber, this.endColumn); } return new Selection2(this.endLineNumber, this.endColumn, startLineNumber, startColumn); } // ---- /** * Create a `Selection` from one or two positions */ static fromPositions(start, end = start) { return new Selection2(start.lineNumber, start.column, end.lineNumber, end.column); } /** * Creates a `Selection` from a range, given a direction. */ static fromRange(range2, direction) { if (direction === 0) { return new Selection2(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn); } else { return new Selection2(range2.endLineNumber, range2.endColumn, range2.startLineNumber, range2.startColumn); } } /** * Create a `Selection` from an `ISelection`. */ static liftSelection(sel) { return new Selection2(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn); } /** * `a` equals `b`. */ static selectionsArrEqual(a, b) { if (a && !b || !a && b) { return false; } if (!a && !b) { return true; } if (a.length !== b.length) { return false; } for (let i2 = 0, len = a.length; i2 < len; i2++) { if (!this.selectionsEqual(a[i2], b[i2])) { return false; } } return true; } /** * Test if `obj` is an `ISelection`. */ static isISelection(obj) { return obj && typeof obj.selectionStartLineNumber === "number" && typeof obj.selectionStartColumn === "number" && typeof obj.positionLineNumber === "number" && typeof obj.positionColumn === "number"; } /** * Create with a direction. */ static createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, direction) { if (direction === 0) { return new Selection2(startLineNumber, startColumn, endLineNumber, endColumn); } return new Selection2(endLineNumber, endColumn, startLineNumber, startColumn); } }; function createScopedLineTokens(context, offset) { const tokenCount = context.getCount(); const tokenIndex = context.findTokenIndexAtOffset(offset); const desiredLanguageId = context.getLanguageId(tokenIndex); let lastTokenIndex = tokenIndex; while (lastTokenIndex + 1 < tokenCount && context.getLanguageId(lastTokenIndex + 1) === desiredLanguageId) { lastTokenIndex++; } let firstTokenIndex = tokenIndex; while (firstTokenIndex > 0 && context.getLanguageId(firstTokenIndex - 1) === desiredLanguageId) { firstTokenIndex--; } return new ScopedLineTokens(context, desiredLanguageId, firstTokenIndex, lastTokenIndex + 1, context.getStartOffset(firstTokenIndex), context.getEndOffset(lastTokenIndex)); } class ScopedLineTokens { constructor(actual, languageId, firstTokenIndex, lastTokenIndex, firstCharOffset, lastCharOffset) { this._scopedLineTokensBrand = void 0; this._actual = actual; this.languageId = languageId; this._firstTokenIndex = firstTokenIndex; this._lastTokenIndex = lastTokenIndex; this.firstCharOffset = firstCharOffset; this._lastCharOffset = lastCharOffset; this.languageIdCodec = actual.languageIdCodec; } getLineContent() { const actualLineContent = this._actual.getLineContent(); return actualLineContent.substring(this.firstCharOffset, this._lastCharOffset); } getLineLength() { return this._lastCharOffset - this.firstCharOffset; } getActualLineContentBefore(offset) { const actualLineContent = this._actual.getLineContent(); return actualLineContent.substring(0, this.firstCharOffset + offset); } getTokenCount() { return this._lastTokenIndex - this._firstTokenIndex; } findTokenIndexAtOffset(offset) { return this._actual.findTokenIndexAtOffset(offset + this.firstCharOffset) - this._firstTokenIndex; } getStandardTokenType(tokenIndex) { return this._actual.getStandardTokenType(tokenIndex + this._firstTokenIndex); } toIViewLineTokens() { return this._actual.sliceAndInflate(this.firstCharOffset, this._lastCharOffset, 0); } } function ignoreBracketsInToken(standardTokenType) { return (standardTokenType & 3) !== 0; } class CursorColumns { static _nextVisibleColumn(codePoint, visibleColumn, tabSize) { if (codePoint === 9) { return CursorColumns.nextRenderTabStop(visibleColumn, tabSize); } if (isFullWidthCharacter(codePoint) || isEmojiImprecise(codePoint)) { return visibleColumn + 2; } return visibleColumn + 1; } /** * Returns a visible column from a column. * @see {@link CursorColumns} */ static visibleColumnFromColumn(lineContent, column, tabSize) { const textLen = Math.min(column - 1, lineContent.length); const text2 = lineContent.substring(0, textLen); const iterator = new GraphemeIterator(text2); let result = 0; while (!iterator.eol()) { const codePoint = getNextCodePoint(text2, textLen, iterator.offset); iterator.nextGraphemeLength(); result = this._nextVisibleColumn(codePoint, result, tabSize); } return result; } /** * Returns a column from a visible column. * @see {@link CursorColumns} */ static columnFromVisibleColumn(lineContent, visibleColumn, tabSize) { if (visibleColumn <= 0) { return 1; } const lineContentLength = lineContent.length; const iterator = new GraphemeIterator(lineContent); let beforeVisibleColumn = 0; let beforeColumn = 1; while (!iterator.eol()) { const codePoint = getNextCodePoint(lineContent, lineContentLength, iterator.offset); iterator.nextGraphemeLength(); const afterVisibleColumn = this._nextVisibleColumn(codePoint, beforeVisibleColumn, tabSize); const afterColumn = iterator.offset + 1; if (afterVisibleColumn >= visibleColumn) { const beforeDelta = visibleColumn - beforeVisibleColumn; const afterDelta = afterVisibleColumn - visibleColumn; if (afterDelta < beforeDelta) { return afterColumn; } else { return beforeColumn; } } beforeVisibleColumn = afterVisibleColumn; beforeColumn = afterColumn; } return lineContentLength + 1; } /** * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns) * @see {@link CursorColumns} */ static nextRenderTabStop(visibleColumn, tabSize) { return visibleColumn + tabSize - visibleColumn % tabSize; } /** * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns) * @see {@link CursorColumns} */ static nextIndentTabStop(visibleColumn, indentSize) { return CursorColumns.nextRenderTabStop(visibleColumn, indentSize); } /** * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns) * @see {@link CursorColumns} */ static prevRenderTabStop(column, tabSize) { return Math.max(0, column - 1 - (column - 1) % tabSize); } /** * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns) * @see {@link CursorColumns} */ static prevIndentTabStop(column, indentSize) { return CursorColumns.prevRenderTabStop(column, indentSize); } } function _normalizeIndentationFromWhitespace(str, indentSize, insertSpaces) { let spacesCnt = 0; for (let i2 = 0; i2 < str.length; i2++) { if (str.charAt(i2) === " ") { spacesCnt = CursorColumns.nextIndentTabStop(spacesCnt, indentSize); } else { spacesCnt++; } } let result = ""; if (!insertSpaces) { const tabsCnt = Math.floor(spacesCnt / indentSize); spacesCnt = spacesCnt % indentSize; for (let i2 = 0; i2 < tabsCnt; i2++) { result += " "; } } for (let i2 = 0; i2 < spacesCnt; i2++) { result += " "; } return result; } function normalizeIndentation(str, indentSize, insertSpaces) { let firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(str); if (firstNonWhitespaceIndex$1 === -1) { firstNonWhitespaceIndex$1 = str.length; } return _normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex$1), indentSize, insertSpaces) + str.substring(firstNonWhitespaceIndex$1); } class InputModeImpl { constructor() { this._inputMode = "insert"; this._onDidChangeInputMode = new Emitter$1(); this.onDidChangeInputMode = this._onDidChangeInputMode.event; } getInputMode() { return this._inputMode; } } const InputMode = new InputModeImpl(); const autoCloseAlways = () => true; const autoCloseNever = () => false; const autoCloseBeforeWhitespace = (chr) => chr === " " || chr === " "; class CursorConfiguration { static shouldRecreate(e) { return e.hasChanged( 165 /* EditorOption.layoutInfo */ ) || e.hasChanged( 148 /* EditorOption.wordSeparators */ ) || e.hasChanged( 45 /* EditorOption.emptySelectionClipboard */ ) || e.hasChanged( 85 /* EditorOption.multiCursorMergeOverlapping */ ) || e.hasChanged( 88 /* EditorOption.multiCursorPaste */ ) || e.hasChanged( 89 /* EditorOption.multiCursorLimit */ ) || e.hasChanged( 10 /* EditorOption.autoClosingBrackets */ ) || e.hasChanged( 11 /* EditorOption.autoClosingComments */ ) || e.hasChanged( 15 /* EditorOption.autoClosingQuotes */ ) || e.hasChanged( 13 /* EditorOption.autoClosingDelete */ ) || e.hasChanged( 14 /* EditorOption.autoClosingOvertype */ ) || e.hasChanged( 20 /* EditorOption.autoSurround */ ) || e.hasChanged( 145 /* EditorOption.useTabStops */ ) || e.hasChanged( 141 /* EditorOption.trimWhitespaceOnDelete */ ) || e.hasChanged( 59 /* EditorOption.fontInfo */ ) || e.hasChanged( 104 /* EditorOption.readOnly */ ) || e.hasChanged( 147 /* EditorOption.wordSegmenterLocales */ ) || e.hasChanged( 93 /* EditorOption.overtypeOnPaste */ ); } constructor(languageId, modelOptions, configuration, languageConfigurationService) { this.languageConfigurationService = languageConfigurationService; this._cursorMoveConfigurationBrand = void 0; this._languageId = languageId; const options = configuration.options; const layoutInfo = options.get( 165 /* EditorOption.layoutInfo */ ); const fontInfo = options.get( 59 /* EditorOption.fontInfo */ ); this.readOnly = options.get( 104 /* EditorOption.readOnly */ ); this.tabSize = modelOptions.tabSize; this.indentSize = modelOptions.indentSize; this.insertSpaces = modelOptions.insertSpaces; this.stickyTabStops = options.get( 132 /* EditorOption.stickyTabStops */ ); this.lineHeight = fontInfo.lineHeight; this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth; this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2); this.useTabStops = options.get( 145 /* EditorOption.useTabStops */ ); this.trimWhitespaceOnDelete = options.get( 141 /* EditorOption.trimWhitespaceOnDelete */ ); this.wordSeparators = options.get( 148 /* EditorOption.wordSeparators */ ); this.emptySelectionClipboard = options.get( 45 /* EditorOption.emptySelectionClipboard */ ); this.copyWithSyntaxHighlighting = options.get( 31 /* EditorOption.copyWithSyntaxHighlighting */ ); this.multiCursorMergeOverlapping = options.get( 85 /* EditorOption.multiCursorMergeOverlapping */ ); this.multiCursorPaste = options.get( 88 /* EditorOption.multiCursorPaste */ ); this.multiCursorLimit = options.get( 89 /* EditorOption.multiCursorLimit */ ); this.autoClosingBrackets = options.get( 10 /* EditorOption.autoClosingBrackets */ ); this.autoClosingComments = options.get( 11 /* EditorOption.autoClosingComments */ ); this.autoClosingQuotes = options.get( 15 /* EditorOption.autoClosingQuotes */ ); this.autoClosingDelete = options.get( 13 /* EditorOption.autoClosingDelete */ ); this.autoClosingOvertype = options.get( 14 /* EditorOption.autoClosingOvertype */ ); this.autoSurround = options.get( 20 /* EditorOption.autoSurround */ ); this.autoIndent = options.get( 16 /* EditorOption.autoIndent */ ); this.wordSegmenterLocales = options.get( 147 /* EditorOption.wordSegmenterLocales */ ); this.overtypeOnPaste = options.get( 93 /* EditorOption.overtypeOnPaste */ ); this.surroundingPairs = {}; this._electricChars = null; this.shouldAutoCloseBefore = { quote: this._getShouldAutoClose(languageId, this.autoClosingQuotes, true), comment: this._getShouldAutoClose(languageId, this.autoClosingComments, false), bracket: this._getShouldAutoClose(languageId, this.autoClosingBrackets, false) }; this.autoClosingPairs = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoClosingPairs(); const surroundingPairs = this.languageConfigurationService.getLanguageConfiguration(languageId).getSurroundingPairs(); if (surroundingPairs) { for (const pair of surroundingPairs) { this.surroundingPairs[pair.open] = pair.close; } } const commentsConfiguration = this.languageConfigurationService.getLanguageConfiguration(languageId).comments; this.blockCommentStartToken = commentsConfiguration?.blockCommentStartToken ?? null; } get electricChars() { if (!this._electricChars) { this._electricChars = {}; const electricChars = this.languageConfigurationService.getLanguageConfiguration(this._languageId).electricCharacter?.getElectricCharacters(); if (electricChars) { for (const char of electricChars) { this._electricChars[char] = true; } } } return this._electricChars; } get inputMode() { return InputMode.getInputMode(); } /** * Should return opening bracket type to match indentation with */ onElectricCharacter(character, context, column) { const scopedLineTokens = createScopedLineTokens(context, column - 1); const electricCharacterSupport = this.languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId).electricCharacter; if (!electricCharacterSupport) { return null; } return electricCharacterSupport.onElectricCharacter(character, scopedLineTokens, column - scopedLineTokens.firstCharOffset); } normalizeIndentation(str) { return normalizeIndentation(str, this.indentSize, this.insertSpaces); } _getShouldAutoClose(languageId, autoCloseConfig, forQuotes) { switch (autoCloseConfig) { case "beforeWhitespace": return autoCloseBeforeWhitespace; case "languageDefined": return this._getLanguageDefinedShouldAutoClose(languageId, forQuotes); case "always": return autoCloseAlways; case "never": return autoCloseNever; } } _getLanguageDefinedShouldAutoClose(languageId, forQuotes) { const autoCloseBeforeSet = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoCloseBeforeSet(forQuotes); return (c) => autoCloseBeforeSet.indexOf(c) !== -1; } /** * Returns a visible column from a column. * @see {@link CursorColumns} */ visibleColumnFromColumn(model, position) { return CursorColumns.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, this.tabSize); } /** * Returns a visible column from a column. * @see {@link CursorColumns} */ columnFromVisibleColumn(model, lineNumber, visibleColumn) { const result = CursorColumns.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, this.tabSize); const minColumn = model.getLineMinColumn(lineNumber); if (result < minColumn) { return minColumn; } const maxColumn = model.getLineMaxColumn(lineNumber); if (result > maxColumn) { return maxColumn; } return result; } } let CursorState$1 = class CursorState2 { static fromModelState(modelState) { return new PartialModelCursorState(modelState); } static fromViewState(viewState) { return new PartialViewCursorState(viewState); } static fromModelSelection(modelSelection) { const selection = Selection$1.liftSelection(modelSelection); const modelState = new SingleCursorState(Range$2.fromPositions(selection.getSelectionStart()), 0, 0, selection.getPosition(), 0); return CursorState2.fromModelState(modelState); } static fromModelSelections(modelSelections) { const states = []; for (let i2 = 0, len = modelSelections.length; i2 < len; i2++) { states[i2] = this.fromModelSelection(modelSelections[i2]); } return states; } constructor(modelState, viewState) { this._cursorStateBrand = void 0; this.modelState = modelState; this.viewState = viewState; } equals(other) { return this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState); } }; class PartialModelCursorState { constructor(modelState) { this.modelState = modelState; this.viewState = null; } } class PartialViewCursorState { constructor(viewState) { this.modelState = null; this.viewState = viewState; } } class SingleCursorState { constructor(selectionStart, selectionStartKind, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns) { this.selectionStart = selectionStart; this.selectionStartKind = selectionStartKind; this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns; this.position = position; this.leftoverVisibleColumns = leftoverVisibleColumns; this._singleCursorStateBrand = void 0; this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position); } equals(other) { return this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns && this.leftoverVisibleColumns === other.leftoverVisibleColumns && this.selectionStartKind === other.selectionStartKind && this.position.equals(other.position) && this.selectionStart.equalsRange(other.selectionStart); } hasSelection() { return !this.selection.isEmpty() || !this.selectionStart.isEmpty(); } move(inSelectionMode, lineNumber, column, leftoverVisibleColumns) { if (inSelectionMode) { return new SingleCursorState(this.selectionStart, this.selectionStartKind, this.selectionStartLeftoverVisibleColumns, new Position$1(lineNumber, column), leftoverVisibleColumns); } else { return new SingleCursorState(new Range$2(lineNumber, column, lineNumber, column), 0, leftoverVisibleColumns, new Position$1(lineNumber, column), leftoverVisibleColumns); } } static _computeSelection(selectionStart, position) { if (selectionStart.isEmpty() || !position.isBeforeOrEqual(selectionStart.getStartPosition())) { return Selection$1.fromPositions(selectionStart.getStartPosition(), position); } else { return Selection$1.fromPositions(selectionStart.getEndPosition(), position); } } } class EditOperationResult { constructor(type, commands, opts) { this._editOperationResultBrand = void 0; this.type = type; this.commands = commands; this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore; this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter; } } function isQuote(ch) { return ch === "'" || ch === '"' || ch === "`"; } class ColumnSelection { static columnSelect(config, model, fromLineNumber, fromVisibleColumn, toLineNumber, toVisibleColumn) { const lineCount = Math.abs(toLineNumber - fromLineNumber) + 1; const reversed = fromLineNumber > toLineNumber; const isRTL = fromVisibleColumn > toVisibleColumn; const isLTR = fromVisibleColumn < toVisibleColumn; const result = []; for (let i2 = 0; i2 < lineCount; i2++) { const lineNumber = fromLineNumber + (reversed ? -i2 : i2); const startColumn = config.columnFromVisibleColumn(model, lineNumber, fromVisibleColumn); const endColumn = config.columnFromVisibleColumn(model, lineNumber, toVisibleColumn); const visibleStartColumn = config.visibleColumnFromColumn(model, new Position$1(lineNumber, startColumn)); const visibleEndColumn = config.visibleColumnFromColumn(model, new Position$1(lineNumber, endColumn)); if (isLTR) { if (visibleStartColumn > toVisibleColumn) { continue; } if (visibleEndColumn < fromVisibleColumn) { continue; } } if (isRTL) { if (visibleEndColumn > fromVisibleColumn) { continue; } if (visibleStartColumn < toVisibleColumn) { continue; } } result.push(new SingleCursorState(new Range$2(lineNumber, startColumn, lineNumber, startColumn), 0, 0, new Position$1(lineNumber, endColumn), 0)); } if (result.length === 0) { for (let i2 = 0; i2 < lineCount; i2++) { const lineNumber = fromLineNumber + (reversed ? -i2 : i2); const maxColumn = model.getLineMaxColumn(lineNumber); result.push(new SingleCursorState(new Range$2(lineNumber, maxColumn, lineNumber, maxColumn), 0, 0, new Position$1(lineNumber, maxColumn), 0)); } } return { viewStates: result, reversed, fromLineNumber, fromVisualColumn: fromVisibleColumn, toLineNumber, toVisualColumn: toVisibleColumn }; } static columnSelectLeft(config, model, prevColumnSelectData) { let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn; if (toViewVisualColumn > 0) { toViewVisualColumn--; } return ColumnSelection.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn); } static columnSelectRight(config, model, prevColumnSelectData) { let maxVisualViewColumn = 0; const minViewLineNumber = Math.min(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber); const maxViewLineNumber = Math.max(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber); for (let lineNumber = minViewLineNumber; lineNumber <= maxViewLineNumber; lineNumber++) { const lineMaxViewColumn = model.getLineMaxColumn(lineNumber); const lineMaxVisualViewColumn = config.visibleColumnFromColumn(model, new Position$1(lineNumber, lineMaxViewColumn)); maxVisualViewColumn = Math.max(maxVisualViewColumn, lineMaxVisualViewColumn); } let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn; if (toViewVisualColumn < maxVisualViewColumn) { toViewVisualColumn++; } return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn); } static columnSelectUp(config, model, prevColumnSelectData, isPaged) { const linesCount = isPaged ? config.pageSize : 1; const toViewLineNumber = Math.max(1, prevColumnSelectData.toViewLineNumber - linesCount); return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn); } static columnSelectDown(config, model, prevColumnSelectData, isPaged) { const linesCount = isPaged ? config.pageSize : 1; const toViewLineNumber = Math.min(model.getLineCount(), prevColumnSelectData.toViewLineNumber + linesCount); return this.columnSelect(config, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn); } } class ReplaceCommand { constructor(range2, text2, insertsAutoWhitespace = false) { this._range = range2; this._text = text2; this.insertsAutoWhitespace = insertsAutoWhitespace; } getEditOperations(model, builder) { builder.addTrackedEditOperation(this._range, this._text); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const srcRange = inverseEditOperations[0].range; return Selection$1.fromPositions(srcRange.getEndPosition()); } } class ReplaceOvertypeCommand { constructor(range2, text2, insertsAutoWhitespace = false) { this._range = range2; this._text = text2; this.insertsAutoWhitespace = insertsAutoWhitespace; } getEditOperations(model, builder) { const intialStartPosition = this._range.getStartPosition(); const initialEndPosition = this._range.getEndPosition(); const initialEndLineNumber = initialEndPosition.lineNumber; const offsetDelta = this._text.length + (this._range.isEmpty() ? 0 : -1); let endPosition = addPositiveOffsetToModelPosition(model, initialEndPosition, offsetDelta); if (endPosition.lineNumber > initialEndLineNumber) { endPosition = new Position$1(initialEndLineNumber, model.getLineMaxColumn(initialEndLineNumber)); } const replaceRange = Range$2.fromPositions(intialStartPosition, endPosition); builder.addTrackedEditOperation(replaceRange, this._text); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const srcRange = inverseEditOperations[0].range; return Selection$1.fromPositions(srcRange.getEndPosition()); } } class ReplaceCommandThatSelectsText { constructor(range2, text2) { this._range = range2; this._text = text2; } getEditOperations(model, builder) { builder.addTrackedEditOperation(this._range, this._text); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const srcRange = inverseEditOperations[0].range; return Selection$1.fromRange( srcRange, 0 /* SelectionDirection.LTR */ ); } } class ReplaceCommandWithoutChangingPosition { constructor(range2, text2, insertsAutoWhitespace = false) { this._range = range2; this._text = text2; this.insertsAutoWhitespace = insertsAutoWhitespace; } getEditOperations(model, builder) { builder.addTrackedEditOperation(this._range, this._text); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const srcRange = inverseEditOperations[0].range; return Selection$1.fromPositions(srcRange.getStartPosition()); } } class ReplaceCommandWithOffsetCursorState { constructor(range2, text2, lineNumberDeltaOffset, columnDeltaOffset, insertsAutoWhitespace = false) { this._range = range2; this._text = text2; this._columnDeltaOffset = columnDeltaOffset; this._lineNumberDeltaOffset = lineNumberDeltaOffset; this.insertsAutoWhitespace = insertsAutoWhitespace; } getEditOperations(model, builder) { builder.addTrackedEditOperation(this._range, this._text); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const srcRange = inverseEditOperations[0].range; return Selection$1.fromPositions(srcRange.getEndPosition().delta(this._lineNumberDeltaOffset, this._columnDeltaOffset)); } } class ReplaceOvertypeCommandOnCompositionEnd { constructor(range2) { this._range = range2; } getEditOperations(model, builder) { const text2 = model.getValueInRange(this._range); const initialEndPosition = this._range.getEndPosition(); const initialEndLineNumber = initialEndPosition.lineNumber; let endPosition = addPositiveOffsetToModelPosition(model, initialEndPosition, text2.length); if (endPosition.lineNumber > initialEndLineNumber) { endPosition = new Position$1(initialEndLineNumber, model.getLineMaxColumn(initialEndLineNumber)); } const replaceRange = Range$2.fromPositions(initialEndPosition, endPosition); builder.addTrackedEditOperation(replaceRange, ""); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const srcRange = inverseEditOperations[0].range; return Selection$1.fromPositions(srcRange.getEndPosition()); } } class ReplaceCommandThatPreservesSelection { constructor(editRange, text2, initialSelection, forceMoveMarkers = false) { this._range = editRange; this._text = text2; this._initialSelection = initialSelection; this._forceMoveMarkers = forceMoveMarkers; this._selectionId = null; } getEditOperations(model, builder) { builder.addTrackedEditOperation(this._range, this._text, this._forceMoveMarkers); this._selectionId = builder.trackSelection(this._initialSelection); } computeCursorState(model, helper) { return helper.getTrackedSelection(this._selectionId); } } function addPositiveOffsetToModelPosition(model, position, offset) { if (offset < 0) { throw new Error("Unexpected negative delta"); } const lineCount = model.getLineCount(); let endPosition = new Position$1(lineCount, model.getLineMaxColumn(lineCount)); for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) { if (lineNumber === position.lineNumber) { const futureOffset = offset - model.getLineMaxColumn(position.lineNumber) + position.column; if (futureOffset <= 0) { endPosition = new Position$1(position.lineNumber, position.column + offset); break; } offset = futureOffset; } else { const futureOffset = offset - model.getLineMaxColumn(lineNumber); if (futureOffset <= 0) { endPosition = new Position$1(lineNumber, offset); break; } offset = futureOffset; } } return endPosition; } class AtomicTabMoveOperations { /** * Get the visible column at the position. If we get to a non-whitespace character first * or past the end of string then return -1. * * **Note** `position` and the return value are 0-based. */ static whitespaceVisibleColumn(lineContent, position, tabSize) { const lineLength = lineContent.length; let visibleColumn = 0; let prevTabStopPosition = -1; let prevTabStopVisibleColumn = -1; for (let i2 = 0; i2 < lineLength; i2++) { if (i2 === position) { return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn]; } if (visibleColumn % tabSize === 0) { prevTabStopPosition = i2; prevTabStopVisibleColumn = visibleColumn; } const chCode = lineContent.charCodeAt(i2); switch (chCode) { case 32: visibleColumn += 1; break; case 9: visibleColumn = CursorColumns.nextRenderTabStop(visibleColumn, tabSize); break; default: return [-1, -1, -1]; } } if (position === lineLength) { return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn]; } return [-1, -1, -1]; } /** * Return the position that should result from a move left, right or to the * nearest tab, if atomic tabs are enabled. Left and right are used for the * arrow key movements, nearest is used for mouse selection. It returns * -1 if atomic tabs are not relevant and you should fall back to normal * behaviour. * * **Note**: `position` and the return value are 0-based. */ static atomicPosition(lineContent, position, tabSize, direction) { const lineLength = lineContent.length; const [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn] = AtomicTabMoveOperations.whitespaceVisibleColumn(lineContent, position, tabSize); if (visibleColumn === -1) { return -1; } let left; switch (direction) { case 0: left = true; break; case 1: left = false; break; case 2: if (visibleColumn % tabSize === 0) { return position; } left = visibleColumn % tabSize <= tabSize / 2; break; } if (left) { if (prevTabStopPosition === -1) { return -1; } let currentVisibleColumn2 = prevTabStopVisibleColumn; for (let i2 = prevTabStopPosition; i2 < lineLength; ++i2) { if (currentVisibleColumn2 === prevTabStopVisibleColumn + tabSize) { return prevTabStopPosition; } const chCode = lineContent.charCodeAt(i2); switch (chCode) { case 32: currentVisibleColumn2 += 1; break; case 9: currentVisibleColumn2 = CursorColumns.nextRenderTabStop(currentVisibleColumn2, tabSize); break; default: return -1; } } if (currentVisibleColumn2 === prevTabStopVisibleColumn + tabSize) { return prevTabStopPosition; } return -1; } const targetVisibleColumn = CursorColumns.nextRenderTabStop(visibleColumn, tabSize); let currentVisibleColumn = visibleColumn; for (let i2 = position; i2 < lineLength; i2++) { if (currentVisibleColumn === targetVisibleColumn) { return i2; } const chCode = lineContent.charCodeAt(i2); switch (chCode) { case 32: currentVisibleColumn += 1; break; case 9: currentVisibleColumn = CursorColumns.nextRenderTabStop(currentVisibleColumn, tabSize); break; default: return -1; } } if (currentVisibleColumn === targetVisibleColumn) { return lineLength; } return -1; } } class CursorPosition { constructor(lineNumber, column, leftoverVisibleColumns) { this._cursorPositionBrand = void 0; this.lineNumber = lineNumber; this.column = column; this.leftoverVisibleColumns = leftoverVisibleColumns; } } class MoveOperations { static leftPosition(model, position) { if (position.column > model.getLineMinColumn(position.lineNumber)) { return position.delta(void 0, -prevCharLength(model.getLineContent(position.lineNumber), position.column - 1)); } else if (position.lineNumber > 1) { const newLineNumber = position.lineNumber - 1; return new Position$1(newLineNumber, model.getLineMaxColumn(newLineNumber)); } else { return position; } } static leftPositionAtomicSoftTabs(model, position, tabSize) { if (position.column <= model.getLineIndentColumn(position.lineNumber)) { const minColumn = model.getLineMinColumn(position.lineNumber); const lineContent = model.getLineContent(position.lineNumber); const newPosition = AtomicTabMoveOperations.atomicPosition( lineContent, position.column - 1, tabSize, 0 /* Direction.Left */ ); if (newPosition !== -1 && newPosition + 1 >= minColumn) { return new Position$1(position.lineNumber, newPosition + 1); } } return this.leftPosition(model, position); } static left(config, model, position) { const pos = config.stickyTabStops ? MoveOperations.leftPositionAtomicSoftTabs(model, position, config.tabSize) : MoveOperations.leftPosition(model, position); return new CursorPosition(pos.lineNumber, pos.column, 0); } /** * @param noOfColumns Must be either `1` * or `Math.round(viewModel.getLineContent(viewLineNumber).length / 2)` (for half lines). */ static moveLeft(config, model, cursor, inSelectionMode, noOfColumns) { let lineNumber, column; if (cursor.hasSelection() && !inSelectionMode) { lineNumber = cursor.selection.startLineNumber; column = cursor.selection.startColumn; } else { const pos = cursor.position.delta(void 0, -(noOfColumns - 1)); const normalizedPos = model.normalizePosition( MoveOperations.clipPositionColumn(pos, model), 0 /* PositionAffinity.Left */ ); const p = MoveOperations.left(config, model, normalizedPos); lineNumber = p.lineNumber; column = p.column; } return cursor.move(inSelectionMode, lineNumber, column, 0); } /** * Adjusts the column so that it is within min/max of the line. */ static clipPositionColumn(position, model) { return new Position$1(position.lineNumber, MoveOperations.clipRange(position.column, model.getLineMinColumn(position.lineNumber), model.getLineMaxColumn(position.lineNumber))); } static clipRange(value, min, max) { if (value < min) { return min; } if (value > max) { return max; } return value; } static rightPosition(model, lineNumber, column) { if (column < model.getLineMaxColumn(lineNumber)) { column = column + nextCharLength(model.getLineContent(lineNumber), column - 1); } else if (lineNumber < model.getLineCount()) { lineNumber = lineNumber + 1; column = model.getLineMinColumn(lineNumber); } return new Position$1(lineNumber, column); } static rightPositionAtomicSoftTabs(model, lineNumber, column, tabSize, indentSize) { if (column < model.getLineIndentColumn(lineNumber)) { const lineContent = model.getLineContent(lineNumber); const newPosition = AtomicTabMoveOperations.atomicPosition( lineContent, column - 1, tabSize, 1 /* Direction.Right */ ); if (newPosition !== -1) { return new Position$1(lineNumber, newPosition + 1); } } return this.rightPosition(model, lineNumber, column); } static right(config, model, position) { const pos = config.stickyTabStops ? MoveOperations.rightPositionAtomicSoftTabs(model, position.lineNumber, position.column, config.tabSize, config.indentSize) : MoveOperations.rightPosition(model, position.lineNumber, position.column); return new CursorPosition(pos.lineNumber, pos.column, 0); } static moveRight(config, model, cursor, inSelectionMode, noOfColumns) { let lineNumber, column; if (cursor.hasSelection() && !inSelectionMode) { lineNumber = cursor.selection.endLineNumber; column = cursor.selection.endColumn; } else { const pos = cursor.position.delta(void 0, noOfColumns - 1); const normalizedPos = model.normalizePosition( MoveOperations.clipPositionColumn(pos, model), 1 /* PositionAffinity.Right */ ); const r = MoveOperations.right(config, model, normalizedPos); lineNumber = r.lineNumber; column = r.column; } return cursor.move(inSelectionMode, lineNumber, column, 0); } static vertical(config, model, lineNumber, column, leftoverVisibleColumns, newLineNumber, allowMoveOnEdgeLine, normalizationAffinity) { const currentVisibleColumn = CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns; const lineCount = model.getLineCount(); const wasOnFirstPosition = lineNumber === 1 && column === 1; const wasOnLastPosition = lineNumber === lineCount && column === model.getLineMaxColumn(lineNumber); const wasAtEdgePosition = newLineNumber < lineNumber ? wasOnFirstPosition : wasOnLastPosition; lineNumber = newLineNumber; if (lineNumber < 1) { lineNumber = 1; if (allowMoveOnEdgeLine) { column = model.getLineMinColumn(lineNumber); } else { column = Math.min(model.getLineMaxColumn(lineNumber), column); } } else if (lineNumber > lineCount) { lineNumber = lineCount; if (allowMoveOnEdgeLine) { column = model.getLineMaxColumn(lineNumber); } else { column = Math.min(model.getLineMaxColumn(lineNumber), column); } } else { column = config.columnFromVisibleColumn(model, lineNumber, currentVisibleColumn); } if (wasAtEdgePosition) { leftoverVisibleColumns = 0; } else { leftoverVisibleColumns = currentVisibleColumn - CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize); } if (normalizationAffinity !== void 0) { const position = new Position$1(lineNumber, column); const newPosition = model.normalizePosition(position, normalizationAffinity); leftoverVisibleColumns = leftoverVisibleColumns + (column - newPosition.column); lineNumber = newPosition.lineNumber; column = newPosition.column; } return new CursorPosition(lineNumber, column, leftoverVisibleColumns); } static down(config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnLastLine) { return this.vertical( config, model, lineNumber, column, leftoverVisibleColumns, lineNumber + count, allowMoveOnLastLine, 4 /* PositionAffinity.RightOfInjectedText */ ); } static moveDown(config, model, cursor, inSelectionMode, linesCount) { let lineNumber, column; if (cursor.hasSelection() && !inSelectionMode) { lineNumber = cursor.selection.endLineNumber; column = cursor.selection.endColumn; } else { lineNumber = cursor.position.lineNumber; column = cursor.position.column; } let i2 = 0; let r; do { r = MoveOperations.down(config, model, lineNumber + i2, column, cursor.leftoverVisibleColumns, linesCount, true); const np = model.normalizePosition( new Position$1(r.lineNumber, r.column), 2 /* PositionAffinity.None */ ); if (np.lineNumber > lineNumber) { break; } } while (i2++ < 10 && lineNumber + i2 < model.getLineCount()); return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns); } static translateDown(config, model, cursor) { const selection = cursor.selection; const selectionStart = MoveOperations.down(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false); const position = MoveOperations.down(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false); return new SingleCursorState(new Range$2(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), 0, selectionStart.leftoverVisibleColumns, new Position$1(position.lineNumber, position.column), position.leftoverVisibleColumns); } static up(config, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnFirstLine) { return this.vertical( config, model, lineNumber, column, leftoverVisibleColumns, lineNumber - count, allowMoveOnFirstLine, 3 /* PositionAffinity.LeftOfInjectedText */ ); } static moveUp(config, model, cursor, inSelectionMode, linesCount) { let lineNumber, column; if (cursor.hasSelection() && !inSelectionMode) { lineNumber = cursor.selection.startLineNumber; column = cursor.selection.startColumn; } else { lineNumber = cursor.position.lineNumber; column = cursor.position.column; } const r = MoveOperations.up(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true); return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns); } static translateUp(config, model, cursor) { const selection = cursor.selection; const selectionStart = MoveOperations.up(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false); const position = MoveOperations.up(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false); return new SingleCursorState(new Range$2(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), 0, selectionStart.leftoverVisibleColumns, new Position$1(position.lineNumber, position.column), position.leftoverVisibleColumns); } static _isBlankLine(model, lineNumber) { if (model.getLineFirstNonWhitespaceColumn(lineNumber) === 0) { return true; } return false; } static moveToPrevBlankLine(config, model, cursor, inSelectionMode) { let lineNumber = cursor.position.lineNumber; while (lineNumber > 1 && this._isBlankLine(model, lineNumber)) { lineNumber--; } while (lineNumber > 1 && !this._isBlankLine(model, lineNumber)) { lineNumber--; } return cursor.move(inSelectionMode, lineNumber, model.getLineMinColumn(lineNumber), 0); } static moveToNextBlankLine(config, model, cursor, inSelectionMode) { const lineCount = model.getLineCount(); let lineNumber = cursor.position.lineNumber; while (lineNumber < lineCount && this._isBlankLine(model, lineNumber)) { lineNumber++; } while (lineNumber < lineCount && !this._isBlankLine(model, lineNumber)) { lineNumber++; } return cursor.move(inSelectionMode, lineNumber, model.getLineMinColumn(lineNumber), 0); } static moveToBeginningOfLine(config, model, cursor, inSelectionMode) { const lineNumber = cursor.position.lineNumber; const minColumn = model.getLineMinColumn(lineNumber); const firstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(lineNumber) || minColumn; let column; const relevantColumnNumber = cursor.position.column; if (relevantColumnNumber === firstNonBlankColumn) { column = minColumn; } else { column = firstNonBlankColumn; } return cursor.move(inSelectionMode, lineNumber, column, 0); } static moveToEndOfLine(config, model, cursor, inSelectionMode, sticky) { const lineNumber = cursor.position.lineNumber; const maxColumn = model.getLineMaxColumn(lineNumber); return cursor.move(inSelectionMode, lineNumber, maxColumn, sticky ? 1073741824 - maxColumn : 0); } static moveToBeginningOfBuffer(config, model, cursor, inSelectionMode) { return cursor.move(inSelectionMode, 1, 1, 0); } static moveToEndOfBuffer(config, model, cursor, inSelectionMode) { const lastLineNumber = model.getLineCount(); const lastColumn = model.getLineMaxColumn(lastLineNumber); return cursor.move(inSelectionMode, lastLineNumber, lastColumn, 0); } } class DeleteOperations { static deleteRight(prevEditOperationType, config, model, selections) { const commands = []; let shouldPushStackElementBefore = prevEditOperationType !== 3; for (let i2 = 0, len = selections.length; i2 < len; i2++) { const selection = selections[i2]; const deleteSelection = this.getDeleteRightRange(selection, model, config); if (deleteSelection.isEmpty()) { commands[i2] = null; continue; } if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) { shouldPushStackElementBefore = true; } commands[i2] = new ReplaceCommand(deleteSelection, ""); } return [shouldPushStackElementBefore, commands]; } static getDeleteRightRange(selection, model, config) { if (!selection.isEmpty()) { return selection; } const position = selection.getPosition(); const rightOfPosition = MoveOperations.right(config, model, position); if (config.trimWhitespaceOnDelete && rightOfPosition.lineNumber !== position.lineNumber) { const currentLineHasContent = model.getLineFirstNonWhitespaceColumn(position.lineNumber) > 0; const firstNonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(rightOfPosition.lineNumber); if (currentLineHasContent && firstNonWhitespaceColumn > 0) { return new Range$2(rightOfPosition.lineNumber, firstNonWhitespaceColumn, position.lineNumber, position.column); } } return new Range$2(rightOfPosition.lineNumber, rightOfPosition.column, position.lineNumber, position.column); } static isAutoClosingPairDelete(autoClosingDelete, autoClosingBrackets, autoClosingQuotes, autoClosingPairsOpen, model, selections, autoClosedCharacters) { if (autoClosingBrackets === "never" && autoClosingQuotes === "never") { return false; } if (autoClosingDelete === "never") { return false; } for (let i2 = 0, len = selections.length; i2 < len; i2++) { const selection = selections[i2]; const position = selection.getPosition(); if (!selection.isEmpty()) { return false; } const lineText = model.getLineContent(position.lineNumber); if (position.column < 2 || position.column >= lineText.length + 1) { return false; } const character = lineText.charAt(position.column - 2); const autoClosingPairCandidates = autoClosingPairsOpen.get(character); if (!autoClosingPairCandidates) { return false; } if (isQuote(character)) { if (autoClosingQuotes === "never") { return false; } } else { if (autoClosingBrackets === "never") { return false; } } const afterCharacter = lineText.charAt(position.column - 1); let foundAutoClosingPair = false; for (const autoClosingPairCandidate of autoClosingPairCandidates) { if (autoClosingPairCandidate.open === character && autoClosingPairCandidate.close === afterCharacter) { foundAutoClosingPair = true; } } if (!foundAutoClosingPair) { return false; } if (autoClosingDelete === "auto") { let found = false; for (let j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) { const autoClosedCharacter = autoClosedCharacters[j]; if (position.lineNumber === autoClosedCharacter.startLineNumber && position.column === autoClosedCharacter.startColumn) { found = true; break; } } if (!found) { return false; } } } return true; } static _runAutoClosingPairDelete(config, model, selections) { const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { const position = selections[i2].getPosition(); const deleteSelection = new Range$2(position.lineNumber, position.column - 1, position.lineNumber, position.column + 1); commands[i2] = new ReplaceCommand(deleteSelection, ""); } return [true, commands]; } static deleteLeft(prevEditOperationType, config, model, selections, autoClosedCharacters) { if (this.isAutoClosingPairDelete(config.autoClosingDelete, config.autoClosingBrackets, config.autoClosingQuotes, config.autoClosingPairs.autoClosingPairsOpenByEnd, model, selections, autoClosedCharacters)) { return this._runAutoClosingPairDelete(config, model, selections); } const commands = []; let shouldPushStackElementBefore = prevEditOperationType !== 2; for (let i2 = 0, len = selections.length; i2 < len; i2++) { const deleteRange = DeleteOperations.getDeleteLeftRange(selections[i2], model, config); if (deleteRange.isEmpty()) { commands[i2] = null; continue; } if (deleteRange.startLineNumber !== deleteRange.endLineNumber) { shouldPushStackElementBefore = true; } commands[i2] = new ReplaceCommand(deleteRange, ""); } return [shouldPushStackElementBefore, commands]; } static getDeleteLeftRange(selection, model, config) { if (!selection.isEmpty()) { return selection; } const position = selection.getPosition(); if (config.useTabStops && position.column > 1) { const lineContent = model.getLineContent(position.lineNumber); const firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent); const lastIndentationColumn = firstNonWhitespaceIndex$1 === -1 ? ( /* entire string is whitespace */ lineContent.length + 1 ) : firstNonWhitespaceIndex$1 + 1; if (position.column <= lastIndentationColumn) { const fromVisibleColumn = config.visibleColumnFromColumn(model, position); const toVisibleColumn = CursorColumns.prevIndentTabStop(fromVisibleColumn, config.indentSize); const toColumn = config.columnFromVisibleColumn(model, position.lineNumber, toVisibleColumn); return new Range$2(position.lineNumber, toColumn, position.lineNumber, position.column); } } return Range$2.fromPositions(DeleteOperations.getPositionAfterDeleteLeft(position, model), position); } static getPositionAfterDeleteLeft(position, model) { if (position.column > 1) { const idx = getLeftDeleteOffset(position.column - 1, model.getLineContent(position.lineNumber)); return position.with(void 0, idx + 1); } else if (position.lineNumber > 1) { const newLine = position.lineNumber - 1; return new Position$1(newLine, model.getLineMaxColumn(newLine)); } else { return position; } } static cut(config, model, selections) { const commands = []; let lastCutRange = null; selections.sort((a, b) => Position$1.compare(a.getStartPosition(), b.getEndPosition())); for (let i2 = 0, len = selections.length; i2 < len; i2++) { const selection = selections[i2]; if (selection.isEmpty()) { if (config.emptySelectionClipboard) { const position = selection.getPosition(); let startLineNumber, startColumn, endLineNumber, endColumn; if (position.lineNumber < model.getLineCount()) { startLineNumber = position.lineNumber; startColumn = 1; endLineNumber = position.lineNumber + 1; endColumn = 1; } else if (position.lineNumber > 1 && lastCutRange?.endLineNumber !== position.lineNumber) { startLineNumber = position.lineNumber - 1; startColumn = model.getLineMaxColumn(position.lineNumber - 1); endLineNumber = position.lineNumber; endColumn = model.getLineMaxColumn(position.lineNumber); } else { startLineNumber = position.lineNumber; startColumn = 1; endLineNumber = position.lineNumber; endColumn = model.getLineMaxColumn(position.lineNumber); } const deleteSelection = new Range$2(startLineNumber, startColumn, endLineNumber, endColumn); lastCutRange = deleteSelection; if (!deleteSelection.isEmpty()) { commands[i2] = new ReplaceCommand(deleteSelection, ""); } else { commands[i2] = null; } } else { commands[i2] = null; } } else { commands[i2] = new ReplaceCommand(selection, ""); } } return new EditOperationResult(0, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: true }); } } const safeIntl = { DateTimeFormat(locales, options) { return new Lazy(() => { try { return new Intl.DateTimeFormat(locales, options); } catch { return new Intl.DateTimeFormat(void 0, options); } }); }, Collator(locales, options) { return new Lazy(() => { try { return new Intl.Collator(locales, options); } catch { return new Intl.Collator(void 0, options); } }); }, Segmenter(locales, options) { return new Lazy(() => { try { return new Intl.Segmenter(locales, options); } catch { return new Intl.Segmenter(void 0, options); } }); }, Locale(tag2, options) { return new Lazy(() => { try { return new Intl.Locale(tag2, options); } catch { return new Intl.Locale(LANGUAGE_DEFAULT, options); } }); }, NumberFormat(locales, options) { return new Lazy(() => { try { return new Intl.NumberFormat(locales, options); } catch { return new Intl.NumberFormat(void 0, options); } }); } }; function toUint8(v) { if (v < 0) { return 0; } if (v > 255) { return 255; } return v | 0; } function toUint32(v) { if (v < 0) { return 0; } if (v > 4294967295) { return 4294967295; } return v | 0; } class CharacterClassifier { constructor(_defaultValue) { const defaultValue = toUint8(_defaultValue); this._defaultValue = defaultValue; this._asciiMap = CharacterClassifier._createAsciiMap(defaultValue); this._map = /* @__PURE__ */ new Map(); } static _createAsciiMap(defaultValue) { const asciiMap = new Uint8Array(256); asciiMap.fill(defaultValue); return asciiMap; } set(charCode, _value) { const value = toUint8(_value); if (charCode >= 0 && charCode < 256) { this._asciiMap[charCode] = value; } else { this._map.set(charCode, value); } } get(charCode) { if (charCode >= 0 && charCode < 256) { return this._asciiMap[charCode]; } else { return this._map.get(charCode) || this._defaultValue; } } clear() { this._asciiMap.fill(this._defaultValue); this._map.clear(); } } class CharacterSet { constructor() { this._actual = new CharacterClassifier( 0 /* Boolean.False */ ); } add(charCode) { this._actual.set( charCode, 1 /* Boolean.True */ ); } has(charCode) { return this._actual.get(charCode) === 1; } clear() { return this._actual.clear(); } } class WordCharacterClassifier extends CharacterClassifier { constructor(wordSeparators2, intlSegmenterLocales) { super( 0 /* WordCharacterClass.Regular */ ); this._segmenter = null; this._cachedLine = null; this._cachedSegments = []; this.intlSegmenterLocales = intlSegmenterLocales; if (this.intlSegmenterLocales.length > 0) { this._segmenter = safeIntl.Segmenter(this.intlSegmenterLocales, { granularity: "word" }); } else { this._segmenter = null; } for (let i2 = 0, len = wordSeparators2.length; i2 < len; i2++) { this.set( wordSeparators2.charCodeAt(i2), 2 /* WordCharacterClass.WordSeparator */ ); } this.set( 32, 1 /* WordCharacterClass.Whitespace */ ); this.set( 9, 1 /* WordCharacterClass.Whitespace */ ); } findPrevIntlWordBeforeOrAtOffset(line, offset) { let candidate = null; for (const segment of this._getIntlSegmenterWordsOnLine(line)) { if (segment.index > offset) { break; } candidate = segment; } return candidate; } findNextIntlWordAtOrAfterOffset(lineContent, offset) { for (const segment of this._getIntlSegmenterWordsOnLine(lineContent)) { if (segment.index < offset) { continue; } return segment; } return null; } _getIntlSegmenterWordsOnLine(line) { if (!this._segmenter) { return []; } if (this._cachedLine === line) { return this._cachedSegments; } this._cachedLine = line; this._cachedSegments = this._filterWordSegments(this._segmenter.value.segment(line)); return this._cachedSegments; } _filterWordSegments(segments) { const result = []; for (const segment of segments) { if (this._isWordLike(segment)) { result.push(segment); } } return result; } _isWordLike(segment) { if (segment.isWordLike) { return true; } return false; } } const wordClassifierCache = new LRUCache(10); function getMapForWordSeparators(wordSeparators2, intlSegmenterLocales) { const key = `${wordSeparators2}/${intlSegmenterLocales.join(",")}`; let result = wordClassifierCache.get(key); if (!result) { result = new WordCharacterClassifier(wordSeparators2, intlSegmenterLocales); wordClassifierCache.set(key, result); } return result; } class WordOperations { static _createWord(lineContent, wordType, nextCharClass, start, end) { return { start, end, wordType, nextCharClass }; } static _createIntlWord(intlWord, nextCharClass) { return { start: intlWord.index, end: intlWord.index + intlWord.segment.length, wordType: 1, nextCharClass }; } static _findPreviousWordOnLine(wordSeparators2, model, position) { const lineContent = model.getLineContent(position.lineNumber); return this._doFindPreviousWordOnLine(lineContent, wordSeparators2, position); } static _doFindPreviousWordOnLine(lineContent, wordSeparators2, position) { let wordType = 0; const previousIntlWord = wordSeparators2.findPrevIntlWordBeforeOrAtOffset(lineContent, position.column - 2); for (let chIndex = position.column - 2; chIndex >= 0; chIndex--) { const chCode = lineContent.charCodeAt(chIndex); const chClass = wordSeparators2.get(chCode); if (previousIntlWord && chIndex === previousIntlWord.index) { return this._createIntlWord(previousIntlWord, chClass); } if (chClass === 0) { if (wordType === 2) { return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators2, wordType, chIndex + 1)); } wordType = 1; } else if (chClass === 2) { if (wordType === 1) { return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators2, wordType, chIndex + 1)); } wordType = 2; } else if (chClass === 1) { if (wordType !== 0) { return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators2, wordType, chIndex + 1)); } } } if (wordType !== 0) { return this._createWord(lineContent, wordType, 1, 0, this._findEndOfWord(lineContent, wordSeparators2, wordType, 0)); } return null; } static _findEndOfWord(lineContent, wordSeparators2, wordType, startIndex) { const nextIntlWord = wordSeparators2.findNextIntlWordAtOrAfterOffset(lineContent, startIndex); const len = lineContent.length; for (let chIndex = startIndex; chIndex < len; chIndex++) { const chCode = lineContent.charCodeAt(chIndex); const chClass = wordSeparators2.get(chCode); if (nextIntlWord && chIndex === nextIntlWord.index + nextIntlWord.segment.length) { return chIndex; } if (chClass === 1) { return chIndex; } if (wordType === 1 && chClass === 2) { return chIndex; } if (wordType === 2 && chClass === 0) { return chIndex; } } return len; } static _findNextWordOnLine(wordSeparators2, model, position) { const lineContent = model.getLineContent(position.lineNumber); return this._doFindNextWordOnLine(lineContent, wordSeparators2, position); } static _doFindNextWordOnLine(lineContent, wordSeparators2, position) { let wordType = 0; const len = lineContent.length; const nextIntlWord = wordSeparators2.findNextIntlWordAtOrAfterOffset(lineContent, position.column - 1); for (let chIndex = position.column - 1; chIndex < len; chIndex++) { const chCode = lineContent.charCodeAt(chIndex); const chClass = wordSeparators2.get(chCode); if (nextIntlWord && chIndex === nextIntlWord.index) { return this._createIntlWord(nextIntlWord, chClass); } if (chClass === 0) { if (wordType === 2) { return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators2, wordType, chIndex - 1), chIndex); } wordType = 1; } else if (chClass === 2) { if (wordType === 1) { return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators2, wordType, chIndex - 1), chIndex); } wordType = 2; } else if (chClass === 1) { if (wordType !== 0) { return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators2, wordType, chIndex - 1), chIndex); } } } if (wordType !== 0) { return this._createWord(lineContent, wordType, 1, this._findStartOfWord(lineContent, wordSeparators2, wordType, len - 1), len); } return null; } static _findStartOfWord(lineContent, wordSeparators2, wordType, startIndex) { const previousIntlWord = wordSeparators2.findPrevIntlWordBeforeOrAtOffset(lineContent, startIndex); for (let chIndex = startIndex; chIndex >= 0; chIndex--) { const chCode = lineContent.charCodeAt(chIndex); const chClass = wordSeparators2.get(chCode); if (previousIntlWord && chIndex === previousIntlWord.index) { return chIndex; } if (chClass === 1) { return chIndex + 1; } if (wordType === 1 && chClass === 2) { return chIndex + 1; } if (wordType === 2 && chClass === 0) { return chIndex + 1; } } return 0; } static moveWordLeft(wordSeparators2, model, position, wordNavigationType, hasMulticursor) { let lineNumber = position.lineNumber; let column = position.column; if (column === 1) { if (lineNumber > 1) { lineNumber = lineNumber - 1; column = model.getLineMaxColumn(lineNumber); } } let prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position$1(lineNumber, column)); if (wordNavigationType === 0) { return new Position$1(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1); } if (wordNavigationType === 1) { if (!hasMulticursor && prevWordOnLine && prevWordOnLine.wordType === 2 && prevWordOnLine.end - prevWordOnLine.start === 1 && prevWordOnLine.nextCharClass === 0) { prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position$1(lineNumber, prevWordOnLine.start + 1)); } return new Position$1(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1); } if (wordNavigationType === 3) { while (prevWordOnLine && prevWordOnLine.wordType === 2) { prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position$1(lineNumber, prevWordOnLine.start + 1)); } return new Position$1(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1); } if (prevWordOnLine && column <= prevWordOnLine.end + 1) { prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position$1(lineNumber, prevWordOnLine.start + 1)); } return new Position$1(lineNumber, prevWordOnLine ? prevWordOnLine.end + 1 : 1); } static _moveWordPartLeft(model, position) { const lineNumber = position.lineNumber; const maxColumn = model.getLineMaxColumn(lineNumber); if (position.column === 1) { return lineNumber > 1 ? new Position$1(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)) : position; } const lineContent = model.getLineContent(lineNumber); for (let column = position.column - 1; column > 1; column--) { const left = lineContent.charCodeAt(column - 2); const right = lineContent.charCodeAt(column - 1); if (left === 95 && right !== 95) { return new Position$1(lineNumber, column); } if (left === 45 && right !== 45) { return new Position$1(lineNumber, column); } if ((isLowerAsciiLetter(left) || isAsciiDigit(left)) && isUpperAsciiLetter(right)) { return new Position$1(lineNumber, column); } if (isUpperAsciiLetter(left) && isUpperAsciiLetter(right)) { if (column + 1 < maxColumn) { const rightRight = lineContent.charCodeAt(column); if (isLowerAsciiLetter(rightRight) || isAsciiDigit(rightRight)) { return new Position$1(lineNumber, column); } } } } return new Position$1(lineNumber, 1); } static moveWordRight(wordSeparators2, model, position, wordNavigationType) { let lineNumber = position.lineNumber; let column = position.column; let movedDown = false; if (column === model.getLineMaxColumn(lineNumber)) { if (lineNumber < model.getLineCount()) { movedDown = true; lineNumber = lineNumber + 1; column = 1; } } let nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$1(lineNumber, column)); if (wordNavigationType === 2) { if (nextWordOnLine && nextWordOnLine.wordType === 2) { if (nextWordOnLine.end - nextWordOnLine.start === 1 && nextWordOnLine.nextCharClass === 0) { nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$1(lineNumber, nextWordOnLine.end + 1)); } } if (nextWordOnLine) { column = nextWordOnLine.end + 1; } else { column = model.getLineMaxColumn(lineNumber); } } else if (wordNavigationType === 3) { if (movedDown) { column = 0; } while (nextWordOnLine && (nextWordOnLine.wordType === 2 || nextWordOnLine.start + 1 <= column)) { nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$1(lineNumber, nextWordOnLine.end + 1)); } if (nextWordOnLine) { column = nextWordOnLine.start + 1; } else { column = model.getLineMaxColumn(lineNumber); } } else { if (nextWordOnLine && !movedDown && column >= nextWordOnLine.start + 1) { nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$1(lineNumber, nextWordOnLine.end + 1)); } if (nextWordOnLine) { column = nextWordOnLine.start + 1; } else { column = model.getLineMaxColumn(lineNumber); } } return new Position$1(lineNumber, column); } static _moveWordPartRight(model, position) { const lineNumber = position.lineNumber; const maxColumn = model.getLineMaxColumn(lineNumber); if (position.column === maxColumn) { return lineNumber < model.getLineCount() ? new Position$1(lineNumber + 1, 1) : position; } const lineContent = model.getLineContent(lineNumber); for (let column = position.column + 1; column < maxColumn; column++) { const left = lineContent.charCodeAt(column - 2); const right = lineContent.charCodeAt(column - 1); if (left !== 95 && right === 95) { return new Position$1(lineNumber, column); } if (left !== 45 && right === 45) { return new Position$1(lineNumber, column); } if ((isLowerAsciiLetter(left) || isAsciiDigit(left)) && isUpperAsciiLetter(right)) { return new Position$1(lineNumber, column); } if (isUpperAsciiLetter(left) && isUpperAsciiLetter(right)) { if (column + 1 < maxColumn) { const rightRight = lineContent.charCodeAt(column); if (isLowerAsciiLetter(rightRight) || isAsciiDigit(rightRight)) { return new Position$1(lineNumber, column); } } } } return new Position$1(lineNumber, maxColumn); } static _deleteWordLeftWhitespace(model, position) { const lineContent = model.getLineContent(position.lineNumber); const startIndex = position.column - 2; const lastNonWhitespace = lastNonWhitespaceIndex(lineContent, startIndex); if (lastNonWhitespace + 1 < startIndex) { return new Range$2(position.lineNumber, lastNonWhitespace + 2, position.lineNumber, position.column); } return null; } static deleteWordLeft(ctx, wordNavigationType) { const wordSeparators2 = ctx.wordSeparators; const model = ctx.model; const selection = ctx.selection; const whitespaceHeuristics = ctx.whitespaceHeuristics; if (!selection.isEmpty()) { return selection; } if (DeleteOperations.isAutoClosingPairDelete(ctx.autoClosingDelete, ctx.autoClosingBrackets, ctx.autoClosingQuotes, ctx.autoClosingPairs.autoClosingPairsOpenByEnd, ctx.model, [ctx.selection], ctx.autoClosedCharacters)) { const position2 = ctx.selection.getPosition(); return new Range$2(position2.lineNumber, position2.column - 1, position2.lineNumber, position2.column + 1); } const position = new Position$1(selection.positionLineNumber, selection.positionColumn); let lineNumber = position.lineNumber; let column = position.column; if (lineNumber === 1 && column === 1) { return null; } if (whitespaceHeuristics) { const r = this._deleteWordLeftWhitespace(model, position); if (r) { return r; } } let prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, position); if (wordNavigationType === 0) { if (prevWordOnLine) { column = prevWordOnLine.start + 1; } else { if (column > 1) { column = 1; } else { lineNumber--; column = model.getLineMaxColumn(lineNumber); } } } else { if (prevWordOnLine && column <= prevWordOnLine.end + 1) { prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position$1(lineNumber, prevWordOnLine.start + 1)); } if (prevWordOnLine) { column = prevWordOnLine.end + 1; } else { if (column > 1) { column = 1; } else { lineNumber--; column = model.getLineMaxColumn(lineNumber); } } } return new Range$2(lineNumber, column, position.lineNumber, position.column); } static deleteInsideWord(wordSeparators2, model, selection) { if (!selection.isEmpty()) { return selection; } const position = new Position$1(selection.positionLineNumber, selection.positionColumn); const r = this._deleteInsideWordWhitespace(model, position); if (r) { return r; } return this._deleteInsideWordDetermineDeleteRange(wordSeparators2, model, position); } static _charAtIsWhitespace(str, index) { const charCode = str.charCodeAt(index); return charCode === 32 || charCode === 9; } static _deleteInsideWordWhitespace(model, position) { const lineContent = model.getLineContent(position.lineNumber); const lineContentLength = lineContent.length; if (lineContentLength === 0) { return null; } let leftIndex = Math.max(position.column - 2, 0); if (!this._charAtIsWhitespace(lineContent, leftIndex)) { return null; } let rightIndex = Math.min(position.column - 1, lineContentLength - 1); if (!this._charAtIsWhitespace(lineContent, rightIndex)) { return null; } while (leftIndex > 0 && this._charAtIsWhitespace(lineContent, leftIndex - 1)) { leftIndex--; } while (rightIndex + 1 < lineContentLength && this._charAtIsWhitespace(lineContent, rightIndex + 1)) { rightIndex++; } return new Range$2(position.lineNumber, leftIndex + 1, position.lineNumber, rightIndex + 2); } static _deleteInsideWordDetermineDeleteRange(wordSeparators2, model, position) { const lineContent = model.getLineContent(position.lineNumber); const lineLength = lineContent.length; if (lineLength === 0) { if (position.lineNumber > 1) { return new Range$2(position.lineNumber - 1, model.getLineMaxColumn(position.lineNumber - 1), position.lineNumber, 1); } else { if (position.lineNumber < model.getLineCount()) { return new Range$2(position.lineNumber, 1, position.lineNumber + 1, 1); } else { return new Range$2(position.lineNumber, 1, position.lineNumber, 1); } } } const touchesWord = (word) => { return word.start + 1 <= position.column && position.column <= word.end + 1; }; const createRangeWithPosition = (startColumn, endColumn) => { startColumn = Math.min(startColumn, position.column); endColumn = Math.max(endColumn, position.column); return new Range$2(position.lineNumber, startColumn, position.lineNumber, endColumn); }; const deleteWordAndAdjacentWhitespace = (word) => { let startColumn = word.start + 1; let endColumn = word.end + 1; let expandedToTheRight = false; while (endColumn - 1 < lineLength && this._charAtIsWhitespace(lineContent, endColumn - 1)) { expandedToTheRight = true; endColumn++; } if (!expandedToTheRight) { while (startColumn > 1 && this._charAtIsWhitespace(lineContent, startColumn - 2)) { startColumn--; } } return createRangeWithPosition(startColumn, endColumn); }; const prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, position); if (prevWordOnLine && touchesWord(prevWordOnLine)) { return deleteWordAndAdjacentWhitespace(prevWordOnLine); } const nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, position); if (nextWordOnLine && touchesWord(nextWordOnLine)) { return deleteWordAndAdjacentWhitespace(nextWordOnLine); } if (prevWordOnLine && nextWordOnLine) { return createRangeWithPosition(prevWordOnLine.end + 1, nextWordOnLine.start + 1); } if (prevWordOnLine) { return createRangeWithPosition(prevWordOnLine.start + 1, prevWordOnLine.end + 1); } if (nextWordOnLine) { return createRangeWithPosition(nextWordOnLine.start + 1, nextWordOnLine.end + 1); } return createRangeWithPosition(1, lineLength + 1); } static _deleteWordPartLeft(model, selection) { if (!selection.isEmpty()) { return selection; } const pos = selection.getPosition(); const toPosition = WordOperations._moveWordPartLeft(model, pos); return new Range$2(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column); } static _findFirstNonWhitespaceChar(str, startIndex) { const len = str.length; for (let chIndex = startIndex; chIndex < len; chIndex++) { const ch = str.charAt(chIndex); if (ch !== " " && ch !== " ") { return chIndex; } } return len; } static _deleteWordRightWhitespace(model, position) { const lineContent = model.getLineContent(position.lineNumber); const startIndex = position.column - 1; const firstNonWhitespace = this._findFirstNonWhitespaceChar(lineContent, startIndex); if (startIndex + 1 < firstNonWhitespace) { return new Range$2(position.lineNumber, position.column, position.lineNumber, firstNonWhitespace + 1); } return null; } static deleteWordRight(ctx, wordNavigationType) { const wordSeparators2 = ctx.wordSeparators; const model = ctx.model; const selection = ctx.selection; const whitespaceHeuristics = ctx.whitespaceHeuristics; if (!selection.isEmpty()) { return selection; } const position = new Position$1(selection.positionLineNumber, selection.positionColumn); let lineNumber = position.lineNumber; let column = position.column; const lineCount = model.getLineCount(); const maxColumn = model.getLineMaxColumn(lineNumber); if (lineNumber === lineCount && column === maxColumn) { return null; } if (whitespaceHeuristics) { const r = this._deleteWordRightWhitespace(model, position); if (r) { return r; } } let nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, position); if (wordNavigationType === 2) { if (nextWordOnLine) { column = nextWordOnLine.end + 1; } else { if (column < maxColumn || lineNumber === lineCount) { column = maxColumn; } else { lineNumber++; nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$1(lineNumber, 1)); if (nextWordOnLine) { column = nextWordOnLine.start + 1; } else { column = model.getLineMaxColumn(lineNumber); } } } } else { if (nextWordOnLine && column >= nextWordOnLine.start + 1) { nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$1(lineNumber, nextWordOnLine.end + 1)); } if (nextWordOnLine) { column = nextWordOnLine.start + 1; } else { if (column < maxColumn || lineNumber === lineCount) { column = maxColumn; } else { lineNumber++; nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$1(lineNumber, 1)); if (nextWordOnLine) { column = nextWordOnLine.start + 1; } else { column = model.getLineMaxColumn(lineNumber); } } } } return new Range$2(lineNumber, column, position.lineNumber, position.column); } static _deleteWordPartRight(model, selection) { if (!selection.isEmpty()) { return selection; } const pos = selection.getPosition(); const toPosition = WordOperations._moveWordPartRight(model, pos); return new Range$2(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column); } static _createWordAtPosition(model, lineNumber, word) { const range2 = new Range$2(lineNumber, word.start + 1, lineNumber, word.end + 1); return { word: model.getValueInRange(range2), startColumn: range2.startColumn, endColumn: range2.endColumn }; } static getWordAtPosition(model, _wordSeparators, _intlSegmenterLocales, position) { const wordSeparators2 = getMapForWordSeparators(_wordSeparators, _intlSegmenterLocales); const prevWord = WordOperations._findPreviousWordOnLine(wordSeparators2, model, position); if (prevWord && prevWord.wordType === 1 && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) { return WordOperations._createWordAtPosition(model, position.lineNumber, prevWord); } const nextWord2 = WordOperations._findNextWordOnLine(wordSeparators2, model, position); if (nextWord2 && nextWord2.wordType === 1 && nextWord2.start <= position.column - 1 && position.column - 1 <= nextWord2.end) { return WordOperations._createWordAtPosition(model, position.lineNumber, nextWord2); } return null; } static word(config, model, cursor, inSelectionMode, position) { const wordSeparators2 = getMapForWordSeparators(config.wordSeparators, config.wordSegmenterLocales); const prevWord = WordOperations._findPreviousWordOnLine(wordSeparators2, model, position); const nextWord2 = WordOperations._findNextWordOnLine(wordSeparators2, model, position); if (!inSelectionMode) { let startColumn2; let endColumn2; if (prevWord && prevWord.wordType === 1 && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) { startColumn2 = prevWord.start + 1; endColumn2 = prevWord.end + 1; } else if (nextWord2 && nextWord2.wordType === 1 && nextWord2.start <= position.column - 1 && position.column - 1 <= nextWord2.end) { startColumn2 = nextWord2.start + 1; endColumn2 = nextWord2.end + 1; } else { if (prevWord) { startColumn2 = prevWord.end + 1; } else { startColumn2 = 1; } if (nextWord2) { endColumn2 = nextWord2.start + 1; } else { endColumn2 = model.getLineMaxColumn(position.lineNumber); } } return new SingleCursorState(new Range$2(position.lineNumber, startColumn2, position.lineNumber, endColumn2), 1, 0, new Position$1(position.lineNumber, endColumn2), 0); } let startColumn; let endColumn; if (prevWord && prevWord.wordType === 1 && prevWord.start < position.column - 1 && position.column - 1 < prevWord.end) { startColumn = prevWord.start + 1; endColumn = prevWord.end + 1; } else if (nextWord2 && nextWord2.wordType === 1 && nextWord2.start < position.column - 1 && position.column - 1 < nextWord2.end) { startColumn = nextWord2.start + 1; endColumn = nextWord2.end + 1; } else { startColumn = position.column; endColumn = position.column; } const lineNumber = position.lineNumber; let column; if (cursor.selectionStart.containsPosition(position)) { column = cursor.selectionStart.endColumn; } else if (position.isBeforeOrEqual(cursor.selectionStart.getStartPosition())) { column = startColumn; const possiblePosition = new Position$1(lineNumber, column); if (cursor.selectionStart.containsPosition(possiblePosition)) { column = cursor.selectionStart.endColumn; } } else { column = endColumn; const possiblePosition = new Position$1(lineNumber, column); if (cursor.selectionStart.containsPosition(possiblePosition)) { column = cursor.selectionStart.startColumn; } } return cursor.move(true, lineNumber, column, 0); } } class WordPartOperations extends WordOperations { static deleteWordPartLeft(ctx) { const candidates = enforceDefined([ WordOperations.deleteWordLeft( ctx, 0 /* WordNavigationType.WordStart */ ), WordOperations.deleteWordLeft( ctx, 2 /* WordNavigationType.WordEnd */ ), WordOperations._deleteWordPartLeft(ctx.model, ctx.selection) ]); candidates.sort(Range$2.compareRangesUsingEnds); return candidates[2]; } static deleteWordPartRight(ctx) { const candidates = enforceDefined([ WordOperations.deleteWordRight( ctx, 0 /* WordNavigationType.WordStart */ ), WordOperations.deleteWordRight( ctx, 2 /* WordNavigationType.WordEnd */ ), WordOperations._deleteWordPartRight(ctx.model, ctx.selection) ]); candidates.sort(Range$2.compareRangesUsingStarts); return candidates[0]; } static moveWordPartLeft(wordSeparators2, model, position, hasMulticursor) { const candidates = enforceDefined([ WordOperations.moveWordLeft(wordSeparators2, model, position, 0, hasMulticursor), WordOperations.moveWordLeft(wordSeparators2, model, position, 2, hasMulticursor), WordOperations._moveWordPartLeft(model, position) ]); candidates.sort(Position$1.compare); return candidates[2]; } static moveWordPartRight(wordSeparators2, model, position) { const candidates = enforceDefined([ WordOperations.moveWordRight( wordSeparators2, model, position, 0 /* WordNavigationType.WordStart */ ), WordOperations.moveWordRight( wordSeparators2, model, position, 2 /* WordNavigationType.WordEnd */ ), WordOperations._moveWordPartRight(model, position) ]); candidates.sort(Position$1.compare); return candidates[0]; } } function enforceDefined(arr) { return arr.filter((el) => Boolean(el)); } function deepClone(obj) { if (!obj || typeof obj !== "object") { return obj; } if (obj instanceof RegExp) { return obj; } const result = Array.isArray(obj) ? [] : {}; Object.entries(obj).forEach(([key, value]) => { result[key] = value && typeof value === "object" ? deepClone(value) : value; }); return result; } function deepFreeze(obj) { if (!obj || typeof obj !== "object") { return obj; } const stack = [obj]; while (stack.length > 0) { const obj2 = stack.shift(); Object.freeze(obj2); for (const key in obj2) { if (_hasOwnProperty.call(obj2, key)) { const prop = obj2[key]; if (typeof prop === "object" && !Object.isFrozen(prop) && !isTypedArray(prop)) { stack.push(prop); } } } } return obj; } const _hasOwnProperty = Object.prototype.hasOwnProperty; function cloneAndChange(obj, changer) { return _cloneAndChange(obj, changer, /* @__PURE__ */ new Set()); } function _cloneAndChange(obj, changer, seen) { if (isUndefinedOrNull(obj)) { return obj; } const changed = changer(obj); if (typeof changed !== "undefined") { return changed; } if (Array.isArray(obj)) { const r1 = []; for (const e of obj) { r1.push(_cloneAndChange(e, changer, seen)); } return r1; } if (isObject(obj)) { if (seen.has(obj)) { throw new Error("Cannot clone recursive data-structure"); } seen.add(obj); const r2 = {}; for (const i2 in obj) { if (_hasOwnProperty.call(obj, i2)) { r2[i2] = _cloneAndChange(obj[i2], changer, seen); } } seen.delete(obj); return r2; } return obj; } function mixin(destination, source, overwrite = true) { if (!isObject(destination)) { return source; } if (isObject(source)) { Object.keys(source).forEach((key) => { if (key in destination) { if (overwrite) { if (isObject(destination[key]) && isObject(source[key])) { mixin(destination[key], source[key], overwrite); } else { destination[key] = source[key]; } } } else { destination[key] = source[key]; } }); } return destination; } function equals(one, other) { if (one === other) { return true; } if (one === null || one === void 0 || other === null || other === void 0) { return false; } if (typeof one !== typeof other) { return false; } if (typeof one !== "object") { return false; } if (Array.isArray(one) !== Array.isArray(other)) { return false; } let i2; let key; if (Array.isArray(one)) { if (one.length !== other.length) { return false; } for (i2 = 0; i2 < one.length; i2++) { if (!equals(one[i2], other[i2])) { return false; } } } else { const oneKeys = []; for (key in one) { oneKeys.push(key); } oneKeys.sort(); const otherKeys = []; for (key in other) { otherKeys.push(key); } otherKeys.sort(); if (!equals(oneKeys, otherKeys)) { return false; } for (i2 = 0; i2 < oneKeys.length; i2++) { if (!equals(one[oneKeys[i2]], other[oneKeys[i2]])) { return false; } } } return true; } var OverviewRulerLane$1; (function(OverviewRulerLane2) { OverviewRulerLane2[OverviewRulerLane2["Left"] = 1] = "Left"; OverviewRulerLane2[OverviewRulerLane2["Center"] = 2] = "Center"; OverviewRulerLane2[OverviewRulerLane2["Right"] = 4] = "Right"; OverviewRulerLane2[OverviewRulerLane2["Full"] = 7] = "Full"; })(OverviewRulerLane$1 || (OverviewRulerLane$1 = {})); var GlyphMarginLane$1; (function(GlyphMarginLane2) { GlyphMarginLane2[GlyphMarginLane2["Left"] = 1] = "Left"; GlyphMarginLane2[GlyphMarginLane2["Center"] = 2] = "Center"; GlyphMarginLane2[GlyphMarginLane2["Right"] = 3] = "Right"; })(GlyphMarginLane$1 || (GlyphMarginLane$1 = {})); var TextDirection$1; (function(TextDirection2) { TextDirection2[TextDirection2["LTR"] = 0] = "LTR"; TextDirection2[TextDirection2["RTL"] = 1] = "RTL"; })(TextDirection$1 || (TextDirection$1 = {})); var InjectedTextCursorStops$1; (function(InjectedTextCursorStops2) { InjectedTextCursorStops2[InjectedTextCursorStops2["Both"] = 0] = "Both"; InjectedTextCursorStops2[InjectedTextCursorStops2["Right"] = 1] = "Right"; InjectedTextCursorStops2[InjectedTextCursorStops2["Left"] = 2] = "Left"; InjectedTextCursorStops2[InjectedTextCursorStops2["None"] = 3] = "None"; })(InjectedTextCursorStops$1 || (InjectedTextCursorStops$1 = {})); class TextModelResolvedOptions { get originalIndentSize() { return this._indentSizeIsTabSize ? "tabSize" : this.indentSize; } /** * @internal */ constructor(src) { this._textModelResolvedOptionsBrand = void 0; this.tabSize = Math.max(1, src.tabSize | 0); if (src.indentSize === "tabSize") { this.indentSize = this.tabSize; this._indentSizeIsTabSize = true; } else { this.indentSize = Math.max(1, src.indentSize | 0); this._indentSizeIsTabSize = false; } this.insertSpaces = Boolean(src.insertSpaces); this.defaultEOL = src.defaultEOL | 0; this.trimAutoWhitespace = Boolean(src.trimAutoWhitespace); this.bracketPairColorizationOptions = src.bracketPairColorizationOptions; } /** * @internal */ equals(other) { return this.tabSize === other.tabSize && this._indentSizeIsTabSize === other._indentSizeIsTabSize && this.indentSize === other.indentSize && this.insertSpaces === other.insertSpaces && this.defaultEOL === other.defaultEOL && this.trimAutoWhitespace === other.trimAutoWhitespace && equals(this.bracketPairColorizationOptions, other.bracketPairColorizationOptions); } /** * @internal */ createChangeEvent(newOpts) { return { tabSize: this.tabSize !== newOpts.tabSize, indentSize: this.indentSize !== newOpts.indentSize, insertSpaces: this.insertSpaces !== newOpts.insertSpaces, trimAutoWhitespace: this.trimAutoWhitespace !== newOpts.trimAutoWhitespace }; } } class FindMatch { /** * @internal */ constructor(range2, matches) { this._findMatchBrand = void 0; this.range = range2; this.matches = matches; } } function isITextSnapshot(obj) { return obj && typeof obj.read === "function"; } class ValidAnnotatedEditOperation { constructor(identifier, range2, text2, forceMoveMarkers, isAutoWhitespaceEdit, _isTracked) { this.identifier = identifier; this.range = range2; this.text = text2; this.forceMoveMarkers = forceMoveMarkers; this.isAutoWhitespaceEdit = isAutoWhitespaceEdit; this._isTracked = _isTracked; } } class SearchData { constructor(regex, wordSeparators2, simpleSearch) { this.regex = regex; this.wordSeparators = wordSeparators2; this.simpleSearch = simpleSearch; } } class ApplyEditsResult { constructor(reverseEdits, changes, trimAutoWhitespaceLineNumbers) { this.reverseEdits = reverseEdits; this.changes = changes; this.trimAutoWhitespaceLineNumbers = trimAutoWhitespaceLineNumbers; } } function shouldSynchronizeModel(model) { return !model.isTooLargeForSyncing() && !model.isForSimpleWidget; } class CursorMoveCommands { static addCursorDown(viewModel, cursors, useLogicalLine) { const result = []; let resultLen = 0; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; result[resultLen++] = new CursorState$1(cursor.modelState, cursor.viewState); if (useLogicalLine) { result[resultLen++] = CursorState$1.fromModelState(MoveOperations.translateDown(viewModel.cursorConfig, viewModel.model, cursor.modelState)); } else { result[resultLen++] = CursorState$1.fromViewState(MoveOperations.translateDown(viewModel.cursorConfig, viewModel, cursor.viewState)); } } return result; } static addCursorUp(viewModel, cursors, useLogicalLine) { const result = []; let resultLen = 0; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; result[resultLen++] = new CursorState$1(cursor.modelState, cursor.viewState); if (useLogicalLine) { result[resultLen++] = CursorState$1.fromModelState(MoveOperations.translateUp(viewModel.cursorConfig, viewModel.model, cursor.modelState)); } else { result[resultLen++] = CursorState$1.fromViewState(MoveOperations.translateUp(viewModel.cursorConfig, viewModel, cursor.viewState)); } } return result; } static moveToBeginningOfLine(viewModel, cursors, inSelectionMode) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; result[i2] = this._moveToLineStart(viewModel, cursor, inSelectionMode); } return result; } static _moveToLineStart(viewModel, cursor, inSelectionMode) { const currentViewStateColumn = cursor.viewState.position.column; const currentModelStateColumn = cursor.modelState.position.column; const isFirstLineOfWrappedLine = currentViewStateColumn === currentModelStateColumn; const currentViewStatelineNumber = cursor.viewState.position.lineNumber; const firstNonBlankColumn = viewModel.getLineFirstNonWhitespaceColumn(currentViewStatelineNumber); const isBeginningOfViewLine = currentViewStateColumn === firstNonBlankColumn; if (!isFirstLineOfWrappedLine && !isBeginningOfViewLine) { return this._moveToLineStartByView(viewModel, cursor, inSelectionMode); } else { return this._moveToLineStartByModel(viewModel, cursor, inSelectionMode); } } static _moveToLineStartByView(viewModel, cursor, inSelectionMode) { return CursorState$1.fromViewState(MoveOperations.moveToBeginningOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode)); } static _moveToLineStartByModel(viewModel, cursor, inSelectionMode) { return CursorState$1.fromModelState(MoveOperations.moveToBeginningOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)); } static moveToEndOfLine(viewModel, cursors, inSelectionMode, sticky) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; result[i2] = this._moveToLineEnd(viewModel, cursor, inSelectionMode, sticky); } return result; } static _moveToLineEnd(viewModel, cursor, inSelectionMode, sticky) { const viewStatePosition = cursor.viewState.position; const viewModelMaxColumn = viewModel.getLineMaxColumn(viewStatePosition.lineNumber); const isEndOfViewLine = viewStatePosition.column === viewModelMaxColumn; const modelStatePosition = cursor.modelState.position; const modelMaxColumn = viewModel.model.getLineMaxColumn(modelStatePosition.lineNumber); const isEndLineOfWrappedLine = viewModelMaxColumn - viewStatePosition.column === modelMaxColumn - modelStatePosition.column; if (isEndOfViewLine || isEndLineOfWrappedLine) { return this._moveToLineEndByModel(viewModel, cursor, inSelectionMode, sticky); } else { return this._moveToLineEndByView(viewModel, cursor, inSelectionMode, sticky); } } static _moveToLineEndByView(viewModel, cursor, inSelectionMode, sticky) { return CursorState$1.fromViewState(MoveOperations.moveToEndOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, sticky)); } static _moveToLineEndByModel(viewModel, cursor, inSelectionMode, sticky) { return CursorState$1.fromModelState(MoveOperations.moveToEndOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, sticky)); } static expandLineSelection(viewModel, cursors) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; const startLineNumber = cursor.modelState.selection.startLineNumber; const lineCount = viewModel.model.getLineCount(); let endLineNumber = cursor.modelState.selection.endLineNumber; let endColumn; if (endLineNumber === lineCount) { endColumn = viewModel.model.getLineMaxColumn(lineCount); } else { endLineNumber++; endColumn = 1; } result[i2] = CursorState$1.fromModelState(new SingleCursorState(new Range$2(startLineNumber, 1, startLineNumber, 1), 0, 0, new Position$1(endLineNumber, endColumn), 0)); } return result; } static moveToBeginningOfBuffer(viewModel, cursors, inSelectionMode) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; result[i2] = CursorState$1.fromModelState(MoveOperations.moveToBeginningOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)); } return result; } static moveToEndOfBuffer(viewModel, cursors, inSelectionMode) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; result[i2] = CursorState$1.fromModelState(MoveOperations.moveToEndOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)); } return result; } static selectAll(viewModel, cursor) { const lineCount = viewModel.model.getLineCount(); const maxColumn = viewModel.model.getLineMaxColumn(lineCount); return CursorState$1.fromModelState(new SingleCursorState(new Range$2(1, 1, 1, 1), 0, 0, new Position$1(lineCount, maxColumn), 0)); } static line(viewModel, cursor, inSelectionMode, _position, _viewPosition) { const position = viewModel.model.validatePosition(_position); const viewPosition = _viewPosition ? viewModel.coordinatesConverter.validateViewPosition(new Position$1(_viewPosition.lineNumber, _viewPosition.column), position) : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position); if (!inSelectionMode) { const lineCount = viewModel.model.getLineCount(); let selectToLineNumber = position.lineNumber + 1; let selectToColumn = 1; if (selectToLineNumber > lineCount) { selectToLineNumber = lineCount; selectToColumn = viewModel.model.getLineMaxColumn(selectToLineNumber); } return CursorState$1.fromModelState(new SingleCursorState(new Range$2(position.lineNumber, 1, selectToLineNumber, selectToColumn), 2, 0, new Position$1(selectToLineNumber, selectToColumn), 0)); } const enteringLineNumber = cursor.modelState.selectionStart.getStartPosition().lineNumber; if (position.lineNumber < enteringLineNumber) { return CursorState$1.fromViewState(cursor.viewState.move(true, viewPosition.lineNumber, 1, 0)); } else if (position.lineNumber > enteringLineNumber) { const lineCount = viewModel.getLineCount(); let selectToViewLineNumber = viewPosition.lineNumber + 1; let selectToViewColumn = 1; if (selectToViewLineNumber > lineCount) { selectToViewLineNumber = lineCount; selectToViewColumn = viewModel.getLineMaxColumn(selectToViewLineNumber); } return CursorState$1.fromViewState(cursor.viewState.move(true, selectToViewLineNumber, selectToViewColumn, 0)); } else { const endPositionOfSelectionStart = cursor.modelState.selectionStart.getEndPosition(); return CursorState$1.fromModelState(cursor.modelState.move(true, endPositionOfSelectionStart.lineNumber, endPositionOfSelectionStart.column, 0)); } } static word(viewModel, cursor, inSelectionMode, _position) { const position = viewModel.model.validatePosition(_position); return CursorState$1.fromModelState(WordOperations.word(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, position)); } static cancelSelection(viewModel, cursor) { if (!cursor.modelState.hasSelection()) { return new CursorState$1(cursor.modelState, cursor.viewState); } const lineNumber = cursor.viewState.position.lineNumber; const column = cursor.viewState.position.column; return CursorState$1.fromViewState(new SingleCursorState(new Range$2(lineNumber, column, lineNumber, column), 0, 0, new Position$1(lineNumber, column), 0)); } static moveTo(viewModel, cursor, inSelectionMode, _position, _viewPosition) { if (inSelectionMode) { if (cursor.modelState.selectionStartKind === 1) { return this.word(viewModel, cursor, inSelectionMode, _position); } if (cursor.modelState.selectionStartKind === 2) { return this.line(viewModel, cursor, inSelectionMode, _position, _viewPosition); } } const position = viewModel.model.validatePosition(_position); const viewPosition = _viewPosition ? viewModel.coordinatesConverter.validateViewPosition(new Position$1(_viewPosition.lineNumber, _viewPosition.column), position) : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position); return CursorState$1.fromViewState(cursor.viewState.move(inSelectionMode, viewPosition.lineNumber, viewPosition.column, 0)); } static simpleMove(viewModel, cursors, direction, inSelectionMode, value, unit) { switch (direction) { case 0: { if (unit === 4) { return this._moveHalfLineLeft(viewModel, cursors, inSelectionMode); } else { return this._moveLeft(viewModel, cursors, inSelectionMode, value); } } case 1: { if (unit === 4) { return this._moveHalfLineRight(viewModel, cursors, inSelectionMode); } else { return this._moveRight(viewModel, cursors, inSelectionMode, value); } } case 2: { if (unit === 2) { return this._moveUpByViewLines(viewModel, cursors, inSelectionMode, value); } else { return this._moveUpByModelLines(viewModel, cursors, inSelectionMode, value); } } case 3: { if (unit === 2) { return this._moveDownByViewLines(viewModel, cursors, inSelectionMode, value); } else { return this._moveDownByModelLines(viewModel, cursors, inSelectionMode, value); } } case 4: { if (unit === 2) { return cursors.map((cursor) => CursorState$1.fromViewState(MoveOperations.moveToPrevBlankLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode))); } else { return cursors.map((cursor) => CursorState$1.fromModelState(MoveOperations.moveToPrevBlankLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode))); } } case 5: { if (unit === 2) { return cursors.map((cursor) => CursorState$1.fromViewState(MoveOperations.moveToNextBlankLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode))); } else { return cursors.map((cursor) => CursorState$1.fromModelState(MoveOperations.moveToNextBlankLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode))); } } case 6: { return this._moveToViewMinColumn(viewModel, cursors, inSelectionMode); } case 7: { return this._moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode); } case 8: { return this._moveToViewCenterColumn(viewModel, cursors, inSelectionMode); } case 9: { return this._moveToViewMaxColumn(viewModel, cursors, inSelectionMode); } case 10: { return this._moveToViewLastNonWhitespaceColumn(viewModel, cursors, inSelectionMode); } default: return null; } } static viewportMove(viewModel, cursors, direction, inSelectionMode, value) { const visibleViewRange = viewModel.getCompletelyVisibleViewRange(); const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange); switch (direction) { case 11: { const modelLineNumber = this._firstLineNumberInRange(viewModel.model, visibleModelRange, value); const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber); return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)]; } case 13: { const modelLineNumber = this._lastLineNumberInRange(viewModel.model, visibleModelRange, value); const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber); return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)]; } case 12: { const modelLineNumber = Math.round((visibleModelRange.startLineNumber + visibleModelRange.endLineNumber) / 2); const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber); return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)]; } case 14: { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; result[i2] = this.findPositionInViewportIfOutside(viewModel, cursor, visibleViewRange, inSelectionMode); } return result; } default: return null; } } static findPositionInViewportIfOutside(viewModel, cursor, visibleViewRange, inSelectionMode) { const viewLineNumber = cursor.viewState.position.lineNumber; if (visibleViewRange.startLineNumber <= viewLineNumber && viewLineNumber <= visibleViewRange.endLineNumber - 1) { return new CursorState$1(cursor.modelState, cursor.viewState); } else { let newViewLineNumber; if (viewLineNumber > visibleViewRange.endLineNumber - 1) { newViewLineNumber = visibleViewRange.endLineNumber - 1; } else if (viewLineNumber < visibleViewRange.startLineNumber) { newViewLineNumber = visibleViewRange.startLineNumber; } else { newViewLineNumber = viewLineNumber; } const position = MoveOperations.vertical(viewModel.cursorConfig, viewModel, viewLineNumber, cursor.viewState.position.column, cursor.viewState.leftoverVisibleColumns, newViewLineNumber, false); return CursorState$1.fromViewState(cursor.viewState.move(inSelectionMode, position.lineNumber, position.column, position.leftoverVisibleColumns)); } } /** * Find the nth line start included in the range (from the start). */ static _firstLineNumberInRange(model, range2, count) { let startLineNumber = range2.startLineNumber; if (range2.startColumn !== model.getLineMinColumn(startLineNumber)) { startLineNumber++; } return Math.min(range2.endLineNumber, startLineNumber + count - 1); } /** * Find the nth line start included in the range (from the end). */ static _lastLineNumberInRange(model, range2, count) { let startLineNumber = range2.startLineNumber; if (range2.startColumn !== model.getLineMinColumn(startLineNumber)) { startLineNumber++; } return Math.max(startLineNumber, range2.endLineNumber - count + 1); } static _moveLeft(viewModel, cursors, inSelectionMode, noOfColumns) { return cursors.map((cursor) => { const direction = viewModel.getTextDirection(cursor.viewState.position.lineNumber); const isRtl = direction === TextDirection$1.RTL; return CursorState$1.fromViewState(isRtl ? MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns) : MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns)); }); } static _moveHalfLineLeft(viewModel, cursors, inSelectionMode) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; const viewLineNumber = cursor.viewState.position.lineNumber; const halfLine = Math.round(viewModel.getLineLength(viewLineNumber) / 2); result[i2] = CursorState$1.fromViewState(MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine)); } return result; } static _moveRight(viewModel, cursors, inSelectionMode, noOfColumns) { return cursors.map((cursor) => { const direction = viewModel.getTextDirection(cursor.viewState.position.lineNumber); const isRtl = direction === TextDirection$1.RTL; return CursorState$1.fromViewState(isRtl ? MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns) : MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns)); }); } static _moveHalfLineRight(viewModel, cursors, inSelectionMode) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; const viewLineNumber = cursor.viewState.position.lineNumber; const halfLine = Math.round(viewModel.getLineLength(viewLineNumber) / 2); result[i2] = CursorState$1.fromViewState(MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine)); } return result; } static _moveDownByViewLines(viewModel, cursors, inSelectionMode, linesCount) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; result[i2] = CursorState$1.fromViewState(MoveOperations.moveDown(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount)); } return result; } static _moveDownByModelLines(viewModel, cursors, inSelectionMode, linesCount) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; result[i2] = CursorState$1.fromModelState(MoveOperations.moveDown(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount)); } return result; } static _moveUpByViewLines(viewModel, cursors, inSelectionMode, linesCount) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; result[i2] = CursorState$1.fromViewState(MoveOperations.moveUp(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount)); } return result; } static _moveUpByModelLines(viewModel, cursors, inSelectionMode, linesCount) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; result[i2] = CursorState$1.fromModelState(MoveOperations.moveUp(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount)); } return result; } static _moveToViewPosition(viewModel, cursor, inSelectionMode, toViewLineNumber, toViewColumn) { return CursorState$1.fromViewState(cursor.viewState.move(inSelectionMode, toViewLineNumber, toViewColumn, 0)); } static _moveToModelPosition(viewModel, cursor, inSelectionMode, toModelLineNumber, toModelColumn) { return CursorState$1.fromModelState(cursor.modelState.move(inSelectionMode, toModelLineNumber, toModelColumn, 0)); } static _moveToViewMinColumn(viewModel, cursors, inSelectionMode) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; const viewLineNumber = cursor.viewState.position.lineNumber; const viewColumn = viewModel.getLineMinColumn(viewLineNumber); result[i2] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; } static _moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; const viewLineNumber = cursor.viewState.position.lineNumber; const viewColumn = viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber); result[i2] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; } static _moveToViewCenterColumn(viewModel, cursors, inSelectionMode) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; const viewLineNumber = cursor.viewState.position.lineNumber; const viewColumn = Math.round((viewModel.getLineMaxColumn(viewLineNumber) + viewModel.getLineMinColumn(viewLineNumber)) / 2); result[i2] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; } static _moveToViewMaxColumn(viewModel, cursors, inSelectionMode) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; const viewLineNumber = cursor.viewState.position.lineNumber; const viewColumn = viewModel.getLineMaxColumn(viewLineNumber); result[i2] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; } static _moveToViewLastNonWhitespaceColumn(viewModel, cursors, inSelectionMode) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; const viewLineNumber = cursor.viewState.position.lineNumber; const viewColumn = viewModel.getLineLastNonWhitespaceColumn(viewLineNumber); result[i2] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn); } return result; } } var CursorMove; (function(CursorMove2) { const isCursorMoveArgs = function(arg) { if (!isObject(arg)) { return false; } const cursorMoveArg = arg; if (!isString$1(cursorMoveArg.to)) { return false; } if (!isUndefined(cursorMoveArg.select) && !isBoolean(cursorMoveArg.select)) { return false; } if (!isUndefined(cursorMoveArg.by) && !isString$1(cursorMoveArg.by)) { return false; } if (!isUndefined(cursorMoveArg.value) && !isNumber$1(cursorMoveArg.value)) { return false; } return true; }; CursorMove2.metadata = { description: "Move cursor to a logical position in the view", args: [ { name: "Cursor move argument object", description: `Property-value pairs that can be passed through this argument: * 'to': A mandatory logical position value providing where to move the cursor. \`\`\` 'left', 'right', 'up', 'down', 'prevBlankLine', 'nextBlankLine', 'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter' 'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter' 'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside' \`\`\` * 'by': Unit to move. Default is computed based on 'to' value. \`\`\` 'line', 'wrappedLine', 'character', 'halfLine' \`\`\` * 'value': Number of units to move. Default is '1'. * 'select': If 'true' makes the selection. Default is 'false'. `, constraint: isCursorMoveArgs, schema: { "type": "object", "required": ["to"], "properties": { "to": { "type": "string", "enum": ["left", "right", "up", "down", "prevBlankLine", "nextBlankLine", "wrappedLineStart", "wrappedLineEnd", "wrappedLineColumnCenter", "wrappedLineFirstNonWhitespaceCharacter", "wrappedLineLastNonWhitespaceCharacter", "viewPortTop", "viewPortCenter", "viewPortBottom", "viewPortIfOutside"] }, "by": { "type": "string", "enum": ["line", "wrappedLine", "character", "halfLine"] }, "value": { "type": "number", "default": 1 }, "select": { "type": "boolean", "default": false } } } } ] }; CursorMove2.RawDirection = { Left: "left", Right: "right", Up: "up", Down: "down", PrevBlankLine: "prevBlankLine", NextBlankLine: "nextBlankLine", WrappedLineStart: "wrappedLineStart", WrappedLineFirstNonWhitespaceCharacter: "wrappedLineFirstNonWhitespaceCharacter", WrappedLineColumnCenter: "wrappedLineColumnCenter", WrappedLineEnd: "wrappedLineEnd", WrappedLineLastNonWhitespaceCharacter: "wrappedLineLastNonWhitespaceCharacter", ViewPortTop: "viewPortTop", ViewPortCenter: "viewPortCenter", ViewPortBottom: "viewPortBottom", ViewPortIfOutside: "viewPortIfOutside" }; CursorMove2.RawUnit = { Line: "line", WrappedLine: "wrappedLine", Character: "character", HalfLine: "halfLine" }; function parse2(args) { if (!args.to) { return null; } let direction; switch (args.to) { case CursorMove2.RawDirection.Left: direction = 0; break; case CursorMove2.RawDirection.Right: direction = 1; break; case CursorMove2.RawDirection.Up: direction = 2; break; case CursorMove2.RawDirection.Down: direction = 3; break; case CursorMove2.RawDirection.PrevBlankLine: direction = 4; break; case CursorMove2.RawDirection.NextBlankLine: direction = 5; break; case CursorMove2.RawDirection.WrappedLineStart: direction = 6; break; case CursorMove2.RawDirection.WrappedLineFirstNonWhitespaceCharacter: direction = 7; break; case CursorMove2.RawDirection.WrappedLineColumnCenter: direction = 8; break; case CursorMove2.RawDirection.WrappedLineEnd: direction = 9; break; case CursorMove2.RawDirection.WrappedLineLastNonWhitespaceCharacter: direction = 10; break; case CursorMove2.RawDirection.ViewPortTop: direction = 11; break; case CursorMove2.RawDirection.ViewPortBottom: direction = 13; break; case CursorMove2.RawDirection.ViewPortCenter: direction = 12; break; case CursorMove2.RawDirection.ViewPortIfOutside: direction = 14; break; default: return null; } let unit = 0; switch (args.by) { case CursorMove2.RawUnit.Line: unit = 1; break; case CursorMove2.RawUnit.WrappedLine: unit = 2; break; case CursorMove2.RawUnit.Character: unit = 3; break; case CursorMove2.RawUnit.HalfLine: unit = 4; break; } return { direction, unit, select: !!args.select, value: args.value || 1 }; } CursorMove2.parse = parse2; })(CursorMove || (CursorMove = {})); var IndentAction$1; (function(IndentAction2) { IndentAction2[IndentAction2["None"] = 0] = "None"; IndentAction2[IndentAction2["Indent"] = 1] = "Indent"; IndentAction2[IndentAction2["IndentOutdent"] = 2] = "IndentOutdent"; IndentAction2[IndentAction2["Outdent"] = 3] = "Outdent"; })(IndentAction$1 || (IndentAction$1 = {})); class StandardAutoClosingPairConditional { constructor(source) { this._neutralCharacter = null; this._neutralCharacterSearched = false; this.open = source.open; this.close = source.close; this._inString = true; this._inComment = true; this._inRegEx = true; if (Array.isArray(source.notIn)) { for (let i2 = 0, len = source.notIn.length; i2 < len; i2++) { const notIn = source.notIn[i2]; switch (notIn) { case "string": this._inString = false; break; case "comment": this._inComment = false; break; case "regex": this._inRegEx = false; break; } } } } isOK(standardToken) { switch (standardToken) { case 0: return true; case 1: return this._inComment; case 2: return this._inString; case 3: return this._inRegEx; } } shouldAutoClose(context, column) { if (context.getTokenCount() === 0) { return true; } const tokenIndex = context.findTokenIndexAtOffset(column - 2); const standardTokenType = context.getStandardTokenType(tokenIndex); return this.isOK(standardTokenType); } _findNeutralCharacterInRange(fromCharCode, toCharCode) { for (let charCode = fromCharCode; charCode <= toCharCode; charCode++) { const character = String.fromCharCode(charCode); if (!this.open.includes(character) && !this.close.includes(character)) { return character; } } return null; } /** * Find a character in the range [0-9a-zA-Z] that does not appear in the open or close */ findNeutralCharacter() { if (!this._neutralCharacterSearched) { this._neutralCharacterSearched = true; if (!this._neutralCharacter) { this._neutralCharacter = this._findNeutralCharacterInRange( 48, 57 /* CharCode.Digit9 */ ); } if (!this._neutralCharacter) { this._neutralCharacter = this._findNeutralCharacterInRange( 97, 122 /* CharCode.z */ ); } if (!this._neutralCharacter) { this._neutralCharacter = this._findNeutralCharacterInRange( 65, 90 /* CharCode.Z */ ); } } return this._neutralCharacter; } } class AutoClosingPairs { constructor(autoClosingPairs) { this.autoClosingPairsOpenByStart = /* @__PURE__ */ new Map(); this.autoClosingPairsOpenByEnd = /* @__PURE__ */ new Map(); this.autoClosingPairsCloseByStart = /* @__PURE__ */ new Map(); this.autoClosingPairsCloseByEnd = /* @__PURE__ */ new Map(); this.autoClosingPairsCloseSingleChar = /* @__PURE__ */ new Map(); for (const pair of autoClosingPairs) { appendEntry(this.autoClosingPairsOpenByStart, pair.open.charAt(0), pair); appendEntry(this.autoClosingPairsOpenByEnd, pair.open.charAt(pair.open.length - 1), pair); appendEntry(this.autoClosingPairsCloseByStart, pair.close.charAt(0), pair); appendEntry(this.autoClosingPairsCloseByEnd, pair.close.charAt(pair.close.length - 1), pair); if (pair.close.length === 1 && pair.open.length === 1) { appendEntry(this.autoClosingPairsCloseSingleChar, pair.close, pair); } } } } function appendEntry(target, key, value) { if (target.has(key)) { target.get(key).push(value); } else { target.set(key, [value]); } } const USUAL_WORD_SEPARATORS = "`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?"; function createWordRegExp(allowInWords = "") { let source = "(-?\\d*\\.\\d\\w*)|([^"; for (const sep2 of USUAL_WORD_SEPARATORS) { if (allowInWords.indexOf(sep2) >= 0) { continue; } source += "\\" + sep2; } source += "\\s]+)"; return new RegExp(source, "g"); } const DEFAULT_WORD_REGEXP = createWordRegExp(); function ensureValidWordDefinition(wordDefinition) { let result = DEFAULT_WORD_REGEXP; if (wordDefinition && wordDefinition instanceof RegExp) { if (!wordDefinition.global) { let flags = "g"; if (wordDefinition.ignoreCase) { flags += "i"; } if (wordDefinition.multiline) { flags += "m"; } if (wordDefinition.unicode) { flags += "u"; } result = new RegExp(wordDefinition.source, flags); } else { result = wordDefinition; } } result.lastIndex = 0; return result; } const _defaultConfig = new LinkedList(); _defaultConfig.unshift({ maxLen: 1e3, windowSize: 15, timeBudget: 150 }); function getWordAtText(column, wordDefinition, text2, textOffset, config) { wordDefinition = ensureValidWordDefinition(wordDefinition); if (!config) { config = Iterable.first(_defaultConfig); } if (text2.length > config.maxLen) { let start = column - config.maxLen / 2; if (start < 0) { start = 0; } else { textOffset += start; } text2 = text2.substring(start, column + config.maxLen / 2); return getWordAtText(column, wordDefinition, text2, textOffset, config); } const t1 = Date.now(); const pos = column - 1 - textOffset; let prevRegexIndex = -1; let match2 = null; for (let i2 = 1; ; i2++) { if (Date.now() - t1 >= config.timeBudget) { break; } const regexIndex = pos - config.windowSize * i2; wordDefinition.lastIndex = Math.max(0, regexIndex); const thisMatch = _findRegexMatchEnclosingPosition(wordDefinition, text2, pos, prevRegexIndex); if (!thisMatch && match2) { break; } match2 = thisMatch; if (regexIndex <= 0) { break; } prevRegexIndex = regexIndex; } if (match2) { const result = { word: match2[0], startColumn: textOffset + 1 + match2.index, endColumn: textOffset + 1 + match2.index + match2[0].length }; wordDefinition.lastIndex = 0; return result; } return null; } function _findRegexMatchEnclosingPosition(wordDefinition, text2, pos, stopPos) { let match2; while (match2 = wordDefinition.exec(text2)) { const matchIndex = match2.index || 0; if (matchIndex <= pos && wordDefinition.lastIndex >= pos) { return match2; } else if (stopPos > 0 && matchIndex > stopPos) { return null; } } return null; } const _CharacterPairSupport = class _CharacterPairSupport { constructor(config) { if (config.autoClosingPairs) { this._autoClosingPairs = config.autoClosingPairs.map((el) => new StandardAutoClosingPairConditional(el)); } else if (config.brackets) { this._autoClosingPairs = config.brackets.map((b) => new StandardAutoClosingPairConditional({ open: b[0], close: b[1] })); } else { this._autoClosingPairs = []; } if (config.__electricCharacterSupport && config.__electricCharacterSupport.docComment) { const docComment = config.__electricCharacterSupport.docComment; this._autoClosingPairs.push(new StandardAutoClosingPairConditional({ open: docComment.open, close: docComment.close || "" })); } this._autoCloseBeforeForQuotes = typeof config.autoCloseBefore === "string" ? config.autoCloseBefore : _CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_QUOTES; this._autoCloseBeforeForBrackets = typeof config.autoCloseBefore === "string" ? config.autoCloseBefore : _CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_BRACKETS; this._surroundingPairs = config.surroundingPairs || this._autoClosingPairs; } getAutoClosingPairs() { return this._autoClosingPairs; } getAutoCloseBeforeSet(forQuotes) { return forQuotes ? this._autoCloseBeforeForQuotes : this._autoCloseBeforeForBrackets; } getSurroundingPairs() { return this._surroundingPairs; } }; _CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_QUOTES = ";:.,=}])> \n "; _CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_BRACKETS = "'\"`;:.,=}])> \n "; let CharacterPairSupport = _CharacterPairSupport; let _utf16LE_TextDecoder; function getUTF16LE_TextDecoder() { if (!_utf16LE_TextDecoder) { _utf16LE_TextDecoder = new TextDecoder("UTF-16LE"); } return _utf16LE_TextDecoder; } let _utf16BE_TextDecoder; function getUTF16BE_TextDecoder() { if (!_utf16BE_TextDecoder) { _utf16BE_TextDecoder = new TextDecoder("UTF-16BE"); } return _utf16BE_TextDecoder; } let _platformTextDecoder; function getPlatformTextDecoder() { if (!_platformTextDecoder) { _platformTextDecoder = isLittleEndian() ? getUTF16LE_TextDecoder() : getUTF16BE_TextDecoder(); } return _platformTextDecoder; } function decodeUTF16LE(source, offset, len) { const view = new Uint16Array(source.buffer, offset, len); if (len > 0 && (view[0] === 65279 || view[0] === 65534)) { return compatDecodeUTF16LE(source, offset, len); } return getUTF16LE_TextDecoder().decode(view); } function compatDecodeUTF16LE(source, offset, len) { const result = []; let resultLen = 0; for (let i2 = 0; i2 < len; i2++) { const charCode = readUInt16LE(source, offset); offset += 2; result[resultLen++] = String.fromCharCode(charCode); } return result.join(""); } class StringBuilder { constructor(capacity) { this._capacity = capacity | 0; this._buffer = new Uint16Array(this._capacity); this._completedStrings = null; this._bufferLength = 0; } reset() { this._completedStrings = null; this._bufferLength = 0; } build() { if (this._completedStrings !== null) { this._flushBuffer(); return this._completedStrings.join(""); } return this._buildBuffer(); } _buildBuffer() { if (this._bufferLength === 0) { return ""; } const view = new Uint16Array(this._buffer.buffer, 0, this._bufferLength); return getPlatformTextDecoder().decode(view); } _flushBuffer() { const bufferString = this._buildBuffer(); this._bufferLength = 0; if (this._completedStrings === null) { this._completedStrings = [bufferString]; } else { this._completedStrings[this._completedStrings.length] = bufferString; } } /** * Append a char code (<2^16) */ appendCharCode(charCode) { const remainingSpace = this._capacity - this._bufferLength; if (remainingSpace <= 1) { if (remainingSpace === 0 || isHighSurrogate(charCode)) { this._flushBuffer(); } } this._buffer[this._bufferLength++] = charCode; } /** * Append an ASCII char code (<2^8) */ appendASCIICharCode(charCode) { if (this._bufferLength === this._capacity) { this._flushBuffer(); } this._buffer[this._bufferLength++] = charCode; } appendString(str) { const strLen = str.length; if (this._bufferLength + strLen >= this._capacity) { this._flushBuffer(); this._completedStrings[this._completedStrings.length] = str; return; } for (let i2 = 0; i2 < strLen; i2++) { this._buffer[this._bufferLength++] = str.charCodeAt(i2); } } } class RichEditBracket { constructor(languageId, index, open, close, forwardRegex, reversedRegex) { this._richEditBracketBrand = void 0; this.languageId = languageId; this.index = index; this.open = open; this.close = close; this.forwardRegex = forwardRegex; this.reversedRegex = reversedRegex; this._openSet = RichEditBracket._toSet(this.open); this._closeSet = RichEditBracket._toSet(this.close); } /** * Check if the provided `text` is an open bracket in this group. */ isOpen(text2) { return this._openSet.has(text2); } /** * Check if the provided `text` is a close bracket in this group. */ isClose(text2) { return this._closeSet.has(text2); } static _toSet(arr) { const result = /* @__PURE__ */ new Set(); for (const element of arr) { result.add(element); } return result; } } function groupFuzzyBrackets(brackets) { const N = brackets.length; brackets = brackets.map((b) => [b[0].toLowerCase(), b[1].toLowerCase()]); const group = []; for (let i2 = 0; i2 < N; i2++) { group[i2] = i2; } const areOverlapping = (a, b) => { const [aOpen, aClose] = a; const [bOpen, bClose] = b; return aOpen === bOpen || aOpen === bClose || aClose === bOpen || aClose === bClose; }; const mergeGroups = (g1, g2) => { const newG = Math.min(g1, g2); const oldG = Math.max(g1, g2); for (let i2 = 0; i2 < N; i2++) { if (group[i2] === oldG) { group[i2] = newG; } } }; for (let i2 = 0; i2 < N; i2++) { const a = brackets[i2]; for (let j = i2 + 1; j < N; j++) { const b = brackets[j]; if (areOverlapping(a, b)) { mergeGroups(group[i2], group[j]); } } } const result = []; for (let g = 0; g < N; g++) { const currentOpen = []; const currentClose = []; for (let i2 = 0; i2 < N; i2++) { if (group[i2] === g) { const [open, close] = brackets[i2]; currentOpen.push(open); currentClose.push(close); } } if (currentOpen.length > 0) { result.push({ open: currentOpen, close: currentClose }); } } return result; } class RichEditBrackets { constructor(languageId, _brackets) { this._richEditBracketsBrand = void 0; const brackets = groupFuzzyBrackets(_brackets); this.brackets = brackets.map((b, index) => { return new RichEditBracket(languageId, index, b.open, b.close, getRegexForBracketPair(b.open, b.close, brackets, index), getReversedRegexForBracketPair(b.open, b.close, brackets, index)); }); this.forwardRegex = getRegexForBrackets(this.brackets); this.reversedRegex = getReversedRegexForBrackets(this.brackets); this.textIsBracket = {}; this.textIsOpenBracket = {}; this.maxBracketLength = 0; for (const bracket of this.brackets) { for (const open of bracket.open) { this.textIsBracket[open] = bracket; this.textIsOpenBracket[open] = true; this.maxBracketLength = Math.max(this.maxBracketLength, open.length); } for (const close of bracket.close) { this.textIsBracket[close] = bracket; this.textIsOpenBracket[close] = false; this.maxBracketLength = Math.max(this.maxBracketLength, close.length); } } } } function collectSuperstrings(str, brackets, currentIndex, dest) { for (let i2 = 0, len = brackets.length; i2 < len; i2++) { if (i2 === currentIndex) { continue; } const bracket = brackets[i2]; for (const open of bracket.open) { if (open.indexOf(str) >= 0) { dest.push(open); } } for (const close of bracket.close) { if (close.indexOf(str) >= 0) { dest.push(close); } } } } function lengthcmp(a, b) { return a.length - b.length; } function unique(arr) { if (arr.length <= 1) { return arr; } const result = []; const seen = /* @__PURE__ */ new Set(); for (const element of arr) { if (seen.has(element)) { continue; } result.push(element); seen.add(element); } return result; } function getRegexForBracketPair(open, close, brackets, currentIndex) { let pieces = []; pieces = pieces.concat(open); pieces = pieces.concat(close); for (let i2 = 0, len = pieces.length; i2 < len; i2++) { collectSuperstrings(pieces[i2], brackets, currentIndex, pieces); } pieces = unique(pieces); pieces.sort(lengthcmp); pieces.reverse(); return createBracketOrRegExp(pieces); } function getReversedRegexForBracketPair(open, close, brackets, currentIndex) { let pieces = []; pieces = pieces.concat(open); pieces = pieces.concat(close); for (let i2 = 0, len = pieces.length; i2 < len; i2++) { collectSuperstrings(pieces[i2], brackets, currentIndex, pieces); } pieces = unique(pieces); pieces.sort(lengthcmp); pieces.reverse(); return createBracketOrRegExp(pieces.map(toReversedString)); } function getRegexForBrackets(brackets) { let pieces = []; for (const bracket of brackets) { for (const open of bracket.open) { pieces.push(open); } for (const close of bracket.close) { pieces.push(close); } } pieces = unique(pieces); return createBracketOrRegExp(pieces); } function getReversedRegexForBrackets(brackets) { let pieces = []; for (const bracket of brackets) { for (const open of bracket.open) { pieces.push(open); } for (const close of bracket.close) { pieces.push(close); } } pieces = unique(pieces); return createBracketOrRegExp(pieces.map(toReversedString)); } function prepareBracketForRegExp$1(str) { const insertWordBoundaries = /^[\w ]+$/.test(str); str = escapeRegExpCharacters(str); return insertWordBoundaries ? `\\b${str}\\b` : str; } function createBracketOrRegExp(pieces, options) { const regexStr = `(${pieces.map(prepareBracketForRegExp$1).join(")|(")})`; return createRegExp(regexStr, true, options); } const toReversedString = /* @__PURE__ */ (function() { function reverse(str) { const arr = new Uint16Array(str.length); let offset = 0; for (let i2 = str.length - 1; i2 >= 0; i2--) { arr[offset++] = str.charCodeAt(i2); } return getPlatformTextDecoder().decode(arr); } let lastInput = null; let lastOutput = null; return function toReversedString2(str) { if (lastInput !== str) { lastInput = str; lastOutput = reverse(lastInput); } return lastOutput; }; })(); class BracketsUtils { static _findPrevBracketInText(reversedBracketRegex, lineNumber, reversedText, offset) { const m = reversedText.match(reversedBracketRegex); if (!m) { return null; } const matchOffset = reversedText.length - (m.index || 0); const matchLength = m[0].length; const absoluteMatchOffset = offset + matchOffset; return new Range$2(lineNumber, absoluteMatchOffset - matchLength + 1, lineNumber, absoluteMatchOffset + 1); } static findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, startOffset, endOffset) { const reversedLineText = toReversedString(lineText); const reversedSubstr = reversedLineText.substring(lineText.length - endOffset, lineText.length - startOffset); return this._findPrevBracketInText(reversedBracketRegex, lineNumber, reversedSubstr, startOffset); } static findNextBracketInText(bracketRegex, lineNumber, text2, offset) { const m = text2.match(bracketRegex); if (!m) { return null; } const matchOffset = m.index || 0; const matchLength = m[0].length; if (matchLength === 0) { return null; } const absoluteMatchOffset = offset + matchOffset; return new Range$2(lineNumber, absoluteMatchOffset + 1, lineNumber, absoluteMatchOffset + 1 + matchLength); } static findNextBracketInRange(bracketRegex, lineNumber, lineText, startOffset, endOffset) { const substr = lineText.substring(startOffset, endOffset); return this.findNextBracketInText(bracketRegex, lineNumber, substr, startOffset); } } class BracketElectricCharacterSupport { constructor(richEditBrackets) { this._richEditBrackets = richEditBrackets; } getElectricCharacters() { const result = []; if (this._richEditBrackets) { for (const bracket of this._richEditBrackets.brackets) { for (const close of bracket.close) { const lastChar = close.charAt(close.length - 1); result.push(lastChar); } } } return distinct(result); } onElectricCharacter(character, context, column) { if (!this._richEditBrackets || this._richEditBrackets.brackets.length === 0) { return null; } const tokenIndex = context.findTokenIndexAtOffset(column - 1); if (ignoreBracketsInToken(context.getStandardTokenType(tokenIndex))) { return null; } const reversedBracketRegex = this._richEditBrackets.reversedRegex; const text2 = context.getLineContent().substring(0, column - 1) + character; const r = BracketsUtils.findPrevBracketInRange(reversedBracketRegex, 1, text2, 0, text2.length); if (!r) { return null; } const bracketText = text2.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase(); const isOpen = this._richEditBrackets.textIsOpenBracket[bracketText]; if (isOpen) { return null; } const textBeforeBracket = context.getActualLineContentBefore(r.startColumn - 1); if (!/^\s*$/.test(textBeforeBracket)) { return null; } return { matchOpenBracket: bracketText }; } } function resetGlobalRegex(reg) { if (reg.global) { reg.lastIndex = 0; } return true; } class IndentRulesSupport { constructor(indentationRules) { this._indentationRules = indentationRules; } shouldIncrease(text2) { if (this._indentationRules) { if (this._indentationRules.increaseIndentPattern && resetGlobalRegex(this._indentationRules.increaseIndentPattern) && this._indentationRules.increaseIndentPattern.test(text2)) { return true; } } return false; } shouldDecrease(text2) { if (this._indentationRules && this._indentationRules.decreaseIndentPattern && resetGlobalRegex(this._indentationRules.decreaseIndentPattern) && this._indentationRules.decreaseIndentPattern.test(text2)) { return true; } return false; } shouldIndentNextLine(text2) { if (this._indentationRules && this._indentationRules.indentNextLinePattern && resetGlobalRegex(this._indentationRules.indentNextLinePattern) && this._indentationRules.indentNextLinePattern.test(text2)) { return true; } return false; } shouldIgnore(text2) { if (this._indentationRules && this._indentationRules.unIndentedLinePattern && resetGlobalRegex(this._indentationRules.unIndentedLinePattern) && this._indentationRules.unIndentedLinePattern.test(text2)) { return true; } return false; } getIndentMetadata(text2) { let ret = 0; if (this.shouldIncrease(text2)) { ret += 1; } if (this.shouldDecrease(text2)) { ret += 2; } if (this.shouldIndentNextLine(text2)) { ret += 4; } if (this.shouldIgnore(text2)) { ret += 8; } return ret; } } class OnEnterSupport { constructor(opts) { opts = opts || {}; opts.brackets = opts.brackets || [ ["(", ")"], ["{", "}"], ["[", "]"] ]; this._brackets = []; opts.brackets.forEach((bracket) => { const openRegExp = OnEnterSupport._createOpenBracketRegExp(bracket[0]); const closeRegExp = OnEnterSupport._createCloseBracketRegExp(bracket[1]); if (openRegExp && closeRegExp) { this._brackets.push({ open: bracket[0], openRegExp, close: bracket[1], closeRegExp }); } }); this._regExpRules = opts.onEnterRules || []; } onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) { if (autoIndent >= 3) { for (let i2 = 0, len = this._regExpRules.length; i2 < len; i2++) { const rule = this._regExpRules[i2]; const regResult = [{ reg: rule.beforeText, text: beforeEnterText }, { reg: rule.afterText, text: afterEnterText }, { reg: rule.previousLineText, text: previousLineText }].every((obj) => { if (!obj.reg) { return true; } obj.reg.lastIndex = 0; return obj.reg.test(obj.text); }); if (regResult) { return rule.action; } } } if (autoIndent >= 2) { if (beforeEnterText.length > 0 && afterEnterText.length > 0) { for (let i2 = 0, len = this._brackets.length; i2 < len; i2++) { const bracket = this._brackets[i2]; if (bracket.openRegExp.test(beforeEnterText) && bracket.closeRegExp.test(afterEnterText)) { return { indentAction: IndentAction$1.IndentOutdent }; } } } } if (autoIndent >= 2) { if (beforeEnterText.length > 0) { for (let i2 = 0, len = this._brackets.length; i2 < len; i2++) { const bracket = this._brackets[i2]; if (bracket.openRegExp.test(beforeEnterText)) { return { indentAction: IndentAction$1.Indent }; } } } } return null; } static _createOpenBracketRegExp(bracket) { let str = escapeRegExpCharacters(bracket); if (!/\B/.test(str.charAt(0))) { str = "\\b" + str; } str += "\\s*$"; return OnEnterSupport._safeRegExp(str); } static _createCloseBracketRegExp(bracket) { let str = escapeRegExpCharacters(bracket); if (!/\B/.test(str.charAt(str.length - 1))) { str = str + "\\b"; } str = "^\\s*" + str; return OnEnterSupport._safeRegExp(str); } static _safeRegExp(def2) { try { return new RegExp(def2); } catch (err) { onUnexpectedError(err); return null; } } } const IConfigurationService = createDecorator("configurationService"); function toValuesTree(properties, conflictReporter) { const root = /* @__PURE__ */ Object.create(null); for (const key in properties) { addToValueTree(root, key, properties[key], conflictReporter); } return root; } function addToValueTree(settingsTreeRoot, key, value, conflictReporter) { const segments = key.split("."); const last = segments.pop(); let curr = settingsTreeRoot; for (let i2 = 0; i2 < segments.length; i2++) { const s = segments[i2]; let obj = curr[s]; switch (typeof obj) { case "undefined": obj = curr[s] = /* @__PURE__ */ Object.create(null); break; case "object": if (obj === null) { conflictReporter(`Ignoring ${key} as ${segments.slice(0, i2 + 1).join(".")} is null`); return; } break; default: conflictReporter(`Ignoring ${key} as ${segments.slice(0, i2 + 1).join(".")} is ${JSON.stringify(obj)}`); return; } curr = obj; } if (typeof curr === "object" && curr !== null) { try { curr[last] = value; } catch (e) { conflictReporter(`Ignoring ${key} as ${segments.join(".")} is ${JSON.stringify(curr)}`); } } else { conflictReporter(`Ignoring ${key} as ${segments.join(".")} is ${JSON.stringify(curr)}`); } } function removeFromValueTree(valueTree, key) { const segments = key.split("."); doRemoveFromValueTree(valueTree, segments); } function doRemoveFromValueTree(valueTree, segments) { if (!valueTree) { return; } const first2 = segments.shift(); if (segments.length === 0) { delete valueTree[first2]; return; } if (Object.keys(valueTree).indexOf(first2) !== -1) { const value = valueTree[first2]; if (typeof value === "object" && !Array.isArray(value)) { doRemoveFromValueTree(value, segments); if (Object.keys(value).length === 0) { delete valueTree[first2]; } } } } function getConfigurationValue(config, settingPath, defaultValue) { function accessSetting(config2, path2) { let current = config2; for (const component of path2) { if (typeof current !== "object" || current === null) { return void 0; } current = current[component]; } return current; } const path = settingPath.split("."); const result = accessSetting(config, path); return typeof result === "undefined" ? defaultValue : result; } function getLanguageTagSettingPlainKey(settingKey) { return settingKey.replace(/^\[/, "").replace(/]$/g, "").replace(/\]\[/g, ", "); } const ILanguageService = createDecorator("languageService"); class SyncDescriptor { constructor(ctor, staticArguments = [], supportsDelayedInstantiation = false) { this.ctor = ctor; this.staticArguments = staticArguments; this.supportsDelayedInstantiation = supportsDelayedInstantiation; } } const _registry = []; function registerSingleton(id, ctorOrDescriptor, supportsDelayedInstantiation) { if (!(ctorOrDescriptor instanceof SyncDescriptor)) { ctorOrDescriptor = new SyncDescriptor(ctorOrDescriptor, [], Boolean(supportsDelayedInstantiation)); } _registry.push([id, ctorOrDescriptor]); } function getSingletonServiceDescriptors() { return _registry; } const Mimes = Object.freeze({ text: "text/plain", binary: "application/octet-stream", unknown: "application/unknown", markdown: "text/markdown", latex: "text/latex", uriList: "text/uri-list", html: "text/html" }); const Extensions$7 = { JSONContribution: "base.contributions.json" }; function normalizeId(id) { if (id.length > 0 && id.charAt(id.length - 1) === "#") { return id.substring(0, id.length - 1); } return id; } class JSONContributionRegistry extends Disposable { constructor() { super(...arguments); this.schemasById = {}; this._onDidChangeSchema = this._register(new Emitter$1()); } registerSchema(uri, unresolvedSchemaContent, store) { const normalizedUri = normalizeId(uri); this.schemasById[normalizedUri] = unresolvedSchemaContent; this._onDidChangeSchema.fire(uri); if (store) { store.add(toDisposable(() => { delete this.schemasById[normalizedUri]; this._onDidChangeSchema.fire(uri); })); } } notifySchemaChanged(uri) { this._onDidChangeSchema.fire(uri); } } const jsonContributionRegistry = new JSONContributionRegistry(); Registry.add(Extensions$7.JSONContribution, jsonContributionRegistry); const Extensions$6 = { Configuration: "base.contributions.configuration" }; const resourceLanguageSettingsSchemaId = "vscode://schemas/settings/resourceLanguage"; const contributionRegistry = Registry.as(Extensions$7.JSONContribution); class ConfigurationRegistry extends Disposable { constructor() { super(); this.registeredConfigurationDefaults = []; this.overrideIdentifiers = /* @__PURE__ */ new Set(); this._onDidSchemaChange = this._register(new Emitter$1()); this._onDidUpdateConfiguration = this._register(new Emitter$1()); this.configurationDefaultsOverrides = /* @__PURE__ */ new Map(); this.defaultLanguageConfigurationOverridesNode = { id: "defaultOverrides", title: localize(1649, "Default Language Configuration Overrides"), properties: {} }; this.configurationContributors = [this.defaultLanguageConfigurationOverridesNode]; this.resourceLanguageSettingsSchema = { properties: {}, patternProperties: {}, additionalProperties: true, allowTrailingCommas: true, allowComments: true }; this.configurationProperties = {}; this.policyConfigurations = /* @__PURE__ */ new Map(); this.excludedConfigurationProperties = {}; contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema); this.registerOverridePropertyPatternKey(); } registerConfiguration(configuration, validate = true) { this.registerConfigurations([configuration], validate); return configuration; } registerConfigurations(configurations, validate = true) { const properties = /* @__PURE__ */ new Set(); this.doRegisterConfigurations(configurations, validate, properties); contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema); this._onDidSchemaChange.fire(); this._onDidUpdateConfiguration.fire({ properties }); } registerDefaultConfigurations(configurationDefaults) { const properties = /* @__PURE__ */ new Set(); this.doRegisterDefaultConfigurations(configurationDefaults, properties); this._onDidSchemaChange.fire(); this._onDidUpdateConfiguration.fire({ properties, defaultsOverrides: true }); } doRegisterDefaultConfigurations(configurationDefaults, bucket) { this.registeredConfigurationDefaults.push(...configurationDefaults); const overrideIdentifiers = []; for (const { overrides, source } of configurationDefaults) { for (const key in overrides) { bucket.add(key); const configurationDefaultOverridesForKey = this.configurationDefaultsOverrides.get(key) ?? this.configurationDefaultsOverrides.set(key, { configurationDefaultOverrides: [] }).get(key); const value = overrides[key]; configurationDefaultOverridesForKey.configurationDefaultOverrides.push({ value, source }); if (OVERRIDE_PROPERTY_REGEX.test(key)) { const newDefaultOverride = this.mergeDefaultConfigurationsForOverrideIdentifier(key, value, source, configurationDefaultOverridesForKey.configurationDefaultOverrideValue); if (!newDefaultOverride) { continue; } configurationDefaultOverridesForKey.configurationDefaultOverrideValue = newDefaultOverride; this.updateDefaultOverrideProperty(key, newDefaultOverride, source); overrideIdentifiers.push(...overrideIdentifiersFromKey(key)); } else { const newDefaultOverride = this.mergeDefaultConfigurationsForConfigurationProperty(key, value, source, configurationDefaultOverridesForKey.configurationDefaultOverrideValue); if (!newDefaultOverride) { continue; } configurationDefaultOverridesForKey.configurationDefaultOverrideValue = newDefaultOverride; const property = this.configurationProperties[key]; if (property) { this.updatePropertyDefaultValue(key, property); this.updateSchema(key, property); } } } } this.doRegisterOverrideIdentifiers(overrideIdentifiers); } updateDefaultOverrideProperty(key, newDefaultOverride, source) { const property = { type: "object", default: newDefaultOverride.value, description: localize(1650, "Configure settings to be overridden for {0}.", getLanguageTagSettingPlainKey(key)), $ref: resourceLanguageSettingsSchemaId, defaultDefaultValue: newDefaultOverride.value, source, defaultValueSource: source }; this.configurationProperties[key] = property; this.defaultLanguageConfigurationOverridesNode.properties[key] = property; } mergeDefaultConfigurationsForOverrideIdentifier(overrideIdentifier, configurationValueObject, valueSource, existingDefaultOverride) { const defaultValue = existingDefaultOverride?.value || {}; const source = existingDefaultOverride?.source ?? /* @__PURE__ */ new Map(); if (!(source instanceof Map)) { console.error("objectConfigurationSources is not a Map"); return void 0; } for (const propertyKey of Object.keys(configurationValueObject)) { const propertyDefaultValue = configurationValueObject[propertyKey]; const isObjectSetting = isObject(propertyDefaultValue) && (isUndefined(defaultValue[propertyKey]) || isObject(defaultValue[propertyKey])); if (isObjectSetting) { defaultValue[propertyKey] = { ...defaultValue[propertyKey] ?? {}, ...propertyDefaultValue }; if (valueSource) { for (const objectKey in propertyDefaultValue) { source.set(`${propertyKey}.${objectKey}`, valueSource); } } } else { defaultValue[propertyKey] = propertyDefaultValue; if (valueSource) { source.set(propertyKey, valueSource); } else { source.delete(propertyKey); } } } return { value: defaultValue, source }; } mergeDefaultConfigurationsForConfigurationProperty(propertyKey, value, valuesSource, existingDefaultOverride) { const property = this.configurationProperties[propertyKey]; const existingDefaultValue = existingDefaultOverride?.value ?? property?.defaultDefaultValue; let source = valuesSource; const isObjectSetting = isObject(value) && (property !== void 0 && property.type === "object" || property === void 0 && (isUndefined(existingDefaultValue) || isObject(existingDefaultValue))); if (isObjectSetting) { source = existingDefaultOverride?.source ?? /* @__PURE__ */ new Map(); if (!(source instanceof Map)) { console.error("defaultValueSource is not a Map"); return void 0; } for (const objectKey in value) { if (valuesSource) { source.set(`${propertyKey}.${objectKey}`, valuesSource); } } value = { ...isObject(existingDefaultValue) ? existingDefaultValue : {}, ...value }; } return { value, source }; } registerOverrideIdentifiers(overrideIdentifiers) { this.doRegisterOverrideIdentifiers(overrideIdentifiers); this._onDidSchemaChange.fire(); } doRegisterOverrideIdentifiers(overrideIdentifiers) { for (const overrideIdentifier of overrideIdentifiers) { this.overrideIdentifiers.add(overrideIdentifier); } this.updateOverridePropertyPatternKey(); } doRegisterConfigurations(configurations, validate, bucket) { configurations.forEach((configuration) => { this.validateAndRegisterProperties(configuration, validate, configuration.extensionInfo, configuration.restrictedProperties, void 0, bucket); this.configurationContributors.push(configuration); this.registerJSONConfiguration(configuration); }); } validateAndRegisterProperties(configuration, validate = true, extensionInfo, restrictedProperties, scope = 4, bucket) { scope = isUndefinedOrNull(configuration.scope) ? scope : configuration.scope; const properties = configuration.properties; if (properties) { for (const key in properties) { const property = properties[key]; if (validate && validateProperty(key, property)) { delete properties[key]; continue; } property.source = extensionInfo; property.defaultDefaultValue = properties[key].default; this.updatePropertyDefaultValue(key, property); if (OVERRIDE_PROPERTY_REGEX.test(key)) { property.scope = void 0; } else { property.scope = isUndefinedOrNull(property.scope) ? scope : property.scope; property.restricted = isUndefinedOrNull(property.restricted) ? !!restrictedProperties?.includes(key) : property.restricted; } if (property.experiment) { if (!property.tags?.some((tag2) => tag2.toLowerCase() === "onexp")) { property.tags = property.tags ?? []; property.tags.push("onExP"); } } else if (property.tags?.some((tag2) => tag2.toLowerCase() === "onexp")) { console.error(`Invalid tag 'onExP' found for property '${key}'. Please use 'experiment' property instead.`); property.experiment = { mode: "startup" }; } const excluded = properties[key].hasOwnProperty("included") && !properties[key].included; const policyName = properties[key].policy?.name; if (excluded) { this.excludedConfigurationProperties[key] = properties[key]; if (policyName) { this.policyConfigurations.set(policyName, key); bucket.add(key); } delete properties[key]; } else { bucket.add(key); if (policyName) { this.policyConfigurations.set(policyName, key); } this.configurationProperties[key] = properties[key]; if (!properties[key].deprecationMessage && properties[key].markdownDeprecationMessage) { properties[key].deprecationMessage = properties[key].markdownDeprecationMessage; } } } } const subNodes = configuration.allOf; if (subNodes) { for (const node of subNodes) { this.validateAndRegisterProperties(node, validate, extensionInfo, restrictedProperties, scope, bucket); } } } getConfigurationProperties() { return this.configurationProperties; } getPolicyConfigurations() { return this.policyConfigurations; } getExcludedConfigurationProperties() { return this.excludedConfigurationProperties; } registerJSONConfiguration(configuration) { const register2 = (configuration2) => { const properties = configuration2.properties; if (properties) { for (const key in properties) { this.updateSchema(key, properties[key]); } } const subNodes = configuration2.allOf; subNodes?.forEach(register2); }; register2(configuration); } updateSchema(key, property) { switch (property.scope) { case 1: break; case 2: break; case 3: break; case 7: break; case 4: break; case 5: break; case 6: this.resourceLanguageSettingsSchema.properties[key] = property; break; } } updateOverridePropertyPatternKey() { for (const overrideIdentifier of this.overrideIdentifiers.values()) { const overrideIdentifierProperty = `[${overrideIdentifier}]`; const resourceLanguagePropertiesSchema = { type: "object", description: localize(1651, "Configure editor settings to be overridden for a language."), errorMessage: localize(1652, "This setting does not support per-language configuration."), $ref: resourceLanguageSettingsSchemaId }; this.updatePropertyDefaultValue(overrideIdentifierProperty, resourceLanguagePropertiesSchema); } } registerOverridePropertyPatternKey() { ({ description: localize(1653, "Configure editor settings to be overridden for a language."), errorMessage: localize(1654, "This setting does not support per-language configuration.") }); this._onDidSchemaChange.fire(); } updatePropertyDefaultValue(key, property) { const configurationdefaultOverride = this.configurationDefaultsOverrides.get(key)?.configurationDefaultOverrideValue; let defaultValue = void 0; let defaultSource = void 0; if (configurationdefaultOverride && (!property.disallowConfigurationDefault || !configurationdefaultOverride.source)) { defaultValue = configurationdefaultOverride.value; defaultSource = configurationdefaultOverride.source; } if (isUndefined(defaultValue)) { defaultValue = property.defaultDefaultValue; defaultSource = void 0; } if (isUndefined(defaultValue)) { defaultValue = getDefaultValue(property.type); } property.default = defaultValue; property.defaultValueSource = defaultSource; } } const OVERRIDE_IDENTIFIER_PATTERN = `\\[([^\\]]+)\\]`; const OVERRIDE_IDENTIFIER_REGEX = new RegExp(OVERRIDE_IDENTIFIER_PATTERN, "g"); const OVERRIDE_PROPERTY_PATTERN = `^(${OVERRIDE_IDENTIFIER_PATTERN})+$`; const OVERRIDE_PROPERTY_REGEX = new RegExp(OVERRIDE_PROPERTY_PATTERN); function overrideIdentifiersFromKey(key) { const identifiers = []; if (OVERRIDE_PROPERTY_REGEX.test(key)) { let matches = OVERRIDE_IDENTIFIER_REGEX.exec(key); while (matches?.length) { const identifier = matches[1].trim(); if (identifier) { identifiers.push(identifier); } matches = OVERRIDE_IDENTIFIER_REGEX.exec(key); } } return distinct(identifiers); } function getDefaultValue(type) { const t = Array.isArray(type) ? type[0] : type; switch (t) { case "boolean": return false; case "integer": case "number": return 0; case "string": return ""; case "array": return []; case "object": return {}; default: return null; } } const configurationRegistry$2 = new ConfigurationRegistry(); Registry.add(Extensions$6.Configuration, configurationRegistry$2); function validateProperty(property, schema) { if (!property.trim()) { return localize(1655, "Cannot register an empty property"); } if (OVERRIDE_PROPERTY_REGEX.test(property)) { return localize(1656, "Cannot register '{0}'. This matches property pattern '\\\\[.*\\\\]$' for describing language specific editor settings. Use 'configurationDefaults' contribution.", property); } if (configurationRegistry$2.getConfigurationProperties()[property] !== void 0) { return localize(1657, "Cannot register '{0}'. This property is already registered.", property); } if (schema.policy?.name && configurationRegistry$2.getPolicyConfigurations().get(schema.policy?.name) !== void 0) { return localize(1658, "Cannot register '{0}'. The associated policy {1} is already registered with {2}.", property, schema.policy?.name, configurationRegistry$2.getPolicyConfigurations().get(schema.policy?.name)); } return null; } const Extensions$5 = { ModesRegistry: "editor.modesRegistry" }; class EditorModesRegistry extends Disposable { constructor() { super(); this._onDidChangeLanguages = this._register(new Emitter$1()); this.onDidChangeLanguages = this._onDidChangeLanguages.event; this._languages = []; } registerLanguage(def2) { this._languages.push(def2); this._onDidChangeLanguages.fire(void 0); return { dispose: () => { for (let i2 = 0, len = this._languages.length; i2 < len; i2++) { if (this._languages[i2] === def2) { this._languages.splice(i2, 1); return; } } } }; } getLanguages() { return this._languages; } } const ModesRegistry = new EditorModesRegistry(); Registry.add(Extensions$5.ModesRegistry, ModesRegistry); const PLAINTEXT_LANGUAGE_ID = "plaintext"; const PLAINTEXT_EXTENSION = ".txt"; ModesRegistry.registerLanguage({ id: PLAINTEXT_LANGUAGE_ID, extensions: [PLAINTEXT_EXTENSION], aliases: [localize(780, "Plain Text"), "text"], mimetypes: [Mimes.text] }); Registry.as(Extensions$6.Configuration).registerDefaultConfigurations([{ overrides: { "[plaintext]": { "editor.unicodeHighlight.ambiguousCharacters": false, "editor.unicodeHighlight.invisibleCharacters": false }, // TODO: Below is a workaround for: https://github.com/microsoft/vscode/issues/240567 "[go]": { "editor.insertSpaces": false }, "[makefile]": { "editor.insertSpaces": false }, "[shellscript]": { "files.eol": "\n" }, "[yaml]": { "editor.insertSpaces": true, "editor.tabSize": 2 } } }]); class LanguageBracketsConfiguration { constructor(languageId, config) { this.languageId = languageId; const bracketPairs = config.brackets ? filterValidBrackets(config.brackets) : []; const openingBracketInfos = new CachedFunction((bracket) => { const closing = /* @__PURE__ */ new Set(); return { info: new OpeningBracketKind(this, bracket, closing), closing }; }); const closingBracketInfos = new CachedFunction((bracket) => { const opening = /* @__PURE__ */ new Set(); const openingColorized = /* @__PURE__ */ new Set(); return { info: new ClosingBracketKind(this, bracket, opening, openingColorized), opening, openingColorized }; }); for (const [open, close] of bracketPairs) { const opening = openingBracketInfos.get(open); const closing = closingBracketInfos.get(close); opening.closing.add(closing.info); closing.opening.add(opening.info); } const colorizedBracketPairs = config.colorizedBracketPairs ? filterValidBrackets(config.colorizedBracketPairs) : bracketPairs.filter((p) => !(p[0] === "<" && p[1] === ">")); for (const [open, close] of colorizedBracketPairs) { const opening = openingBracketInfos.get(open); const closing = closingBracketInfos.get(close); opening.closing.add(closing.info); closing.openingColorized.add(opening.info); closing.opening.add(opening.info); } this._openingBrackets = new Map([...openingBracketInfos.cachedValues].map(([k, v]) => [k, v.info])); this._closingBrackets = new Map([...closingBracketInfos.cachedValues].map(([k, v]) => [k, v.info])); } /** * No two brackets have the same bracket text. */ get openingBrackets() { return [...this._openingBrackets.values()]; } /** * No two brackets have the same bracket text. */ get closingBrackets() { return [...this._closingBrackets.values()]; } getOpeningBracketInfo(bracketText) { return this._openingBrackets.get(bracketText); } getClosingBracketInfo(bracketText) { return this._closingBrackets.get(bracketText); } getBracketInfo(bracketText) { return this.getOpeningBracketInfo(bracketText) || this.getClosingBracketInfo(bracketText); } getBracketRegExp(options) { const brackets = Array.from([...this._openingBrackets.keys(), ...this._closingBrackets.keys()]); return createBracketOrRegExp(brackets, options); } } function filterValidBrackets(bracketPairs) { return bracketPairs.filter(([open, close]) => open !== "" && close !== ""); } class BracketKindBase { constructor(config, bracketText) { this.config = config; this.bracketText = bracketText; } get languageId() { return this.config.languageId; } } class OpeningBracketKind extends BracketKindBase { constructor(config, bracketText, openedBrackets) { super(config, bracketText); this.openedBrackets = openedBrackets; this.isOpeningBracket = true; } } class ClosingBracketKind extends BracketKindBase { constructor(config, bracketText, openingBrackets, openingColorizedBrackets) { super(config, bracketText); this.openingBrackets = openingBrackets; this.openingColorizedBrackets = openingColorizedBrackets; this.isOpeningBracket = false; } /** * Checks if this bracket closes the given other bracket. * If the bracket infos come from different configurations, this method will return false. */ closes(other) { if (other["config"] !== this.config) { return false; } return this.openingBrackets.has(other); } closesColorized(other) { if (other["config"] !== this.config) { return false; } return this.openingColorizedBrackets.has(other); } getOpeningBrackets() { return [...this.openingBrackets]; } } var __decorate$34 = function(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d = decorators[i2]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param$2Z = function(paramIndex, decorator) { return function(target, key) { decorator(target, key, paramIndex); }; }; class LanguageConfigurationServiceChangeEvent { constructor(languageId) { this.languageId = languageId; } affects(languageId) { return !this.languageId ? true : this.languageId === languageId; } } const ILanguageConfigurationService = createDecorator("languageConfigurationService"); let LanguageConfigurationService = class LanguageConfigurationService extends Disposable { constructor(configurationService, languageService) { super(); this.configurationService = configurationService; this.languageService = languageService; this._registry = this._register(new LanguageConfigurationRegistry()); this.onDidChangeEmitter = this._register(new Emitter$1()); this.onDidChange = this.onDidChangeEmitter.event; this.configurations = /* @__PURE__ */ new Map(); const languageConfigKeys = new Set(Object.values(customizedLanguageConfigKeys)); this._register(this.configurationService.onDidChangeConfiguration((e) => { const globalConfigChanged = e.change.keys.some((k) => languageConfigKeys.has(k)); const localConfigChanged = e.change.overrides.filter(([overrideLangName, keys]) => keys.some((k) => languageConfigKeys.has(k))).map(([overrideLangName]) => overrideLangName); if (globalConfigChanged) { this.configurations.clear(); this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(void 0)); } else { for (const languageId of localConfigChanged) { if (this.languageService.isRegisteredLanguageId(languageId)) { this.configurations.delete(languageId); this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(languageId)); } } } })); this._register(this._registry.onDidChange((e) => { this.configurations.delete(e.languageId); this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(e.languageId)); })); } register(languageId, configuration, priority) { return this._registry.register(languageId, configuration, priority); } getLanguageConfiguration(languageId) { let result = this.configurations.get(languageId); if (!result) { result = computeConfig(languageId, this._registry, this.configurationService, this.languageService); this.configurations.set(languageId, result); } return result; } }; LanguageConfigurationService = __decorate$34([ __param$2Z(0, IConfigurationService), __param$2Z(1, ILanguageService) ], LanguageConfigurationService); function computeConfig(languageId, registry, configurationService, languageService) { let languageConfig = registry.getLanguageConfiguration(languageId); if (!languageConfig) { if (!languageService.isRegisteredLanguageId(languageId)) { return new ResolvedLanguageConfiguration(languageId, {}); } languageConfig = new ResolvedLanguageConfiguration(languageId, {}); } const customizedConfig = getCustomizedLanguageConfig(languageConfig.languageId, configurationService); const data = combineLanguageConfigurations([languageConfig.underlyingConfig, customizedConfig]); const config = new ResolvedLanguageConfiguration(languageConfig.languageId, data); return config; } const customizedLanguageConfigKeys = { brackets: "editor.language.brackets", colorizedBracketPairs: "editor.language.colorizedBracketPairs" }; function getCustomizedLanguageConfig(languageId, configurationService) { const brackets = configurationService.getValue(customizedLanguageConfigKeys.brackets, { overrideIdentifier: languageId }); const colorizedBracketPairs = configurationService.getValue(customizedLanguageConfigKeys.colorizedBracketPairs, { overrideIdentifier: languageId }); return { brackets: validateBracketPairs(brackets), colorizedBracketPairs: validateBracketPairs(colorizedBracketPairs) }; } function validateBracketPairs(data) { if (!Array.isArray(data)) { return void 0; } return data.map((pair) => { if (!Array.isArray(pair) || pair.length !== 2) { return void 0; } return [pair[0], pair[1]]; }).filter((p) => !!p); } function getIndentationAtPosition(model, lineNumber, column) { const lineText = model.getLineContent(lineNumber); let indentation = getLeadingWhitespace(lineText); if (indentation.length > column - 1) { indentation = indentation.substring(0, column - 1); } return indentation; } class ComposedLanguageConfiguration { constructor(languageId) { this.languageId = languageId; this._resolved = null; this._entries = []; this._order = 0; this._resolved = null; } register(configuration, priority) { const entry = new LanguageConfigurationContribution(configuration, priority, ++this._order); this._entries.push(entry); this._resolved = null; return markAsSingleton(toDisposable(() => { for (let i2 = 0; i2 < this._entries.length; i2++) { if (this._entries[i2] === entry) { this._entries.splice(i2, 1); this._resolved = null; break; } } })); } getResolvedConfiguration() { if (!this._resolved) { const config = this._resolve(); if (config) { this._resolved = new ResolvedLanguageConfiguration(this.languageId, config); } } return this._resolved; } _resolve() { if (this._entries.length === 0) { return null; } this._entries.sort(LanguageConfigurationContribution.cmp); return combineLanguageConfigurations(this._entries.map((e) => e.configuration)); } } function combineLanguageConfigurations(configs) { let result = { comments: void 0, brackets: void 0, wordPattern: void 0, indentationRules: void 0, onEnterRules: void 0, autoClosingPairs: void 0, surroundingPairs: void 0, autoCloseBefore: void 0, folding: void 0, colorizedBracketPairs: void 0, __electricCharacterSupport: void 0 }; for (const entry of configs) { result = { comments: entry.comments || result.comments, brackets: entry.brackets || result.brackets, wordPattern: entry.wordPattern || result.wordPattern, indentationRules: entry.indentationRules || result.indentationRules, onEnterRules: entry.onEnterRules || result.onEnterRules, autoClosingPairs: entry.autoClosingPairs || result.autoClosingPairs, surroundingPairs: entry.surroundingPairs || result.surroundingPairs, autoCloseBefore: entry.autoCloseBefore || result.autoCloseBefore, folding: entry.folding || result.folding, colorizedBracketPairs: entry.colorizedBracketPairs || result.colorizedBracketPairs, __electricCharacterSupport: entry.__electricCharacterSupport || result.__electricCharacterSupport }; } return result; } class LanguageConfigurationContribution { constructor(configuration, priority, order) { this.configuration = configuration; this.priority = priority; this.order = order; } static cmp(a, b) { if (a.priority === b.priority) { return a.order - b.order; } return a.priority - b.priority; } } class LanguageConfigurationChangeEvent { constructor(languageId) { this.languageId = languageId; } } class LanguageConfigurationRegistry extends Disposable { constructor() { super(); this._entries = /* @__PURE__ */ new Map(); this._onDidChange = this._register(new Emitter$1()); this.onDidChange = this._onDidChange.event; this._register(this.register(PLAINTEXT_LANGUAGE_ID, { brackets: [ ["(", ")"], ["[", "]"], ["{", "}"] ], surroundingPairs: [ { open: "{", close: "}" }, { open: "[", close: "]" }, { open: "(", close: ")" }, { open: "<", close: ">" }, { open: '"', close: '"' }, { open: "'", close: "'" }, { open: "`", close: "`" } ], colorizedBracketPairs: [], folding: { offSide: true } }, 0)); } /** * @param priority Use a higher number for higher priority */ register(languageId, configuration, priority = 0) { let entries2 = this._entries.get(languageId); if (!entries2) { entries2 = new ComposedLanguageConfiguration(languageId); this._entries.set(languageId, entries2); } const disposable = entries2.register(configuration, priority); this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageId)); return markAsSingleton(toDisposable(() => { disposable.dispose(); this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageId)); })); } getLanguageConfiguration(languageId) { const entries2 = this._entries.get(languageId); return entries2?.getResolvedConfiguration() || null; } } class ResolvedLanguageConfiguration { constructor(languageId, underlyingConfig) { this.languageId = languageId; this.underlyingConfig = underlyingConfig; this._brackets = null; this._electricCharacter = null; this._onEnterSupport = this.underlyingConfig.brackets || this.underlyingConfig.indentationRules || this.underlyingConfig.onEnterRules ? new OnEnterSupport(this.underlyingConfig) : null; this.comments = ResolvedLanguageConfiguration._handleComments(this.underlyingConfig); this.characterPair = new CharacterPairSupport(this.underlyingConfig); this.wordDefinition = this.underlyingConfig.wordPattern || DEFAULT_WORD_REGEXP; this.indentationRules = this.underlyingConfig.indentationRules; if (this.underlyingConfig.indentationRules) { this.indentRulesSupport = new IndentRulesSupport(this.underlyingConfig.indentationRules); } else { this.indentRulesSupport = null; } this.foldingRules = this.underlyingConfig.folding || {}; this.bracketsNew = new LanguageBracketsConfiguration(languageId, this.underlyingConfig); } getWordDefinition() { return ensureValidWordDefinition(this.wordDefinition); } get brackets() { if (!this._brackets && this.underlyingConfig.brackets) { this._brackets = new RichEditBrackets(this.languageId, this.underlyingConfig.brackets); } return this._brackets; } get electricCharacter() { if (!this._electricCharacter) { this._electricCharacter = new BracketElectricCharacterSupport(this.brackets); } return this._electricCharacter; } onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) { if (!this._onEnterSupport) { return null; } return this._onEnterSupport.onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText); } getAutoClosingPairs() { return new AutoClosingPairs(this.characterPair.getAutoClosingPairs()); } getAutoCloseBeforeSet(forQuotes) { return this.characterPair.getAutoCloseBeforeSet(forQuotes); } getSurroundingPairs() { return this.characterPair.getSurroundingPairs(); } static _handleComments(conf) { const commentRule = conf.comments; if (!commentRule) { return null; } const comments = {}; if (commentRule.lineComment) { if (typeof commentRule.lineComment === "string") { comments.lineCommentToken = commentRule.lineComment; } else { comments.lineCommentToken = commentRule.lineComment.comment; comments.lineCommentNoIndent = commentRule.lineComment.noIndent; } } if (commentRule.blockComment) { const [blockStart, blockEnd] = commentRule.blockComment; comments.blockCommentStartToken = blockStart; comments.blockCommentEndToken = blockEnd; } return comments; } } registerSingleton( ILanguageConfigurationService, LanguageConfigurationService, 1 /* InstantiationType.Delayed */ ); class TokenMetadata { static getLanguageId(metadata) { return (metadata & 255) >>> 0; } static getTokenType(metadata) { return (metadata & 768) >>> 8; } static containsBalancedBrackets(metadata) { return (metadata & 1024) !== 0; } static getFontStyle(metadata) { return (metadata & 30720) >>> 11; } static getForeground(metadata) { return (metadata & 16744448) >>> 15; } static getBackground(metadata) { return (metadata & 4278190080) >>> 24; } static getClassNameFromMetadata(metadata) { const foreground2 = this.getForeground(metadata); let className2 = "mtk" + foreground2; const fontStyle = this.getFontStyle(metadata); if (fontStyle & 1) { className2 += " mtki"; } if (fontStyle & 2) { className2 += " mtkb"; } if (fontStyle & 4) { className2 += " mtku"; } if (fontStyle & 8) { className2 += " mtks"; } return className2; } static getInlineStyleFromMetadata(metadata, colorMap) { const foreground2 = this.getForeground(metadata); const fontStyle = this.getFontStyle(metadata); let result = `color: ${colorMap[foreground2]};`; if (fontStyle & 1) { result += "font-style: italic;"; } if (fontStyle & 2) { result += "font-weight: bold;"; } let textDecoration = ""; if (fontStyle & 4) { textDecoration += " underline"; } if (fontStyle & 8) { textDecoration += " line-through"; } if (textDecoration) { result += `text-decoration:${textDecoration};`; } return result; } static getPresentationFromMetadata(metadata) { const foreground2 = this.getForeground(metadata); const fontStyle = this.getFontStyle(metadata); return { foreground: foreground2, italic: Boolean( fontStyle & 1 /* FontStyle.Italic */ ), bold: Boolean( fontStyle & 2 /* FontStyle.Bold */ ), underline: Boolean( fontStyle & 4 /* FontStyle.Underline */ ), strikethrough: Boolean( fontStyle & 8 /* FontStyle.Strikethrough */ ) }; } } class OffsetRange { static fromTo(start, endExclusive) { return new OffsetRange(start, endExclusive); } static addRange(range2, sortedRanges) { let i2 = 0; while (i2 < sortedRanges.length && sortedRanges[i2].endExclusive < range2.start) { i2++; } let j = i2; while (j < sortedRanges.length && sortedRanges[j].start <= range2.endExclusive) { j++; } if (i2 === j) { sortedRanges.splice(i2, 0, range2); } else { const start = Math.min(range2.start, sortedRanges[i2].start); const end = Math.max(range2.endExclusive, sortedRanges[j - 1].endExclusive); sortedRanges.splice(i2, j - i2, new OffsetRange(start, end)); } } static tryCreate(start, endExclusive) { if (start > endExclusive) { return void 0; } return new OffsetRange(start, endExclusive); } static ofLength(length) { return new OffsetRange(0, length); } static ofStartAndLength(start, length) { return new OffsetRange(start, start + length); } static emptyAt(offset) { return new OffsetRange(offset, offset); } constructor(start, endExclusive) { this.start = start; this.endExclusive = endExclusive; if (start > endExclusive) { throw new BugIndicatingError(`Invalid range: ${this.toString()}`); } } get isEmpty() { return this.start === this.endExclusive; } delta(offset) { return new OffsetRange(this.start + offset, this.endExclusive + offset); } deltaStart(offset) { return new OffsetRange(this.start + offset, this.endExclusive); } deltaEnd(offset) { return new OffsetRange(this.start, this.endExclusive + offset); } get length() { return this.endExclusive - this.start; } toString() { return `[${this.start}, ${this.endExclusive})`; } equals(other) { return this.start === other.start && this.endExclusive === other.endExclusive; } contains(offset) { return this.start <= offset && offset < this.endExclusive; } /** * for all numbers n: range1.contains(n) or range2.contains(n) => range1.join(range2).contains(n) * The joined range is the smallest range that contains both ranges. */ join(other) { return new OffsetRange(Math.min(this.start, other.start), Math.max(this.endExclusive, other.endExclusive)); } /** * for all numbers n: range1.contains(n) and range2.contains(n) <=> range1.intersect(range2).contains(n) * * The resulting range is empty if the ranges do not intersect, but touch. * If the ranges don't even touch, the result is undefined. */ intersect(other) { const start = Math.max(this.start, other.start); const end = Math.min(this.endExclusive, other.endExclusive); if (start <= end) { return new OffsetRange(start, end); } return void 0; } intersectionLength(range2) { const start = Math.max(this.start, range2.start); const end = Math.min(this.endExclusive, range2.endExclusive); return Math.max(0, end - start); } intersects(other) { const start = Math.max(this.start, other.start); const end = Math.min(this.endExclusive, other.endExclusive); return start < end; } intersectsOrTouches(other) { const start = Math.max(this.start, other.start); const end = Math.min(this.endExclusive, other.endExclusive); return start <= end; } isBefore(other) { return this.endExclusive <= other.start; } isAfter(other) { return this.start >= other.endExclusive; } slice(arr) { return arr.slice(this.start, this.endExclusive); } substring(str) { return str.substring(this.start, this.endExclusive); } /** * Returns the given value if it is contained in this instance, otherwise the closest value that is contained. * The range must not be empty. */ clip(value) { if (this.isEmpty) { throw new BugIndicatingError(`Invalid clipping range: ${this.toString()}`); } return Math.max(this.start, Math.min(this.endExclusive - 1, value)); } /** * Returns `r := value + k * length` such that `r` is contained in this range. * The range must not be empty. * * E.g. `[5, 10).clipCyclic(10) === 5`, `[5, 10).clipCyclic(11) === 6` and `[5, 10).clipCyclic(4) === 9`. */ clipCyclic(value) { if (this.isEmpty) { throw new BugIndicatingError(`Invalid clipping range: ${this.toString()}`); } if (value < this.start) { return this.endExclusive - (this.start - value) % this.length; } if (value >= this.endExclusive) { return this.start + (value - this.start) % this.length; } return value; } forEach(f) { for (let i2 = this.start; i2 < this.endExclusive; i2++) { f(i2); } } /** * this: [ 5, 10), range: [10, 15) => [5, 15)] * Throws if the ranges are not touching. */ joinRightTouching(range2) { if (this.endExclusive !== range2.start) { throw new BugIndicatingError(`Invalid join: ${this.toString()} and ${range2.toString()}`); } return new OffsetRange(this.start, range2.endExclusive); } } class OffsetRangeSet { constructor() { this._sortedRanges = []; } addRange(range2) { let i2 = 0; while (i2 < this._sortedRanges.length && this._sortedRanges[i2].endExclusive < range2.start) { i2++; } let j = i2; while (j < this._sortedRanges.length && this._sortedRanges[j].start <= range2.endExclusive) { j++; } if (i2 === j) { this._sortedRanges.splice(i2, 0, range2); } else { const start = Math.min(range2.start, this._sortedRanges[i2].start); const end = Math.max(range2.endExclusive, this._sortedRanges[j - 1].endExclusive); this._sortedRanges.splice(i2, j - i2, new OffsetRange(start, end)); } } toString() { return this._sortedRanges.map((r) => r.toString()).join(", "); } /** * Returns of there is a value that is contained in this instance and the given range. */ intersectsStrict(other) { let i2 = 0; while (i2 < this._sortedRanges.length && this._sortedRanges[i2].endExclusive <= other.start) { i2++; } return i2 < this._sortedRanges.length && this._sortedRanges[i2].start < other.endExclusive; } intersectWithRange(other) { const result = new OffsetRangeSet(); for (const range2 of this._sortedRanges) { const intersection2 = range2.intersect(other); if (intersection2) { result.addRange(intersection2); } } return result; } intersectWithRangeLength(other) { return this.intersectWithRange(other).length; } get length() { return this._sortedRanges.reduce((prev, cur) => prev + cur.length, 0); } } const _LineTokens = class _LineTokens { static createEmpty(lineContent, decoder) { const defaultMetadata = _LineTokens.defaultTokenMetadata; const tokens = new Uint32Array(2); tokens[0] = lineContent.length; tokens[1] = defaultMetadata; return new _LineTokens(tokens, lineContent, decoder); } static createFromTextAndMetadata(data, decoder) { let offset = 0; let fullText = ""; const tokens = new Array(); for (const { text: text2, metadata } of data) { tokens.push(offset + text2.length, metadata); offset += text2.length; fullText += text2; } return new _LineTokens(new Uint32Array(tokens), fullText, decoder); } static convertToEndOffset(tokens, lineTextLength) { const tokenCount = tokens.length >>> 1; const lastTokenIndex = tokenCount - 1; for (let tokenIndex = 0; tokenIndex < lastTokenIndex; tokenIndex++) { tokens[tokenIndex << 1] = tokens[tokenIndex + 1 << 1]; } tokens[lastTokenIndex << 1] = lineTextLength; } static findIndexInTokensArray(tokens, desiredIndex) { if (tokens.length <= 2) { return 0; } let low = 0; let high = (tokens.length >>> 1) - 1; while (low < high) { const mid = low + Math.floor((high - low) / 2); const endOffset = tokens[mid << 1]; if (endOffset === desiredIndex) { return mid + 1; } else if (endOffset < desiredIndex) { low = mid + 1; } else if (endOffset > desiredIndex) { high = mid; } } return low; } constructor(tokens, text2, decoder) { this._lineTokensBrand = void 0; const tokensLength = tokens.length > 1 ? tokens[tokens.length - 2] : 0; if (tokensLength !== text2.length) { onUnexpectedError(new Error("Token length and text length do not match!")); } this._tokens = tokens; this._tokensCount = this._tokens.length >>> 1; this._text = text2; this.languageIdCodec = decoder; } getTextLength() { return this._text.length; } equals(other) { if (other instanceof _LineTokens) { return this.slicedEquals(other, 0, this._tokensCount); } return false; } slicedEquals(other, sliceFromTokenIndex, sliceTokenCount) { if (this._text !== other._text) { return false; } if (this._tokensCount !== other._tokensCount) { return false; } const from = sliceFromTokenIndex << 1; const to = from + (sliceTokenCount << 1); for (let i2 = from; i2 < to; i2++) { if (this._tokens[i2] !== other._tokens[i2]) { return false; } } return true; } getLineContent() { return this._text; } getCount() { return this._tokensCount; } getStartOffset(tokenIndex) { if (tokenIndex > 0) { return this._tokens[tokenIndex - 1 << 1]; } return 0; } getMetadata(tokenIndex) { const metadata = this._tokens[(tokenIndex << 1) + 1]; return metadata; } getLanguageId(tokenIndex) { const metadata = this._tokens[(tokenIndex << 1) + 1]; const languageId = TokenMetadata.getLanguageId(metadata); return this.languageIdCodec.decodeLanguageId(languageId); } getStandardTokenType(tokenIndex) { const metadata = this._tokens[(tokenIndex << 1) + 1]; return TokenMetadata.getTokenType(metadata); } getForeground(tokenIndex) { const metadata = this._tokens[(tokenIndex << 1) + 1]; return TokenMetadata.getForeground(metadata); } getClassName(tokenIndex) { const metadata = this._tokens[(tokenIndex << 1) + 1]; return TokenMetadata.getClassNameFromMetadata(metadata); } getInlineStyle(tokenIndex, colorMap) { const metadata = this._tokens[(tokenIndex << 1) + 1]; return TokenMetadata.getInlineStyleFromMetadata(metadata, colorMap); } getPresentation(tokenIndex) { const metadata = this._tokens[(tokenIndex << 1) + 1]; return TokenMetadata.getPresentationFromMetadata(metadata); } getEndOffset(tokenIndex) { return this._tokens[tokenIndex << 1]; } /** * Find the token containing offset `offset`. * @param offset The search offset * @return The index of the token containing the offset. */ findTokenIndexAtOffset(offset) { return _LineTokens.findIndexInTokensArray(this._tokens, offset); } inflate() { return this; } sliceAndInflate(startOffset, endOffset, deltaOffset) { return new SliceLineTokens(this, startOffset, endOffset, deltaOffset); } sliceZeroCopy(range2) { return this.sliceAndInflate(range2.start, range2.endExclusive, 0); } /** * @pure * @param insertTokens Must be sorted by offset. */ withInserted(insertTokens) { if (insertTokens.length === 0) { return this; } let nextOriginalTokenIdx = 0; let nextInsertTokenIdx = 0; let text2 = ""; const newTokens = new Array(); let originalEndOffset = 0; while (true) { const nextOriginalTokenEndOffset = nextOriginalTokenIdx < this._tokensCount ? this._tokens[nextOriginalTokenIdx << 1] : -1; const nextInsertToken = nextInsertTokenIdx < insertTokens.length ? insertTokens[nextInsertTokenIdx] : null; if (nextOriginalTokenEndOffset !== -1 && (nextInsertToken === null || nextOriginalTokenEndOffset <= nextInsertToken.offset)) { text2 += this._text.substring(originalEndOffset, nextOriginalTokenEndOffset); const metadata = this._tokens[(nextOriginalTokenIdx << 1) + 1]; newTokens.push(text2.length, metadata); nextOriginalTokenIdx++; originalEndOffset = nextOriginalTokenEndOffset; } else if (nextInsertToken) { if (nextInsertToken.offset > originalEndOffset) { text2 += this._text.substring(originalEndOffset, nextInsertToken.offset); const metadata = this._tokens[(nextOriginalTokenIdx << 1) + 1]; newTokens.push(text2.length, metadata); originalEndOffset = nextInsertToken.offset; } text2 += nextInsertToken.text; newTokens.push(text2.length, nextInsertToken.tokenMetadata); nextInsertTokenIdx++; } else { break; } } return new _LineTokens(new Uint32Array(newTokens), text2, this.languageIdCodec); } getTokensInRange(range2) { const builder = new TokenArrayBuilder(); const startTokenIndex = this.findTokenIndexAtOffset(range2.start); const endTokenIndex = this.findTokenIndexAtOffset(range2.endExclusive); for (let tokenIndex = startTokenIndex; tokenIndex <= endTokenIndex; tokenIndex++) { const tokenRange = new OffsetRange(this.getStartOffset(tokenIndex), this.getEndOffset(tokenIndex)); const length = tokenRange.intersectionLength(range2); if (length > 0) { builder.add(length, this.getMetadata(tokenIndex)); } } return builder.build(); } getTokenText(tokenIndex) { const startOffset = this.getStartOffset(tokenIndex); const endOffset = this.getEndOffset(tokenIndex); const text2 = this._text.substring(startOffset, endOffset); return text2; } forEach(callback) { const tokenCount = this.getCount(); for (let tokenIndex = 0; tokenIndex < tokenCount; tokenIndex++) { callback(tokenIndex); } } toString() { let result = ""; this.forEach((i2) => { result += `[${this.getTokenText(i2)}]{${this.getClassName(i2)}}`; }); return result; } }; _LineTokens.defaultTokenMetadata = (0 << 11 | 1 << 15 | 2 << 24) >>> 0; let LineTokens = _LineTokens; class SliceLineTokens { constructor(source, startOffset, endOffset, deltaOffset) { this._source = source; this._startOffset = startOffset; this._endOffset = endOffset; this._deltaOffset = deltaOffset; this._firstTokenIndex = source.findTokenIndexAtOffset(startOffset); this.languageIdCodec = source.languageIdCodec; this._tokensCount = 0; for (let i2 = this._firstTokenIndex, len = source.getCount(); i2 < len; i2++) { const tokenStartOffset = source.getStartOffset(i2); if (tokenStartOffset >= endOffset) { break; } this._tokensCount++; } } getMetadata(tokenIndex) { return this._source.getMetadata(this._firstTokenIndex + tokenIndex); } getLanguageId(tokenIndex) { return this._source.getLanguageId(this._firstTokenIndex + tokenIndex); } getLineContent() { return this._source.getLineContent().substring(this._startOffset, this._endOffset); } equals(other) { if (other instanceof SliceLineTokens) { return this._startOffset === other._startOffset && this._endOffset === other._endOffset && this._deltaOffset === other._deltaOffset && this._source.slicedEquals(other._source, this._firstTokenIndex, this._tokensCount); } return false; } getCount() { return this._tokensCount; } getStandardTokenType(tokenIndex) { return this._source.getStandardTokenType(this._firstTokenIndex + tokenIndex); } getForeground(tokenIndex) { return this._source.getForeground(this._firstTokenIndex + tokenIndex); } getEndOffset(tokenIndex) { const tokenEndOffset = this._source.getEndOffset(this._firstTokenIndex + tokenIndex); return Math.min(this._endOffset, tokenEndOffset) - this._startOffset + this._deltaOffset; } getClassName(tokenIndex) { return this._source.getClassName(this._firstTokenIndex + tokenIndex); } getInlineStyle(tokenIndex, colorMap) { return this._source.getInlineStyle(this._firstTokenIndex + tokenIndex, colorMap); } getPresentation(tokenIndex) { return this._source.getPresentation(this._firstTokenIndex + tokenIndex); } findTokenIndexAtOffset(offset) { return this._source.findTokenIndexAtOffset(offset + this._startOffset - this._deltaOffset) - this._firstTokenIndex; } getTokenText(tokenIndex) { const adjustedTokenIndex = this._firstTokenIndex + tokenIndex; const tokenStartOffset = this._source.getStartOffset(adjustedTokenIndex); const tokenEndOffset = this._source.getEndOffset(adjustedTokenIndex); let text2 = this._source.getTokenText(adjustedTokenIndex); if (tokenStartOffset < this._startOffset) { text2 = text2.substring(this._startOffset - tokenStartOffset); } if (tokenEndOffset > this._endOffset) { text2 = text2.substring(0, text2.length - (tokenEndOffset - this._endOffset)); } return text2; } forEach(callback) { for (let tokenIndex = 0; tokenIndex < this.getCount(); tokenIndex++) { callback(tokenIndex); } } } function getStandardTokenTypeAtPosition(model, position) { const lineNumber = position.lineNumber; if (!model.tokenization.isCheapToTokenize(lineNumber)) { return void 0; } model.tokenization.forceTokenization(lineNumber); const lineTokens = model.tokenization.getLineTokens(lineNumber); const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1); const tokenType = lineTokens.getStandardTokenType(tokenIndex); return tokenType; } class TokenArray { static fromLineTokens(lineTokens) { const tokenInfo = []; for (let i2 = 0; i2 < lineTokens.getCount(); i2++) { tokenInfo.push(new TokenInfo(lineTokens.getEndOffset(i2) - lineTokens.getStartOffset(i2), lineTokens.getMetadata(i2))); } return TokenArray.create(tokenInfo); } static create(tokenInfo) { return new TokenArray(tokenInfo); } constructor(_tokenInfo) { this._tokenInfo = _tokenInfo; } toLineTokens(lineContent, decoder) { return LineTokens.createFromTextAndMetadata(this.map((r, t) => ({ text: r.substring(lineContent), metadata: t.metadata })), decoder); } forEach(cb) { let lengthSum = 0; for (const tokenInfo of this._tokenInfo) { const range2 = new OffsetRange(lengthSum, lengthSum + tokenInfo.length); cb(range2, tokenInfo); lengthSum += tokenInfo.length; } } map(cb) { const result = []; let lengthSum = 0; for (const tokenInfo of this._tokenInfo) { const range2 = new OffsetRange(lengthSum, lengthSum + tokenInfo.length); result.push(cb(range2, tokenInfo)); lengthSum += tokenInfo.length; } return result; } slice(range2) { const result = []; let lengthSum = 0; for (const tokenInfo of this._tokenInfo) { const tokenStart = lengthSum; const tokenEndEx = tokenStart + tokenInfo.length; if (tokenEndEx > range2.start) { if (tokenStart >= range2.endExclusive) { break; } const deltaBefore = Math.max(0, range2.start - tokenStart); const deltaAfter = Math.max(0, tokenEndEx - range2.endExclusive); result.push(new TokenInfo(tokenInfo.length - deltaBefore - deltaAfter, tokenInfo.metadata)); } lengthSum += tokenInfo.length; } return TokenArray.create(result); } } class TokenInfo { constructor(length, metadata) { this.length = length; this.metadata = metadata; } } class TokenArrayBuilder { constructor() { this._tokens = []; } add(length, metadata) { this._tokens.push(new TokenInfo(length, metadata)); } build() { return TokenArray.create(this._tokens); } } class ProcessedIndentRulesSupport { constructor(model, indentRulesSupport, languageConfigurationService) { this._indentRulesSupport = indentRulesSupport; this._indentationLineProcessor = new IndentationLineProcessor(model, languageConfigurationService); } /** * Apply the new indentation and return whether the indentation level should be increased after the given line number */ shouldIncrease(lineNumber, newIndentation) { const processedLine = this._indentationLineProcessor.getProcessedLine(lineNumber, newIndentation); return this._indentRulesSupport.shouldIncrease(processedLine); } /** * Apply the new indentation and return whether the indentation level should be decreased after the given line number */ shouldDecrease(lineNumber, newIndentation) { const processedLine = this._indentationLineProcessor.getProcessedLine(lineNumber, newIndentation); return this._indentRulesSupport.shouldDecrease(processedLine); } /** * Apply the new indentation and return whether the indentation level should remain unchanged at the given line number */ shouldIgnore(lineNumber, newIndentation) { const processedLine = this._indentationLineProcessor.getProcessedLine(lineNumber, newIndentation); return this._indentRulesSupport.shouldIgnore(processedLine); } /** * Apply the new indentation and return whether the indentation level should increase on the line after the given line number */ shouldIndentNextLine(lineNumber, newIndentation) { const processedLine = this._indentationLineProcessor.getProcessedLine(lineNumber, newIndentation); return this._indentRulesSupport.shouldIndentNextLine(processedLine); } } class IndentationContextProcessor { constructor(model, languageConfigurationService) { this.model = model; this.indentationLineProcessor = new IndentationLineProcessor(model, languageConfigurationService); } /** * Returns the processed text, stripped from the language configuration brackets within the string, comment and regex tokens, around the given range */ getProcessedTokenContextAroundRange(range2) { const beforeRangeProcessedTokens = this._getProcessedTokensBeforeRange(range2); const afterRangeProcessedTokens = this._getProcessedTokensAfterRange(range2); const previousLineProcessedTokens = this._getProcessedPreviousLineTokens(range2); return { beforeRangeProcessedTokens, afterRangeProcessedTokens, previousLineProcessedTokens }; } _getProcessedTokensBeforeRange(range2) { this.model.tokenization.forceTokenization(range2.startLineNumber); const lineTokens = this.model.tokenization.getLineTokens(range2.startLineNumber); const scopedLineTokens = createScopedLineTokens(lineTokens, range2.startColumn - 1); let slicedTokens; if (isLanguageDifferentFromLineStart(this.model, range2.getStartPosition())) { const columnIndexWithinScope = range2.startColumn - 1 - scopedLineTokens.firstCharOffset; const firstCharacterOffset = scopedLineTokens.firstCharOffset; const lastCharacterOffset = firstCharacterOffset + columnIndexWithinScope; slicedTokens = lineTokens.sliceAndInflate(firstCharacterOffset, lastCharacterOffset, 0); } else { const columnWithinLine = range2.startColumn - 1; slicedTokens = lineTokens.sliceAndInflate(0, columnWithinLine, 0); } const processedTokens = this.indentationLineProcessor.getProcessedTokens(slicedTokens); return processedTokens; } _getProcessedTokensAfterRange(range2) { const position = range2.isEmpty() ? range2.getStartPosition() : range2.getEndPosition(); this.model.tokenization.forceTokenization(position.lineNumber); const lineTokens = this.model.tokenization.getLineTokens(position.lineNumber); const scopedLineTokens = createScopedLineTokens(lineTokens, position.column - 1); const columnIndexWithinScope = position.column - 1 - scopedLineTokens.firstCharOffset; const firstCharacterOffset = scopedLineTokens.firstCharOffset + columnIndexWithinScope; const lastCharacterOffset = scopedLineTokens.firstCharOffset + scopedLineTokens.getLineLength(); const slicedTokens = lineTokens.sliceAndInflate(firstCharacterOffset, lastCharacterOffset, 0); const processedTokens = this.indentationLineProcessor.getProcessedTokens(slicedTokens); return processedTokens; } _getProcessedPreviousLineTokens(range2) { const getScopedLineTokensAtEndColumnOfLine = (lineNumber) => { this.model.tokenization.forceTokenization(lineNumber); const lineTokens2 = this.model.tokenization.getLineTokens(lineNumber); const endColumnOfLine = this.model.getLineMaxColumn(lineNumber) - 1; const scopedLineTokensAtEndColumn = createScopedLineTokens(lineTokens2, endColumnOfLine); return scopedLineTokensAtEndColumn; }; this.model.tokenization.forceTokenization(range2.startLineNumber); const lineTokens = this.model.tokenization.getLineTokens(range2.startLineNumber); const scopedLineTokens = createScopedLineTokens(lineTokens, range2.startColumn - 1); const emptyTokens = LineTokens.createEmpty("", scopedLineTokens.languageIdCodec); const previousLineNumber = range2.startLineNumber - 1; const isFirstLine = previousLineNumber === 0; if (isFirstLine) { return emptyTokens; } const canScopeExtendOnPreviousLine = scopedLineTokens.firstCharOffset === 0; if (!canScopeExtendOnPreviousLine) { return emptyTokens; } const scopedLineTokensAtEndColumnOfPreviousLine = getScopedLineTokensAtEndColumnOfLine(previousLineNumber); const doesLanguageContinueOnPreviousLine = scopedLineTokens.languageId === scopedLineTokensAtEndColumnOfPreviousLine.languageId; if (!doesLanguageContinueOnPreviousLine) { return emptyTokens; } const previousSlicedLineTokens = scopedLineTokensAtEndColumnOfPreviousLine.toIViewLineTokens(); const processedTokens = this.indentationLineProcessor.getProcessedTokens(previousSlicedLineTokens); return processedTokens; } } class IndentationLineProcessor { constructor(model, languageConfigurationService) { this.model = model; this.languageConfigurationService = languageConfigurationService; } /** * Get the processed line for the given line number and potentially adjust the indentation level. * Remove the language configuration brackets from the regex, string and comment tokens. */ getProcessedLine(lineNumber, newIndentation) { const replaceIndentation = (line, newIndentation2) => { const currentIndentation = getLeadingWhitespace(line); const adjustedLine = newIndentation2 + line.substring(currentIndentation.length); return adjustedLine; }; this.model.tokenization.forceTokenization?.(lineNumber); const tokens = this.model.tokenization.getLineTokens(lineNumber); let processedLine = this.getProcessedTokens(tokens).getLineContent(); if (newIndentation !== void 0) { processedLine = replaceIndentation(processedLine, newIndentation); } return processedLine; } /** * Process the line with the given tokens, remove the language configuration brackets from the regex, string and comment tokens. */ getProcessedTokens(tokens) { const shouldRemoveBracketsFromTokenType = (tokenType) => { return tokenType === 2 || tokenType === 3 || tokenType === 1; }; const languageId = tokens.getLanguageId(0); const bracketsConfiguration = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew; const bracketsRegExp = bracketsConfiguration.getBracketRegExp({ global: true }); const textAndMetadata = []; tokens.forEach((tokenIndex) => { const tokenType = tokens.getStandardTokenType(tokenIndex); let text2 = tokens.getTokenText(tokenIndex); if (shouldRemoveBracketsFromTokenType(tokenType)) { text2 = text2.replace(bracketsRegExp, ""); } const metadata = tokens.getMetadata(tokenIndex); textAndMetadata.push({ text: text2, metadata }); }); const processedLineTokens = LineTokens.createFromTextAndMetadata(textAndMetadata, tokens.languageIdCodec); return processedLineTokens; } } function isLanguageDifferentFromLineStart(model, position) { model.tokenization.forceTokenization(position.lineNumber); const lineTokens = model.tokenization.getLineTokens(position.lineNumber); const scopedLineTokens = createScopedLineTokens(lineTokens, position.column - 1); const doesScopeStartAtOffsetZero = scopedLineTokens.firstCharOffset === 0; const isScopedLanguageEqualToFirstLanguageOnLine = lineTokens.getLanguageId(0) === scopedLineTokens.languageId; const languageIsDifferentFromLineStart = !doesScopeStartAtOffsetZero && !isScopedLanguageEqualToFirstLanguageOnLine; return languageIsDifferentFromLineStart; } function getEnterAction(autoIndent, model, range2, languageConfigurationService) { model.tokenization.forceTokenization(range2.startLineNumber); const languageId = model.getLanguageIdAtPosition(range2.startLineNumber, range2.startColumn); const richEditSupport = languageConfigurationService.getLanguageConfiguration(languageId); if (!richEditSupport) { return null; } const indentationContextProcessor = new IndentationContextProcessor(model, languageConfigurationService); const processedContextTokens = indentationContextProcessor.getProcessedTokenContextAroundRange(range2); const previousLineText = processedContextTokens.previousLineProcessedTokens.getLineContent(); const beforeEnterText = processedContextTokens.beforeRangeProcessedTokens.getLineContent(); const afterEnterText = processedContextTokens.afterRangeProcessedTokens.getLineContent(); const enterResult = richEditSupport.onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText); if (!enterResult) { return null; } const indentAction = enterResult.indentAction; let appendText = enterResult.appendText; const removeText = enterResult.removeText || 0; if (!appendText) { if (indentAction === IndentAction$1.Indent || indentAction === IndentAction$1.IndentOutdent) { appendText = " "; } else { appendText = ""; } } else if (indentAction === IndentAction$1.Indent) { appendText = " " + appendText; } let indentation = getIndentationAtPosition(model, range2.startLineNumber, range2.startColumn); if (removeText) { indentation = indentation.substring(0, indentation.length - removeText); } return { indentAction, appendText, removeText, indentation }; } var __decorate$33 = function(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d = decorators[i2]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param$2Y = function(paramIndex, decorator) { return function(target, key) { decorator(target, key, paramIndex); }; }; var ShiftCommand_1; const repeatCache = /* @__PURE__ */ Object.create(null); function cachedStringRepeat(str, count) { if (count <= 0) { return ""; } if (!repeatCache[str]) { repeatCache[str] = ["", str]; } const cache = repeatCache[str]; for (let i2 = cache.length; i2 <= count; i2++) { cache[i2] = cache[i2 - 1] + str; } return cache[count]; } let ShiftCommand = ShiftCommand_1 = class ShiftCommand { static unshiftIndent(line, column, tabSize, indentSize, insertSpaces) { const contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(line, column, tabSize); if (insertSpaces) { const indent = cachedStringRepeat(" ", indentSize); const desiredTabStop = CursorColumns.prevIndentTabStop(contentStartVisibleColumn, indentSize); const indentCount = desiredTabStop / indentSize; return cachedStringRepeat(indent, indentCount); } else { const indent = " "; const desiredTabStop = CursorColumns.prevRenderTabStop(contentStartVisibleColumn, tabSize); const indentCount = desiredTabStop / tabSize; return cachedStringRepeat(indent, indentCount); } } static shiftIndent(line, column, tabSize, indentSize, insertSpaces) { const contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(line, column, tabSize); if (insertSpaces) { const indent = cachedStringRepeat(" ", indentSize); const desiredTabStop = CursorColumns.nextIndentTabStop(contentStartVisibleColumn, indentSize); const indentCount = desiredTabStop / indentSize; return cachedStringRepeat(indent, indentCount); } else { const indent = " "; const desiredTabStop = CursorColumns.nextRenderTabStop(contentStartVisibleColumn, tabSize); const indentCount = desiredTabStop / tabSize; return cachedStringRepeat(indent, indentCount); } } constructor(range2, opts, _languageConfigurationService) { this._languageConfigurationService = _languageConfigurationService; this._opts = opts; this._selection = range2; this._selectionId = null; this._useLastEditRangeForCursorEndPosition = false; this._selectionStartColumnStaysPut = false; } _addEditOperation(builder, range2, text2) { if (this._useLastEditRangeForCursorEndPosition) { builder.addTrackedEditOperation(range2, text2); } else { builder.addEditOperation(range2, text2); } } getEditOperations(model, builder) { const startLine = this._selection.startLineNumber; let endLine = this._selection.endLineNumber; if (this._selection.endColumn === 1 && startLine !== endLine) { endLine = endLine - 1; } const { tabSize, indentSize, insertSpaces } = this._opts; const shouldIndentEmptyLines = startLine === endLine; if (this._opts.useTabStops) { if (this._selection.isEmpty()) { if (/^\s*$/.test(model.getLineContent(startLine))) { this._useLastEditRangeForCursorEndPosition = true; } } let previousLineExtraSpaces = 0, extraSpaces = 0; for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++, previousLineExtraSpaces = extraSpaces) { extraSpaces = 0; const lineText = model.getLineContent(lineNumber); let indentationEndIndex = firstNonWhitespaceIndex(lineText); if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) { continue; } if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) { continue; } if (indentationEndIndex === -1) { indentationEndIndex = lineText.length; } if (lineNumber > 1) { const contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(lineText, indentationEndIndex + 1, tabSize); if (contentStartVisibleColumn % indentSize !== 0) { if (model.tokenization.isCheapToTokenize(lineNumber - 1)) { const enterAction = getEnterAction(this._opts.autoIndent, model, new Range$2(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1), lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)), this._languageConfigurationService); if (enterAction) { extraSpaces = previousLineExtraSpaces; if (enterAction.appendText) { for (let j = 0, lenJ = enterAction.appendText.length; j < lenJ && extraSpaces < indentSize; j++) { if (enterAction.appendText.charCodeAt(j) === 32) { extraSpaces++; } else { break; } } } if (enterAction.removeText) { extraSpaces = Math.max(0, extraSpaces - enterAction.removeText); } for (let j = 0; j < extraSpaces; j++) { if (indentationEndIndex === 0 || lineText.charCodeAt(indentationEndIndex - 1) !== 32) { break; } indentationEndIndex--; } } } } } if (this._opts.isUnshift && indentationEndIndex === 0) { continue; } let desiredIndent; if (this._opts.isUnshift) { desiredIndent = ShiftCommand_1.unshiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces); } else { desiredIndent = ShiftCommand_1.shiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces); } this._addEditOperation(builder, new Range$2(lineNumber, 1, lineNumber, indentationEndIndex + 1), desiredIndent); if (lineNumber === startLine && !this._selection.isEmpty()) { this._selectionStartColumnStaysPut = this._selection.startColumn <= indentationEndIndex + 1; } } } else { if (!this._opts.isUnshift && this._selection.isEmpty() && model.getLineLength(startLine) === 0) { this._useLastEditRangeForCursorEndPosition = true; } const oneIndent = insertSpaces ? cachedStringRepeat(" ", indentSize) : " "; for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++) { const lineText = model.getLineContent(lineNumber); let indentationEndIndex = firstNonWhitespaceIndex(lineText); if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) { continue; } if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) { continue; } if (indentationEndIndex === -1) { indentationEndIndex = lineText.length; } if (this._opts.isUnshift && indentationEndIndex === 0) { continue; } if (this._opts.isUnshift) { indentationEndIndex = Math.min(indentationEndIndex, indentSize); for (let i2 = 0; i2 < indentationEndIndex; i2++) { const chr = lineText.charCodeAt(i2); if (chr === 9) { indentationEndIndex = i2 + 1; break; } } this._addEditOperation(builder, new Range$2(lineNumber, 1, lineNumber, indentationEndIndex + 1), ""); } else { this._addEditOperation(builder, new Range$2(lineNumber, 1, lineNumber, 1), oneIndent); if (lineNumber === startLine && !this._selection.isEmpty()) { this._selectionStartColumnStaysPut = this._selection.startColumn === 1; } } } } this._selectionId = builder.trackSelection(this._selection); } computeCursorState(model, helper) { if (this._useLastEditRangeForCursorEndPosition) { const lastOp = helper.getInverseEditOperations()[0]; return new Selection$1(lastOp.range.endLineNumber, lastOp.range.endColumn, lastOp.range.endLineNumber, lastOp.range.endColumn); } const result = helper.getTrackedSelection(this._selectionId); if (this._selectionStartColumnStaysPut) { const initialStartColumn = this._selection.startColumn; const resultStartColumn = result.startColumn; if (resultStartColumn <= initialStartColumn) { return result; } if (result.getDirection() === 0) { return new Selection$1(result.startLineNumber, initialStartColumn, result.endLineNumber, result.endColumn); } return new Selection$1(result.endLineNumber, result.endColumn, result.startLineNumber, initialStartColumn); } return result; } }; ShiftCommand = ShiftCommand_1 = __decorate$33([ __param$2Y(2, ILanguageConfigurationService) ], ShiftCommand); class SurroundSelectionCommand { constructor(range2, charBeforeSelection, charAfterSelection) { this._range = range2; this._charBeforeSelection = charBeforeSelection; this._charAfterSelection = charAfterSelection; } getEditOperations(model, builder) { builder.addTrackedEditOperation(new Range$2(this._range.startLineNumber, this._range.startColumn, this._range.startLineNumber, this._range.startColumn), this._charBeforeSelection); builder.addTrackedEditOperation(new Range$2(this._range.endLineNumber, this._range.endColumn, this._range.endLineNumber, this._range.endColumn), this._charAfterSelection || null); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const firstOperationRange = inverseEditOperations[0].range; const secondOperationRange = inverseEditOperations[1].range; return new Selection$1(firstOperationRange.endLineNumber, firstOperationRange.endColumn, secondOperationRange.endLineNumber, secondOperationRange.endColumn - this._charAfterSelection.length); } } class CompositionSurroundSelectionCommand { constructor(_position, _text, _charAfter) { this._position = _position; this._text = _text; this._charAfter = _charAfter; } getEditOperations(model, builder) { builder.addTrackedEditOperation(new Range$2(this._position.lineNumber, this._position.column, this._position.lineNumber, this._position.column), this._text + this._charAfter); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const opRange = inverseEditOperations[0].range; return new Selection$1(opRange.endLineNumber, opRange.startColumn, opRange.endLineNumber, opRange.endColumn - this._charAfter.length); } } function getPrecedingValidLine(model, lineNumber, processedIndentRulesSupport) { const languageId = model.tokenization.getLanguageIdAtPosition(lineNumber, 0); if (lineNumber > 1) { let lastLineNumber; let resultLineNumber = -1; for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) { if (model.tokenization.getLanguageIdAtPosition(lastLineNumber, 0) !== languageId) { return resultLineNumber; } const text2 = model.getLineContent(lastLineNumber); if (processedIndentRulesSupport.shouldIgnore(lastLineNumber) || /^\s+$/.test(text2) || text2 === "") { resultLineNumber = lastLineNumber; continue; } return lastLineNumber; } } return -1; } function getInheritIndentForLine(autoIndent, model, lineNumber, honorIntentialIndent = true, languageConfigurationService) { if (autoIndent < 4) { return null; } const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(model.tokenization.getLanguageId()).indentRulesSupport; if (!indentRulesSupport) { return null; } const processedIndentRulesSupport = new ProcessedIndentRulesSupport(model, indentRulesSupport, languageConfigurationService); if (lineNumber <= 1) { return { indentation: "", action: null }; } for (let priorLineNumber = lineNumber - 1; priorLineNumber > 0; priorLineNumber--) { if (model.getLineContent(priorLineNumber) !== "") { break; } if (priorLineNumber === 1) { return { indentation: "", action: null }; } } const precedingUnIgnoredLine = getPrecedingValidLine(model, lineNumber, processedIndentRulesSupport); if (precedingUnIgnoredLine < 0) { return null; } else if (precedingUnIgnoredLine < 1) { return { indentation: "", action: null }; } if (processedIndentRulesSupport.shouldIncrease(precedingUnIgnoredLine) || processedIndentRulesSupport.shouldIndentNextLine(precedingUnIgnoredLine)) { const precedingUnIgnoredLineContent = model.getLineContent(precedingUnIgnoredLine); return { indentation: getLeadingWhitespace(precedingUnIgnoredLineContent), action: IndentAction$1.Indent, line: precedingUnIgnoredLine }; } else if (processedIndentRulesSupport.shouldDecrease(precedingUnIgnoredLine)) { const precedingUnIgnoredLineContent = model.getLineContent(precedingUnIgnoredLine); return { indentation: getLeadingWhitespace(precedingUnIgnoredLineContent), action: null, line: precedingUnIgnoredLine }; } else { if (precedingUnIgnoredLine === 1) { return { indentation: getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)), action: null, line: precedingUnIgnoredLine }; } const previousLine = precedingUnIgnoredLine - 1; const previousLineIndentMetadata = indentRulesSupport.getIndentMetadata(model.getLineContent(previousLine)); if (!(previousLineIndentMetadata & (1 | 2)) && previousLineIndentMetadata & 4) { let stopLine = 0; for (let i2 = previousLine - 1; i2 > 0; i2--) { if (processedIndentRulesSupport.shouldIndentNextLine(i2)) { continue; } stopLine = i2; break; } return { indentation: getLeadingWhitespace(model.getLineContent(stopLine + 1)), action: null, line: stopLine + 1 }; } if (honorIntentialIndent) { return { indentation: getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)), action: null, line: precedingUnIgnoredLine }; } else { for (let i2 = precedingUnIgnoredLine; i2 > 0; i2--) { if (processedIndentRulesSupport.shouldIncrease(i2)) { return { indentation: getLeadingWhitespace(model.getLineContent(i2)), action: IndentAction$1.Indent, line: i2 }; } else if (processedIndentRulesSupport.shouldIndentNextLine(i2)) { let stopLine = 0; for (let j = i2 - 1; j > 0; j--) { if (processedIndentRulesSupport.shouldIndentNextLine(i2)) { continue; } stopLine = j; break; } return { indentation: getLeadingWhitespace(model.getLineContent(stopLine + 1)), action: null, line: stopLine + 1 }; } else if (processedIndentRulesSupport.shouldDecrease(i2)) { return { indentation: getLeadingWhitespace(model.getLineContent(i2)), action: null, line: i2 }; } } return { indentation: getLeadingWhitespace(model.getLineContent(1)), action: null, line: 1 }; } } } function getGoodIndentForLine(autoIndent, virtualModel, languageId, lineNumber, indentConverter, languageConfigurationService) { if (autoIndent < 4) { return null; } const richEditSupport = languageConfigurationService.getLanguageConfiguration(languageId); if (!richEditSupport) { return null; } const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(languageId).indentRulesSupport; if (!indentRulesSupport) { return null; } const processedIndentRulesSupport = new ProcessedIndentRulesSupport(virtualModel, indentRulesSupport, languageConfigurationService); const indent = getInheritIndentForLine(autoIndent, virtualModel, lineNumber, void 0, languageConfigurationService); if (indent) { const inheritLine = indent.line; if (inheritLine !== void 0) { let shouldApplyEnterRules = true; for (let inBetweenLine = inheritLine; inBetweenLine < lineNumber - 1; inBetweenLine++) { if (!/^\s*$/.test(virtualModel.getLineContent(inBetweenLine))) { shouldApplyEnterRules = false; break; } } if (shouldApplyEnterRules) { const enterResult = richEditSupport.onEnter(autoIndent, "", virtualModel.getLineContent(inheritLine), ""); if (enterResult) { let indentation = getLeadingWhitespace(virtualModel.getLineContent(inheritLine)); if (enterResult.removeText) { indentation = indentation.substring(0, indentation.length - enterResult.removeText); } if (enterResult.indentAction === IndentAction$1.Indent || enterResult.indentAction === IndentAction$1.IndentOutdent) { indentation = indentConverter.shiftIndent(indentation); } else if (enterResult.indentAction === IndentAction$1.Outdent) { indentation = indentConverter.unshiftIndent(indentation); } if (processedIndentRulesSupport.shouldDecrease(lineNumber)) { indentation = indentConverter.unshiftIndent(indentation); } if (enterResult.appendText) { indentation += enterResult.appendText; } return getLeadingWhitespace(indentation); } } } if (processedIndentRulesSupport.shouldDecrease(lineNumber)) { if (indent.action === IndentAction$1.Indent) { return indent.indentation; } else { return indentConverter.unshiftIndent(indent.indentation); } } else { if (indent.action === IndentAction$1.Indent) { return indentConverter.shiftIndent(indent.indentation); } else { return indent.indentation; } } } return null; } function getIndentForEnter(autoIndent, model, range2, indentConverter, languageConfigurationService) { if (autoIndent < 4) { return null; } const languageId = model.getLanguageIdAtPosition(range2.startLineNumber, range2.startColumn); const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(languageId).indentRulesSupport; if (!indentRulesSupport) { return null; } model.tokenization.forceTokenization(range2.startLineNumber); const indentationContextProcessor = new IndentationContextProcessor(model, languageConfigurationService); const processedContextTokens = indentationContextProcessor.getProcessedTokenContextAroundRange(range2); const afterEnterProcessedTokens = processedContextTokens.afterRangeProcessedTokens; const beforeEnterProcessedTokens = processedContextTokens.beforeRangeProcessedTokens; const beforeEnterIndent = getLeadingWhitespace(beforeEnterProcessedTokens.getLineContent()); const virtualModel = createVirtualModelWithModifiedTokensAtLine(model, range2.startLineNumber, beforeEnterProcessedTokens); const languageIsDifferentFromLineStart = isLanguageDifferentFromLineStart(model, range2.getStartPosition()); const currentLine = model.getLineContent(range2.startLineNumber); const currentLineIndent = getLeadingWhitespace(currentLine); const afterEnterAction = getInheritIndentForLine(autoIndent, virtualModel, range2.startLineNumber + 1, void 0, languageConfigurationService); if (!afterEnterAction) { const beforeEnter = languageIsDifferentFromLineStart ? currentLineIndent : beforeEnterIndent; return { beforeEnter, afterEnter: beforeEnter }; } let afterEnterIndent = languageIsDifferentFromLineStart ? currentLineIndent : afterEnterAction.indentation; if (afterEnterAction.action === IndentAction$1.Indent) { afterEnterIndent = indentConverter.shiftIndent(afterEnterIndent); } if (indentRulesSupport.shouldDecrease(afterEnterProcessedTokens.getLineContent())) { afterEnterIndent = indentConverter.unshiftIndent(afterEnterIndent); } return { beforeEnter: languageIsDifferentFromLineStart ? currentLineIndent : beforeEnterIndent, afterEnter: afterEnterIndent }; } function getIndentActionForType(cursorConfig, model, range2, ch, indentConverter, languageConfigurationService) { const autoIndent = cursorConfig.autoIndent; if (autoIndent < 4) { return null; } const languageIsDifferentFromLineStart = isLanguageDifferentFromLineStart(model, range2.getStartPosition()); if (languageIsDifferentFromLineStart) { return null; } const languageId = model.getLanguageIdAtPosition(range2.startLineNumber, range2.startColumn); const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(languageId).indentRulesSupport; if (!indentRulesSupport) { return null; } const indentationContextProcessor = new IndentationContextProcessor(model, languageConfigurationService); const processedContextTokens = indentationContextProcessor.getProcessedTokenContextAroundRange(range2); const beforeRangeText = processedContextTokens.beforeRangeProcessedTokens.getLineContent(); const afterRangeText = processedContextTokens.afterRangeProcessedTokens.getLineContent(); const textAroundRange = beforeRangeText + afterRangeText; const textAroundRangeWithCharacter = beforeRangeText + ch + afterRangeText; if (!indentRulesSupport.shouldDecrease(textAroundRange) && indentRulesSupport.shouldDecrease(textAroundRangeWithCharacter)) { const r = getInheritIndentForLine(autoIndent, model, range2.startLineNumber, false, languageConfigurationService); if (!r) { return null; } let indentation = r.indentation; if (r.action !== IndentAction$1.Indent) { indentation = indentConverter.unshiftIndent(indentation); } return indentation; } const previousLineNumber = range2.startLineNumber - 1; if (previousLineNumber > 0) { const previousLine = model.getLineContent(previousLineNumber); if (indentRulesSupport.shouldIndentNextLine(previousLine) && indentRulesSupport.shouldIncrease(textAroundRangeWithCharacter)) { const inheritedIndentationData = getInheritIndentForLine(autoIndent, model, range2.startLineNumber, false, languageConfigurationService); const inheritedIndentation = inheritedIndentationData?.indentation; if (inheritedIndentation !== void 0) { const currentLine = model.getLineContent(range2.startLineNumber); const actualCurrentIndentation = getLeadingWhitespace(currentLine); const inferredCurrentIndentation = indentConverter.shiftIndent(inheritedIndentation); const inferredIndentationEqualsActual = inferredCurrentIndentation === actualCurrentIndentation; const textAroundRangeContainsOnlyWhitespace = /^\s*$/.test(textAroundRange); const autoClosingPairs = cursorConfig.autoClosingPairs.autoClosingPairsOpenByEnd.get(ch); const autoClosingPairExists = autoClosingPairs && autoClosingPairs.length > 0; const isChFirstNonWhitespaceCharacterAndInAutoClosingPair = autoClosingPairExists && textAroundRangeContainsOnlyWhitespace; if (inferredIndentationEqualsActual && isChFirstNonWhitespaceCharacterAndInAutoClosingPair) { return inheritedIndentation; } } } } return null; } function getIndentMetadata(model, lineNumber, languageConfigurationService) { const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).indentRulesSupport; if (!indentRulesSupport) { return null; } if (lineNumber < 1 || lineNumber > model.getLineCount()) { return null; } return indentRulesSupport.getIndentMetadata(model.getLineContent(lineNumber)); } function createVirtualModelWithModifiedTokensAtLine(model, modifiedLineNumber, modifiedTokens) { const virtualModel = { tokenization: { getLineTokens: (lineNumber) => { if (lineNumber === modifiedLineNumber) { return modifiedTokens; } else { return model.tokenization.getLineTokens(lineNumber); } }, getLanguageId: () => { return model.getLanguageId(); }, getLanguageIdAtPosition: (lineNumber, column) => { return model.getLanguageIdAtPosition(lineNumber, column); } }, getLineContent: (lineNumber) => { if (lineNumber === modifiedLineNumber) { return modifiedTokens.getLineContent(); } else { return model.getLineContent(lineNumber); } } }; return virtualModel; } class AutoIndentOperation { static getEdits(config, model, selections, ch, isDoingComposition) { if (!isDoingComposition && this._isAutoIndentType(config, model, selections)) { const indentationForSelections = []; for (const selection of selections) { const indentation = this._findActualIndentationForSelection(config, model, selection, ch); if (indentation === null) { return; } indentationForSelections.push({ selection, indentation }); } const autoClosingPairClose = AutoClosingOpenCharTypeOperation.getAutoClosingPairClose(config, model, selections, ch, false); return this._getIndentationAndAutoClosingPairEdits(config, model, indentationForSelections, ch, autoClosingPairClose); } return; } static _isAutoIndentType(config, model, selections) { if (config.autoIndent < 4) { return false; } for (let i2 = 0, len = selections.length; i2 < len; i2++) { if (!model.tokenization.isCheapToTokenize(selections[i2].getEndPosition().lineNumber)) { return false; } } return true; } static _findActualIndentationForSelection(config, model, selection, ch) { const actualIndentation = getIndentActionForType(config, model, selection, ch, { shiftIndent: (indentation) => { return shiftIndent(config, indentation); }, unshiftIndent: (indentation) => { return unshiftIndent(config, indentation); } }, config.languageConfigurationService); if (actualIndentation === null) { return null; } const currentIndentation = getIndentationAtPosition(model, selection.startLineNumber, selection.startColumn); if (actualIndentation === config.normalizeIndentation(currentIndentation)) { return null; } return actualIndentation; } static _getIndentationAndAutoClosingPairEdits(config, model, indentationForSelections, ch, autoClosingPairClose) { const commands = indentationForSelections.map(({ selection, indentation }) => { if (autoClosingPairClose !== null) { const indentationEdit = this._getEditFromIndentationAndSelection(config, model, indentation, selection, ch, false); return new TypeWithIndentationAndAutoClosingCommand(indentationEdit, selection, ch, autoClosingPairClose); } else { const indentationEdit = this._getEditFromIndentationAndSelection(config, model, indentation, selection, ch, true); return typeCommand(indentationEdit.range, indentationEdit.text, false); } }); const editOptions = { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false }; return new EditOperationResult(4, commands, editOptions); } static _getEditFromIndentationAndSelection(config, model, indentation, selection, ch, includeChInEdit = true) { const startLineNumber = selection.startLineNumber; const firstNonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(startLineNumber); let text2 = config.normalizeIndentation(indentation); if (firstNonWhitespaceColumn !== 0) { const startLine = model.getLineContent(startLineNumber); text2 += startLine.substring(firstNonWhitespaceColumn - 1, selection.startColumn - 1); } text2 += includeChInEdit ? ch : ""; const range2 = new Range$2(startLineNumber, 1, selection.endLineNumber, selection.endColumn); return { range: range2, text: text2 }; } } class AutoClosingOvertypeOperation { static getEdits(prevEditOperationType, config, model, selections, autoClosedCharacters, ch) { if (isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) { return this._runAutoClosingOvertype(prevEditOperationType, selections, ch); } return; } static _runAutoClosingOvertype(prevEditOperationType, selections, ch) { const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { const selection = selections[i2]; const position = selection.getPosition(); const typeSelection = new Range$2(position.lineNumber, position.column, position.lineNumber, position.column + 1); commands[i2] = new ReplaceCommand(typeSelection, ch); } return new EditOperationResult(4, commands, { shouldPushStackElementBefore: shouldPushStackElementBetween( prevEditOperationType, 4 /* EditOperationType.TypingOther */ ), shouldPushStackElementAfter: false }); } } class AutoClosingOvertypeWithInterceptorsOperation { static getEdits(config, model, selections, autoClosedCharacters, ch) { if (isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch)) { const commands = selections.map((s) => new ReplaceCommand(new Range$2(s.positionLineNumber, s.positionColumn, s.positionLineNumber, s.positionColumn + 1), "", false)); return new EditOperationResult(4, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false }); } return; } } class AutoClosingOpenCharTypeOperation { static getEdits(config, model, selections, ch, chIsAlreadyTyped, isDoingComposition) { if (!isDoingComposition) { const autoClosingPairClose = this.getAutoClosingPairClose(config, model, selections, ch, chIsAlreadyTyped); if (autoClosingPairClose !== null) { return this._runAutoClosingOpenCharType(selections, ch, chIsAlreadyTyped, autoClosingPairClose); } } return; } static _runAutoClosingOpenCharType(selections, ch, chIsAlreadyTyped, autoClosingPairClose) { const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { const selection = selections[i2]; commands[i2] = new TypeWithAutoClosingCommand(selection, ch, !chIsAlreadyTyped, autoClosingPairClose); } return new EditOperationResult(4, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false }); } static getAutoClosingPairClose(config, model, selections, ch, chIsAlreadyTyped) { for (const selection of selections) { if (!selection.isEmpty()) { return null; } } const positions = selections.map((s) => { const position = s.getPosition(); if (chIsAlreadyTyped) { return { lineNumber: position.lineNumber, beforeColumn: position.column - ch.length, afterColumn: position.column }; } else { return { lineNumber: position.lineNumber, beforeColumn: position.column, afterColumn: position.column }; } }); const pair = this._findAutoClosingPairOpen(config, model, positions.map((p) => new Position$1(p.lineNumber, p.beforeColumn)), ch); if (!pair) { return null; } let autoCloseConfig; let shouldAutoCloseBefore; const chIsQuote = isQuote(ch); if (chIsQuote) { autoCloseConfig = config.autoClosingQuotes; shouldAutoCloseBefore = config.shouldAutoCloseBefore.quote; } else { const pairIsForComments = config.blockCommentStartToken ? pair.open.includes(config.blockCommentStartToken) : false; if (pairIsForComments) { autoCloseConfig = config.autoClosingComments; shouldAutoCloseBefore = config.shouldAutoCloseBefore.comment; } else { autoCloseConfig = config.autoClosingBrackets; shouldAutoCloseBefore = config.shouldAutoCloseBefore.bracket; } } if (autoCloseConfig === "never") { return null; } const containedPair = this._findContainedAutoClosingPair(config, pair); const containedPairClose = containedPair ? containedPair.close : ""; let isContainedPairPresent = true; for (const position of positions) { const { lineNumber, beforeColumn, afterColumn } = position; const lineText = model.getLineContent(lineNumber); const lineBefore = lineText.substring(0, beforeColumn - 1); const lineAfter = lineText.substring(afterColumn - 1); if (!lineAfter.startsWith(containedPairClose)) { isContainedPairPresent = false; } if (lineAfter.length > 0) { const characterAfter = lineAfter.charAt(0); const isBeforeCloseBrace = this._isBeforeClosingBrace(config, lineAfter); if (!isBeforeCloseBrace && !shouldAutoCloseBefore(characterAfter)) { return null; } } if (pair.open.length === 1 && (ch === "'" || ch === '"') && autoCloseConfig !== "always") { const wordSeparators2 = getMapForWordSeparators(config.wordSeparators, []); if (lineBefore.length > 0) { const characterBefore = lineBefore.charCodeAt(lineBefore.length - 1); if (wordSeparators2.get(characterBefore) === 0) { return null; } } } if (!model.tokenization.isCheapToTokenize(lineNumber)) { return null; } model.tokenization.forceTokenization(lineNumber); const lineTokens = model.tokenization.getLineTokens(lineNumber); const scopedLineTokens = createScopedLineTokens(lineTokens, beforeColumn - 1); if (!pair.shouldAutoClose(scopedLineTokens, beforeColumn - scopedLineTokens.firstCharOffset)) { return null; } const neutralCharacter = pair.findNeutralCharacter(); if (neutralCharacter) { const tokenType = model.tokenization.getTokenTypeIfInsertingCharacter(lineNumber, beforeColumn, neutralCharacter); if (!pair.isOK(tokenType)) { return null; } } } if (isContainedPairPresent) { return pair.close.substring(0, pair.close.length - containedPairClose.length); } else { return pair.close; } } /** * Find another auto-closing pair that is contained by the one passed in. * * e.g. when having [(,)] and [(*,*)] as auto-closing pairs * this method will find [(,)] as a containment pair for [(*,*)] */ static _findContainedAutoClosingPair(config, pair) { if (pair.open.length <= 1) { return null; } const lastChar = pair.close.charAt(pair.close.length - 1); const candidates = config.autoClosingPairs.autoClosingPairsCloseByEnd.get(lastChar) || []; let result = null; for (const candidate of candidates) { if (candidate.open !== pair.open && pair.open.includes(candidate.open) && pair.close.endsWith(candidate.close)) { if (!result || candidate.open.length > result.open.length) { result = candidate; } } } return result; } /** * Determine if typing `ch` at all `positions` in the `model` results in an * auto closing open sequence being typed. * * Auto closing open sequences can consist of multiple characters, which * can lead to ambiguities. In such a case, the longest auto-closing open * sequence is returned. */ static _findAutoClosingPairOpen(config, model, positions, ch) { const candidates = config.autoClosingPairs.autoClosingPairsOpenByEnd.get(ch); if (!candidates) { return null; } let result = null; for (const candidate of candidates) { if (result === null || candidate.open.length > result.open.length) { let candidateIsMatch = true; for (const position of positions) { const relevantText = model.getValueInRange(new Range$2(position.lineNumber, position.column - candidate.open.length + 1, position.lineNumber, position.column)); if (relevantText + ch !== candidate.open) { candidateIsMatch = false; break; } } if (candidateIsMatch) { result = candidate; } } } return result; } static _isBeforeClosingBrace(config, lineAfter) { const nextChar = lineAfter.charAt(0); const potentialStartingBraces = config.autoClosingPairs.autoClosingPairsOpenByStart.get(nextChar) || []; const potentialClosingBraces = config.autoClosingPairs.autoClosingPairsCloseByStart.get(nextChar) || []; const isBeforeStartingBrace = potentialStartingBraces.some((x) => lineAfter.startsWith(x.open)); const isBeforeClosingBrace = potentialClosingBraces.some((x) => lineAfter.startsWith(x.close)); return !isBeforeStartingBrace && isBeforeClosingBrace; } } class CompositionEndOvertypeOperation { static getEdits(config, compositions) { const isOvertypeMode = config.inputMode === "overtype"; if (!isOvertypeMode) { return null; } const commands = compositions.map((composition) => new ReplaceOvertypeCommandOnCompositionEnd(composition.insertedTextRange)); return new EditOperationResult(4, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false }); } } class SurroundSelectionOperation { static getEdits(config, model, selections, ch, isDoingComposition) { if (!isDoingComposition && this._isSurroundSelectionType(config, model, selections, ch)) { return this._runSurroundSelectionType(config, selections, ch); } return; } static _runSurroundSelectionType(config, selections, ch) { const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { const selection = selections[i2]; const closeCharacter = config.surroundingPairs[ch]; commands[i2] = new SurroundSelectionCommand(selection, ch, closeCharacter); } return new EditOperationResult(0, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: true }); } static _isSurroundSelectionType(config, model, selections, ch) { if (!shouldSurroundChar(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) { return false; } const isTypingAQuoteCharacter = isQuote(ch); for (const selection of selections) { if (selection.isEmpty()) { return false; } let selectionContainsOnlyWhitespace = true; for (let lineNumber = selection.startLineNumber; lineNumber <= selection.endLineNumber; lineNumber++) { const lineText = model.getLineContent(lineNumber); const startIndex = lineNumber === selection.startLineNumber ? selection.startColumn - 1 : 0; const endIndex = lineNumber === selection.endLineNumber ? selection.endColumn - 1 : lineText.length; const selectedText = lineText.substring(startIndex, endIndex); if (/[^ \t]/.test(selectedText)) { selectionContainsOnlyWhitespace = false; break; } } if (selectionContainsOnlyWhitespace) { return false; } if (isTypingAQuoteCharacter && selection.startLineNumber === selection.endLineNumber && selection.startColumn + 1 === selection.endColumn) { const selectionText = model.getValueInRange(selection); if (isQuote(selectionText)) { return false; } } } return true; } } class InterceptorElectricCharOperation { static getEdits(prevEditOperationType, config, model, selections, ch, isDoingComposition) { if (!isDoingComposition && this._isTypeInterceptorElectricChar(config, model, selections)) { const r = this._typeInterceptorElectricChar(prevEditOperationType, config, model, selections[0], ch); if (r) { return r; } } return; } static _isTypeInterceptorElectricChar(config, model, selections) { if (selections.length === 1 && model.tokenization.isCheapToTokenize(selections[0].getEndPosition().lineNumber)) { return true; } return false; } static _typeInterceptorElectricChar(prevEditOperationType, config, model, selection, ch) { if (!config.electricChars.hasOwnProperty(ch) || !selection.isEmpty()) { return null; } const position = selection.getPosition(); model.tokenization.forceTokenization(position.lineNumber); const lineTokens = model.tokenization.getLineTokens(position.lineNumber); let electricAction; try { electricAction = config.onElectricCharacter(ch, lineTokens, position.column); } catch (e) { onUnexpectedError(e); return null; } if (!electricAction) { return null; } if (electricAction.matchOpenBracket) { const endColumn = (lineTokens.getLineContent() + ch).lastIndexOf(electricAction.matchOpenBracket) + 1; const match2 = model.bracketPairs.findMatchingBracketUp( electricAction.matchOpenBracket, { lineNumber: position.lineNumber, column: endColumn }, 500 /* give at most 500ms to compute */ ); if (match2) { if (match2.startLineNumber === position.lineNumber) { return null; } const matchLine = model.getLineContent(match2.startLineNumber); const matchLineIndentation = getLeadingWhitespace(matchLine); const newIndentation = config.normalizeIndentation(matchLineIndentation); const lineText = model.getLineContent(position.lineNumber); const lineFirstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(position.lineNumber) || position.column; const prefix = lineText.substring(lineFirstNonBlankColumn - 1, position.column - 1); const typeText = newIndentation + prefix + ch; const typeSelection = new Range$2(position.lineNumber, 1, position.lineNumber, position.column); const command = new ReplaceCommand(typeSelection, typeText); return new EditOperationResult(getTypingOperation(typeText, prevEditOperationType), [command], { shouldPushStackElementBefore: false, shouldPushStackElementAfter: true }); } } return null; } } class SimpleCharacterTypeOperation { static getEdits(config, prevEditOperationType, selections, ch, isDoingComposition) { const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { const ChosenReplaceCommand = config.inputMode === "overtype" && !isDoingComposition ? ReplaceOvertypeCommand : ReplaceCommand; commands[i2] = new ChosenReplaceCommand(selections[i2], ch); } const opType = getTypingOperation(ch, prevEditOperationType); return new EditOperationResult(opType, commands, { shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, opType), shouldPushStackElementAfter: false }); } } class EnterOperation { static getEdits(config, model, selections, ch, isDoingComposition) { if (!isDoingComposition && ch === "\n") { const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { commands[i2] = this._enter(config, model, false, selections[i2]); } return new EditOperationResult(4, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false }); } return; } static _enter(config, model, keepPosition, range2) { if (config.autoIndent === 0) { return typeCommand(range2, "\n", keepPosition); } if (!model.tokenization.isCheapToTokenize(range2.getStartPosition().lineNumber) || config.autoIndent === 1) { const lineText2 = model.getLineContent(range2.startLineNumber); const indentation2 = getLeadingWhitespace(lineText2).substring(0, range2.startColumn - 1); return typeCommand(range2, "\n" + config.normalizeIndentation(indentation2), keepPosition); } const r = getEnterAction(config.autoIndent, model, range2, config.languageConfigurationService); if (r) { if (r.indentAction === IndentAction$1.None) { return typeCommand(range2, "\n" + config.normalizeIndentation(r.indentation + r.appendText), keepPosition); } else if (r.indentAction === IndentAction$1.Indent) { return typeCommand(range2, "\n" + config.normalizeIndentation(r.indentation + r.appendText), keepPosition); } else if (r.indentAction === IndentAction$1.IndentOutdent) { const normalIndent = config.normalizeIndentation(r.indentation); const increasedIndent = config.normalizeIndentation(r.indentation + r.appendText); const typeText = "\n" + increasedIndent + "\n" + normalIndent; if (keepPosition) { return new ReplaceCommandWithoutChangingPosition(range2, typeText, true); } else { return new ReplaceCommandWithOffsetCursorState(range2, typeText, -1, increasedIndent.length - normalIndent.length, true); } } else if (r.indentAction === IndentAction$1.Outdent) { const actualIndentation = unshiftIndent(config, r.indentation); return typeCommand(range2, "\n" + config.normalizeIndentation(actualIndentation + r.appendText), keepPosition); } } const lineText = model.getLineContent(range2.startLineNumber); const indentation = getLeadingWhitespace(lineText).substring(0, range2.startColumn - 1); if (config.autoIndent >= 4) { const ir = getIndentForEnter(config.autoIndent, model, range2, { unshiftIndent: (indent) => { return unshiftIndent(config, indent); }, shiftIndent: (indent) => { return shiftIndent(config, indent); }, normalizeIndentation: (indent) => { return config.normalizeIndentation(indent); } }, config.languageConfigurationService); if (ir) { let oldEndViewColumn = config.visibleColumnFromColumn(model, range2.getEndPosition()); const oldEndColumn = range2.endColumn; const newLineContent = model.getLineContent(range2.endLineNumber); const firstNonWhitespace = firstNonWhitespaceIndex(newLineContent); if (firstNonWhitespace >= 0) { range2 = range2.setEndPosition(range2.endLineNumber, Math.max(range2.endColumn, firstNonWhitespace + 1)); } else { range2 = range2.setEndPosition(range2.endLineNumber, model.getLineMaxColumn(range2.endLineNumber)); } if (keepPosition) { return new ReplaceCommandWithoutChangingPosition(range2, "\n" + config.normalizeIndentation(ir.afterEnter), true); } else { let offset = 0; if (oldEndColumn <= firstNonWhitespace + 1) { if (!config.insertSpaces) { oldEndViewColumn = Math.ceil(oldEndViewColumn / config.indentSize); } offset = Math.min(oldEndViewColumn + 1 - config.normalizeIndentation(ir.afterEnter).length - 1, 0); } return new ReplaceCommandWithOffsetCursorState(range2, "\n" + config.normalizeIndentation(ir.afterEnter), 0, offset, true); } } } return typeCommand(range2, "\n" + config.normalizeIndentation(indentation), keepPosition); } static lineInsertBefore(config, model, selections) { if (model === null || selections === null) { return []; } const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { let lineNumber = selections[i2].positionLineNumber; if (lineNumber === 1) { commands[i2] = new ReplaceCommandWithoutChangingPosition(new Range$2(1, 1, 1, 1), "\n"); } else { lineNumber--; const column = model.getLineMaxColumn(lineNumber); commands[i2] = this._enter(config, model, false, new Range$2(lineNumber, column, lineNumber, column)); } } return commands; } static lineInsertAfter(config, model, selections) { if (model === null || selections === null) { return []; } const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { const lineNumber = selections[i2].positionLineNumber; const column = model.getLineMaxColumn(lineNumber); commands[i2] = this._enter(config, model, false, new Range$2(lineNumber, column, lineNumber, column)); } return commands; } static lineBreakInsert(config, model, selections) { const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { commands[i2] = this._enter(config, model, true, selections[i2]); } return commands; } } class PasteOperation { static getEdits(config, model, selections, text2, pasteOnNewLine, multicursorText) { const distributedPaste = this._distributePasteToCursors(config, selections, text2, pasteOnNewLine, multicursorText); if (distributedPaste) { selections = selections.sort(Range$2.compareRangesUsingStarts); return this._distributedPaste(config, model, selections, distributedPaste); } else { return this._simplePaste(config, model, selections, text2, pasteOnNewLine); } } static _distributePasteToCursors(config, selections, text2, pasteOnNewLine, multicursorText) { if (pasteOnNewLine) { return null; } if (selections.length === 1) { return null; } if (multicursorText && multicursorText.length === selections.length) { return multicursorText; } if (config.multiCursorPaste === "spread") { if (text2.charCodeAt(text2.length - 1) === 10) { text2 = text2.substring(0, text2.length - 1); } if (text2.charCodeAt(text2.length - 1) === 13) { text2 = text2.substring(0, text2.length - 1); } const lines = splitLines(text2); if (lines.length === selections.length) { return lines; } } return null; } static _distributedPaste(config, model, selections, text2) { const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { const shouldOvertypeOnPaste = config.overtypeOnPaste && config.inputMode === "overtype"; const ChosenReplaceCommand = shouldOvertypeOnPaste ? ReplaceOvertypeCommand : ReplaceCommand; commands[i2] = new ChosenReplaceCommand(selections[i2], text2[i2]); } return new EditOperationResult(0, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: true }); } static _simplePaste(config, model, selections, text2, pasteOnNewLine) { const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { const selection = selections[i2]; const position = selection.getPosition(); if (pasteOnNewLine && !selection.isEmpty()) { pasteOnNewLine = false; } if (pasteOnNewLine && text2.indexOf("\n") !== text2.length - 1) { pasteOnNewLine = false; } if (pasteOnNewLine) { const typeSelection = new Range$2(position.lineNumber, 1, position.lineNumber, 1); commands[i2] = new ReplaceCommandThatPreservesSelection(typeSelection, text2, selection, true); } else { const shouldOvertypeOnPaste = config.overtypeOnPaste && config.inputMode === "overtype"; const ChosenReplaceCommand = shouldOvertypeOnPaste ? ReplaceOvertypeCommand : ReplaceCommand; commands[i2] = new ChosenReplaceCommand(selection, text2); } } return new EditOperationResult(0, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: true }); } } class CompositionOperation { static getEdits(prevEditOperationType, config, model, selections, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) { const commands = selections.map((selection) => this._compositionType(model, selection, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta)); return new EditOperationResult(4, commands, { shouldPushStackElementBefore: shouldPushStackElementBetween( prevEditOperationType, 4 /* EditOperationType.TypingOther */ ), shouldPushStackElementAfter: false }); } static _compositionType(model, selection, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) { if (!selection.isEmpty()) { return null; } const pos = selection.getPosition(); const startColumn = Math.max(1, pos.column - replacePrevCharCnt); const endColumn = Math.min(model.getLineMaxColumn(pos.lineNumber), pos.column + replaceNextCharCnt); const range2 = new Range$2(pos.lineNumber, startColumn, pos.lineNumber, endColumn); return new ReplaceCommandWithOffsetCursorState(range2, text2, 0, positionDelta); } } class TypeWithoutInterceptorsOperation { static getEdits(prevEditOperationType, selections, str) { const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { commands[i2] = new ReplaceCommand(selections[i2], str); } const opType = getTypingOperation(str, prevEditOperationType); return new EditOperationResult(opType, commands, { shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, opType), shouldPushStackElementAfter: false }); } } class TabOperation { static getCommands(config, model, selections) { const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { const selection = selections[i2]; if (selection.isEmpty()) { const lineText = model.getLineContent(selection.startLineNumber); if (/^\s*$/.test(lineText) && model.tokenization.isCheapToTokenize(selection.startLineNumber)) { let goodIndent = this._goodIndentForLine(config, model, selection.startLineNumber); goodIndent = goodIndent || " "; const possibleTypeText = config.normalizeIndentation(goodIndent); if (!lineText.startsWith(possibleTypeText)) { commands[i2] = new ReplaceCommand(new Range$2(selection.startLineNumber, 1, selection.startLineNumber, lineText.length + 1), possibleTypeText, true); continue; } } commands[i2] = this._replaceJumpToNextIndent(config, model, selection, true); } else { if (selection.startLineNumber === selection.endLineNumber) { const lineMaxColumn = model.getLineMaxColumn(selection.startLineNumber); if (selection.startColumn !== 1 || selection.endColumn !== lineMaxColumn) { commands[i2] = this._replaceJumpToNextIndent(config, model, selection, false); continue; } } commands[i2] = new ShiftCommand(selection, { isUnshift: false, tabSize: config.tabSize, indentSize: config.indentSize, insertSpaces: config.insertSpaces, useTabStops: config.useTabStops, autoIndent: config.autoIndent }, config.languageConfigurationService); } } return commands; } static _goodIndentForLine(config, model, lineNumber) { let action = null; let indentation = ""; const expectedIndentAction = getInheritIndentForLine(config.autoIndent, model, lineNumber, false, config.languageConfigurationService); if (expectedIndentAction) { action = expectedIndentAction.action; indentation = expectedIndentAction.indentation; } else if (lineNumber > 1) { let lastLineNumber; for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) { const lineText = model.getLineContent(lastLineNumber); const nonWhitespaceIdx = lastNonWhitespaceIndex(lineText); if (nonWhitespaceIdx >= 0) { break; } } if (lastLineNumber < 1) { return null; } const maxColumn = model.getLineMaxColumn(lastLineNumber); const expectedEnterAction = getEnterAction(config.autoIndent, model, new Range$2(lastLineNumber, maxColumn, lastLineNumber, maxColumn), config.languageConfigurationService); if (expectedEnterAction) { indentation = expectedEnterAction.indentation + expectedEnterAction.appendText; } } if (action) { if (action === IndentAction$1.Indent) { indentation = shiftIndent(config, indentation); } if (action === IndentAction$1.Outdent) { indentation = unshiftIndent(config, indentation); } indentation = config.normalizeIndentation(indentation); } if (!indentation) { return null; } return indentation; } static _replaceJumpToNextIndent(config, model, selection, insertsAutoWhitespace) { let typeText = ""; const position = selection.getStartPosition(); if (config.insertSpaces) { const visibleColumnFromColumn = config.visibleColumnFromColumn(model, position); const indentSize = config.indentSize; const spacesCnt = indentSize - visibleColumnFromColumn % indentSize; for (let i2 = 0; i2 < spacesCnt; i2++) { typeText += " "; } } else { typeText = " "; } return new ReplaceCommand(selection, typeText, insertsAutoWhitespace); } } class BaseTypeWithAutoClosingCommand extends ReplaceCommandWithOffsetCursorState { constructor(selection, text2, lineNumberDeltaOffset, columnDeltaOffset, openCharacter, closeCharacter) { super(selection, text2, lineNumberDeltaOffset, columnDeltaOffset); this._openCharacter = openCharacter; this._closeCharacter = closeCharacter; this.closeCharacterRange = null; this.enclosingRange = null; } _computeCursorStateWithRange(model, range2, helper) { this.closeCharacterRange = new Range$2(range2.startLineNumber, range2.endColumn - this._closeCharacter.length, range2.endLineNumber, range2.endColumn); this.enclosingRange = new Range$2(range2.startLineNumber, range2.endColumn - this._openCharacter.length - this._closeCharacter.length, range2.endLineNumber, range2.endColumn); return super.computeCursorState(model, helper); } } class TypeWithAutoClosingCommand extends BaseTypeWithAutoClosingCommand { constructor(selection, openCharacter, insertOpenCharacter, closeCharacter) { const text2 = (insertOpenCharacter ? openCharacter : "") + closeCharacter; const lineNumberDeltaOffset = 0; const columnDeltaOffset = -closeCharacter.length; super(selection, text2, lineNumberDeltaOffset, columnDeltaOffset, openCharacter, closeCharacter); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); const range2 = inverseEditOperations[0].range; return this._computeCursorStateWithRange(model, range2, helper); } } class TypeWithIndentationAndAutoClosingCommand extends BaseTypeWithAutoClosingCommand { constructor(autoIndentationEdit, selection, openCharacter, closeCharacter) { const text2 = openCharacter + closeCharacter; const lineNumberDeltaOffset = 0; const columnDeltaOffset = openCharacter.length; super(selection, text2, lineNumberDeltaOffset, columnDeltaOffset, openCharacter, closeCharacter); this._autoIndentationEdit = autoIndentationEdit; this._autoClosingEdit = { range: selection, text: text2 }; } getEditOperations(model, builder) { builder.addTrackedEditOperation(this._autoIndentationEdit.range, this._autoIndentationEdit.text); builder.addTrackedEditOperation(this._autoClosingEdit.range, this._autoClosingEdit.text); } computeCursorState(model, helper) { const inverseEditOperations = helper.getInverseEditOperations(); if (inverseEditOperations.length !== 2) { throw new Error("There should be two inverse edit operations!"); } const range1 = inverseEditOperations[0].range; const range2 = inverseEditOperations[1].range; const range3 = range1.plusRange(range2); return this._computeCursorStateWithRange(model, range3, helper); } } function getTypingOperation(typedText, previousTypingOperation) { if (typedText === " ") { return previousTypingOperation === 5 || previousTypingOperation === 6 ? 6 : 5; } return 4; } function shouldPushStackElementBetween(previousTypingOperation, typingOperation) { if (isTypingOperation(previousTypingOperation) && !isTypingOperation(typingOperation)) { return true; } if (previousTypingOperation === 5) { return false; } return normalizeOperationType(previousTypingOperation) !== normalizeOperationType(typingOperation); } function normalizeOperationType(type) { return type === 6 || type === 5 ? "space" : type; } function isTypingOperation(type) { return type === 4 || type === 5 || type === 6; } function isAutoClosingOvertype(config, model, selections, autoClosedCharacters, ch) { if (config.autoClosingOvertype === "never") { return false; } if (!config.autoClosingPairs.autoClosingPairsCloseSingleChar.has(ch)) { return false; } for (let i2 = 0, len = selections.length; i2 < len; i2++) { const selection = selections[i2]; if (!selection.isEmpty()) { return false; } const position = selection.getPosition(); const lineText = model.getLineContent(position.lineNumber); const afterCharacter = lineText.charAt(position.column - 1); if (afterCharacter !== ch) { return false; } const chIsQuote = isQuote(ch); const beforeCharacter = position.column > 2 ? lineText.charCodeAt(position.column - 2) : 0; if (beforeCharacter === 92 && chIsQuote) { return false; } if (config.autoClosingOvertype === "auto") { let found = false; for (let j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) { const autoClosedCharacter = autoClosedCharacters[j]; if (position.lineNumber === autoClosedCharacter.startLineNumber && position.column === autoClosedCharacter.startColumn) { found = true; break; } } if (!found) { return false; } } } return true; } function typeCommand(range2, text2, keepPosition) { if (keepPosition) { return new ReplaceCommandWithoutChangingPosition(range2, text2, true); } else { return new ReplaceCommand(range2, text2, true); } } function shiftIndent(config, indentation, count) { count = count || 1; return ShiftCommand.shiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces); } function unshiftIndent(config, indentation, count) { count = count || 1; return ShiftCommand.unshiftIndent(indentation, indentation.length + count, config.tabSize, config.indentSize, config.insertSpaces); } function shouldSurroundChar(config, ch) { if (isQuote(ch)) { return config.autoSurround === "quotes" || config.autoSurround === "languageDefined"; } else { return config.autoSurround === "brackets" || config.autoSurround === "languageDefined"; } } class TypeOperations { static indent(config, model, selections) { if (model === null || selections === null) { return []; } const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { commands[i2] = new ShiftCommand(selections[i2], { isUnshift: false, tabSize: config.tabSize, indentSize: config.indentSize, insertSpaces: config.insertSpaces, useTabStops: config.useTabStops, autoIndent: config.autoIndent }, config.languageConfigurationService); } return commands; } static outdent(config, model, selections) { const commands = []; for (let i2 = 0, len = selections.length; i2 < len; i2++) { commands[i2] = new ShiftCommand(selections[i2], { isUnshift: true, tabSize: config.tabSize, indentSize: config.indentSize, insertSpaces: config.insertSpaces, useTabStops: config.useTabStops, autoIndent: config.autoIndent }, config.languageConfigurationService); } return commands; } static paste(config, model, selections, text2, pasteOnNewLine, multicursorText) { return PasteOperation.getEdits(config, model, selections, text2, pasteOnNewLine, multicursorText); } static tab(config, model, selections) { return TabOperation.getCommands(config, model, selections); } static compositionType(prevEditOperationType, config, model, selections, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) { return CompositionOperation.getEdits(prevEditOperationType, config, model, selections, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta); } /** * This is very similar with typing, but the character is already in the text buffer! */ static compositionEndWithInterceptors(prevEditOperationType, config, model, compositions, selections, autoClosedCharacters) { if (!compositions) { return null; } let insertedText = null; for (const composition of compositions) { if (insertedText === null) { insertedText = composition.insertedText; } else if (insertedText !== composition.insertedText) { return null; } } if (!insertedText || insertedText.length !== 1) { return CompositionEndOvertypeOperation.getEdits(config, compositions); } const ch = insertedText; let hasDeletion = false; for (const composition of compositions) { if (composition.deletedText.length !== 0) { hasDeletion = true; break; } } if (hasDeletion) { if (!shouldSurroundChar(config, ch) || !config.surroundingPairs.hasOwnProperty(ch)) { return null; } const isTypingAQuoteCharacter = isQuote(ch); for (const composition of compositions) { if (composition.deletedSelectionStart !== 0 || composition.deletedSelectionEnd !== composition.deletedText.length) { return null; } if (/^[ \t]+$/.test(composition.deletedText)) { return null; } if (isTypingAQuoteCharacter && isQuote(composition.deletedText)) { return null; } } const positions = []; for (const selection of selections) { if (!selection.isEmpty()) { return null; } positions.push(selection.getPosition()); } if (positions.length !== compositions.length) { return null; } const commands = []; for (let i2 = 0, len = positions.length; i2 < len; i2++) { commands.push(new CompositionSurroundSelectionCommand(positions[i2], compositions[i2].deletedText, config.surroundingPairs[ch])); } return new EditOperationResult(4, commands, { shouldPushStackElementBefore: true, shouldPushStackElementAfter: false }); } const autoClosingOvertypeEdits = AutoClosingOvertypeWithInterceptorsOperation.getEdits(config, model, selections, autoClosedCharacters, ch); if (autoClosingOvertypeEdits !== void 0) { return autoClosingOvertypeEdits; } const autoClosingOpenCharEdits = AutoClosingOpenCharTypeOperation.getEdits(config, model, selections, ch, true, false); if (autoClosingOpenCharEdits !== void 0) { return autoClosingOpenCharEdits; } return CompositionEndOvertypeOperation.getEdits(config, compositions); } static typeWithInterceptors(isDoingComposition, prevEditOperationType, config, model, selections, autoClosedCharacters, ch) { const enterEdits = EnterOperation.getEdits(config, model, selections, ch, isDoingComposition); if (enterEdits !== void 0) { return enterEdits; } const autoIndentEdits = AutoIndentOperation.getEdits(config, model, selections, ch, isDoingComposition); if (autoIndentEdits !== void 0) { return autoIndentEdits; } const autoClosingOverTypeEdits = AutoClosingOvertypeOperation.getEdits(prevEditOperationType, config, model, selections, autoClosedCharacters, ch); if (autoClosingOverTypeEdits !== void 0) { return autoClosingOverTypeEdits; } const autoClosingOpenCharEdits = AutoClosingOpenCharTypeOperation.getEdits(config, model, selections, ch, false, isDoingComposition); if (autoClosingOpenCharEdits !== void 0) { return autoClosingOpenCharEdits; } const surroundSelectionEdits = SurroundSelectionOperation.getEdits(config, model, selections, ch, isDoingComposition); if (surroundSelectionEdits !== void 0) { return surroundSelectionEdits; } const interceptorElectricCharOperation = InterceptorElectricCharOperation.getEdits(prevEditOperationType, config, model, selections, ch, isDoingComposition); if (interceptorElectricCharOperation !== void 0) { return interceptorElectricCharOperation; } return SimpleCharacterTypeOperation.getEdits(config, prevEditOperationType, selections, ch, isDoingComposition); } static typeWithoutInterceptors(prevEditOperationType, config, model, selections, str) { return TypeWithoutInterceptorsOperation.getEdits(prevEditOperationType, selections, str); } } class CompositionOutcome { constructor(deletedText, deletedSelectionStart, deletedSelectionEnd, insertedText, insertedSelectionStart, insertedSelectionEnd, insertedTextRange) { this.deletedText = deletedText; this.deletedSelectionStart = deletedSelectionStart; this.deletedSelectionEnd = deletedSelectionEnd; this.insertedText = insertedText; this.insertedSelectionStart = insertedSelectionStart; this.insertedSelectionEnd = insertedSelectionEnd; this.insertedTextRange = insertedTextRange; } } var EditorContextKeys; (function(EditorContextKeys2) { EditorContextKeys2.editorSimpleInput = new RawContextKey("editorSimpleInput", false, true); EditorContextKeys2.editorTextFocus = new RawContextKey("editorTextFocus", false, localize(678, "Whether the editor text has focus (cursor is blinking)")); EditorContextKeys2.focus = new RawContextKey("editorFocus", false, localize(679, "Whether the editor or an editor widget has focus (e.g. focus is in the find widget)")); EditorContextKeys2.textInputFocus = new RawContextKey("textInputFocus", false, localize(680, "Whether an editor or a rich text input has focus (cursor is blinking)")); EditorContextKeys2.readOnly = new RawContextKey("editorReadonly", false, localize(681, "Whether the editor is read-only")); EditorContextKeys2.inDiffEditor = new RawContextKey("inDiffEditor", false, localize(682, "Whether the context is a diff editor")); EditorContextKeys2.isEmbeddedDiffEditor = new RawContextKey("isEmbeddedDiffEditor", false, localize(683, "Whether the context is an embedded diff editor")); EditorContextKeys2.multiDiffEditorAllCollapsed = new RawContextKey("multiDiffEditorAllCollapsed", void 0, localize(684, "Whether all files in multi diff editor are collapsed")); EditorContextKeys2.hasChanges = new RawContextKey("diffEditorHasChanges", false, localize(685, "Whether the diff editor has changes")); EditorContextKeys2.comparingMovedCode = new RawContextKey("comparingMovedCode", false, localize(686, "Whether a moved code block is selected for comparison")); EditorContextKeys2.accessibleDiffViewerVisible = new RawContextKey("accessibleDiffViewerVisible", false, localize(687, "Whether the accessible diff viewer is visible")); EditorContextKeys2.diffEditorRenderSideBySideInlineBreakpointReached = new RawContextKey("diffEditorRenderSideBySideInlineBreakpointReached", false, localize(688, "Whether the diff editor render side by side inline breakpoint is reached")); EditorContextKeys2.diffEditorInlineMode = new RawContextKey("diffEditorInlineMode", false, localize(689, "Whether inline mode is active")); EditorContextKeys2.diffEditorOriginalWritable = new RawContextKey("diffEditorOriginalWritable", false, localize(690, "Whether modified is writable in the diff editor")); EditorContextKeys2.diffEditorModifiedWritable = new RawContextKey("diffEditorModifiedWritable", false, localize(691, "Whether modified is writable in the diff editor")); EditorContextKeys2.diffEditorOriginalUri = new RawContextKey("diffEditorOriginalUri", "", localize(692, "The uri of the original document")); EditorContextKeys2.diffEditorModifiedUri = new RawContextKey("diffEditorModifiedUri", "", localize(693, "The uri of the modified document")); EditorContextKeys2.columnSelection = new RawContextKey("editorColumnSelection", false, localize(694, "Whether `editor.columnSelection` is enabled")); EditorContextKeys2.writable = EditorContextKeys2.readOnly.toNegated(); EditorContextKeys2.hasNonEmptySelection = new RawContextKey("editorHasSelection", false, localize(695, "Whether the editor has text selected")); EditorContextKeys2.hasOnlyEmptySelection = EditorContextKeys2.hasNonEmptySelection.toNegated(); EditorContextKeys2.hasMultipleSelections = new RawContextKey("editorHasMultipleSelections", false, localize(696, "Whether the editor has multiple selections")); EditorContextKeys2.hasSingleSelection = EditorContextKeys2.hasMultipleSelections.toNegated(); EditorContextKeys2.tabMovesFocus = new RawContextKey("editorTabMovesFocus", false, localize(697, "Whether `Tab` will move focus out of the editor")); EditorContextKeys2.tabDoesNotMoveFocus = EditorContextKeys2.tabMovesFocus.toNegated(); EditorContextKeys2.isInEmbeddedEditor = new RawContextKey("isInEmbeddedEditor", false, true); EditorContextKeys2.canUndo = new RawContextKey("canUndo", false, true); EditorContextKeys2.canRedo = new RawContextKey("canRedo", false, true); EditorContextKeys2.hoverVisible = new RawContextKey("editorHoverVisible", false, localize(698, "Whether the editor hover is visible")); EditorContextKeys2.hoverFocused = new RawContextKey("editorHoverFocused", false, localize(699, "Whether the editor hover is focused")); EditorContextKeys2.stickyScrollFocused = new RawContextKey("stickyScrollFocused", false, localize(700, "Whether the sticky scroll is focused")); EditorContextKeys2.stickyScrollVisible = new RawContextKey("stickyScrollVisible", false, localize(701, "Whether the sticky scroll is visible")); EditorContextKeys2.standaloneColorPickerVisible = new RawContextKey("standaloneColorPickerVisible", false, localize(702, "Whether the standalone color picker is visible")); EditorContextKeys2.standaloneColorPickerFocused = new RawContextKey("standaloneColorPickerFocused", false, localize(703, "Whether the standalone color picker is focused")); EditorContextKeys2.inCompositeEditor = new RawContextKey("inCompositeEditor", void 0, localize(704, "Whether the editor is part of a larger editor (e.g. notebooks)")); EditorContextKeys2.notInCompositeEditor = EditorContextKeys2.inCompositeEditor.toNegated(); EditorContextKeys2.languageId = new RawContextKey("editorLangId", "", localize(705, "The language identifier of the editor")); EditorContextKeys2.hasCompletionItemProvider = new RawContextKey("editorHasCompletionItemProvider", false, localize(706, "Whether the editor has a completion item provider")); EditorContextKeys2.hasCodeActionsProvider = new RawContextKey("editorHasCodeActionsProvider", false, localize(707, "Whether the editor has a code actions provider")); EditorContextKeys2.hasCodeLensProvider = new RawContextKey("editorHasCodeLensProvider", false, localize(708, "Whether the editor has a code lens provider")); EditorContextKeys2.hasDefinitionProvider = new RawContextKey("editorHasDefinitionProvider", false, localize(709, "Whether the editor has a definition provider")); EditorContextKeys2.hasDeclarationProvider = new RawContextKey("editorHasDeclarationProvider", false, localize(710, "Whether the editor has a declaration provider")); EditorContextKeys2.hasImplementationProvider = new RawContextKey("editorHasImplementationProvider", false, localize(711, "Whether the editor has an implementation provider")); EditorContextKeys2.hasTypeDefinitionProvider = new RawContextKey("editorHasTypeDefinitionProvider", false, localize(712, "Whether the editor has a type definition provider")); EditorContextKeys2.hasHoverProvider = new RawContextKey("editorHasHoverProvider", false, localize(713, "Whether the editor has a hover provider")); EditorContextKeys2.hasDocumentHighlightProvider = new RawContextKey("editorHasDocumentHighlightProvider", false, localize(714, "Whether the editor has a document highlight provider")); EditorContextKeys2.hasDocumentSymbolProvider = new RawContextKey("editorHasDocumentSymbolProvider", false, localize(715, "Whether the editor has a document symbol provider")); EditorContextKeys2.hasReferenceProvider = new RawContextKey("editorHasReferenceProvider", false, localize(716, "Whether the editor has a reference provider")); EditorContextKeys2.hasRenameProvider = new RawContextKey("editorHasRenameProvider", false, localize(717, "Whether the editor has a rename provider")); EditorContextKeys2.hasSignatureHelpProvider = new RawContextKey("editorHasSignatureHelpProvider", false, localize(718, "Whether the editor has a signature help provider")); EditorContextKeys2.hasInlayHintsProvider = new RawContextKey("editorHasInlayHintsProvider", false, localize(719, "Whether the editor has an inline hints provider")); EditorContextKeys2.hasDocumentFormattingProvider = new RawContextKey("editorHasDocumentFormattingProvider", false, localize(720, "Whether the editor has a document formatting provider")); EditorContextKeys2.hasDocumentSelectionFormattingProvider = new RawContextKey("editorHasDocumentSelectionFormattingProvider", false, localize(721, "Whether the editor has a document selection formatting provider")); EditorContextKeys2.hasMultipleDocumentFormattingProvider = new RawContextKey("editorHasMultipleDocumentFormattingProvider", false, localize(722, "Whether the editor has multiple document formatting providers")); EditorContextKeys2.hasMultipleDocumentSelectionFormattingProvider = new RawContextKey("editorHasMultipleDocumentSelectionFormattingProvider", false, localize(723, "Whether the editor has multiple document selection formatting providers")); })(EditorContextKeys || (EditorContextKeys = {})); const CORE_WEIGHT = 0; class CoreEditorCommand extends EditorCommand { runEditorCommand(accessor, editor2, args) { const viewModel = editor2._getViewModel(); if (!viewModel) { return; } this.runCoreEditorCommand(viewModel, args || {}); } } var EditorScroll_; (function(EditorScroll_2) { const isEditorScrollArgs = function(arg) { if (!isObject(arg)) { return false; } const scrollArg = arg; if (!isString$1(scrollArg.to)) { return false; } if (!isUndefined(scrollArg.by) && !isString$1(scrollArg.by)) { return false; } if (!isUndefined(scrollArg.value) && !isNumber$1(scrollArg.value)) { return false; } if (!isUndefined(scrollArg.revealCursor) && !isBoolean(scrollArg.revealCursor)) { return false; } return true; }; EditorScroll_2.metadata = { description: "Scroll editor in the given direction", args: [ { name: "Editor scroll argument object", description: `Property-value pairs that can be passed through this argument: * 'to': A mandatory direction value. \`\`\` 'up', 'down' \`\`\` * 'by': Unit to move. Default is computed based on 'to' value. \`\`\` 'line', 'wrappedLine', 'page', 'halfPage', 'editor' \`\`\` * 'value': Number of units to move. Default is '1'. * 'revealCursor': If 'true' reveals the cursor if it is outside view port. `, constraint: isEditorScrollArgs, schema: { "type": "object", "required": ["to"], "properties": { "to": { "type": "string", "enum": ["up", "down"] }, "by": { "type": "string", "enum": ["line", "wrappedLine", "page", "halfPage", "editor"] }, "value": { "type": "number", "default": 1 }, "revealCursor": { "type": "boolean" } } } } ] }; EditorScroll_2.RawDirection = { Up: "up", Right: "right", Down: "down", Left: "left" }; EditorScroll_2.RawUnit = { Line: "line", WrappedLine: "wrappedLine", Page: "page", HalfPage: "halfPage", Editor: "editor", Column: "column" }; function parse2(args) { let direction; switch (args.to) { case EditorScroll_2.RawDirection.Up: direction = 1; break; case EditorScroll_2.RawDirection.Right: direction = 2; break; case EditorScroll_2.RawDirection.Down: direction = 3; break; case EditorScroll_2.RawDirection.Left: direction = 4; break; default: return null; } let unit; switch (args.by) { case EditorScroll_2.RawUnit.Line: unit = 1; break; case EditorScroll_2.RawUnit.WrappedLine: unit = 2; break; case EditorScroll_2.RawUnit.Page: unit = 3; break; case EditorScroll_2.RawUnit.HalfPage: unit = 4; break; case EditorScroll_2.RawUnit.Editor: unit = 5; break; case EditorScroll_2.RawUnit.Column: unit = 6; break; default: unit = 2; } const value = Math.floor(args.value || 1); const revealCursor = !!args.revealCursor; return { direction, unit, value, revealCursor, select: !!args.select }; } EditorScroll_2.parse = parse2; })(EditorScroll_ || (EditorScroll_ = {})); var RevealLine_; (function(RevealLine_2) { const isRevealLineArgs = function(arg) { if (!isObject(arg)) { return false; } const reveaLineArg = arg; if (!isNumber$1(reveaLineArg.lineNumber) && !isString$1(reveaLineArg.lineNumber)) { return false; } if (!isUndefined(reveaLineArg.at) && !isString$1(reveaLineArg.at)) { return false; } return true; }; RevealLine_2.metadata = { description: "Reveal the given line at the given logical position", args: [ { name: "Reveal line argument object", description: `Property-value pairs that can be passed through this argument: * 'lineNumber': A mandatory line number value. * 'at': Logical position at which line has to be revealed. \`\`\` 'top', 'center', 'bottom' \`\`\` `, constraint: isRevealLineArgs, schema: { "type": "object", "required": ["lineNumber"], "properties": { "lineNumber": { "type": ["number", "string"] }, "at": { "type": "string", "enum": ["top", "center", "bottom"] } } } } ] }; RevealLine_2.RawAtArgument = { Top: "top", Center: "center", Bottom: "bottom" }; })(RevealLine_ || (RevealLine_ = {})); class EditorOrNativeTextInputCommand { constructor(target) { target.addImplementation(1e4, "code-editor", (accessor, args) => { const focusedEditor = accessor.get(ICodeEditorService).getFocusedCodeEditor(); if (focusedEditor && focusedEditor.hasTextFocus()) { return this._runEditorCommand(accessor, focusedEditor, args); } return false; }); target.addImplementation(1e3, "generic-dom-input-textarea", (accessor, args) => { const activeElement = getActiveElement(); if (activeElement && isEditableElement(activeElement)) { this.runDOMCommand(activeElement); return true; } return false; }); target.addImplementation(0, "generic-dom", (accessor, args) => { const activeEditor = accessor.get(ICodeEditorService).getActiveCodeEditor(); if (activeEditor) { activeEditor.focus(); return this._runEditorCommand(accessor, activeEditor, args); } return false; }); } _runEditorCommand(accessor, editor2, args) { const result = this.runEditorCommand(accessor, editor2, args); if (result) { return result; } return true; } } var CoreNavigationCommands; (function(CoreNavigationCommands2) { class BaseMoveToCommand extends CoreEditorCommand { constructor(opts) { super(opts); this._inSelectionMode = opts.inSelectionMode; } runCoreEditorCommand(viewModel, args) { if (!args.position) { return; } viewModel.model.pushStackElement(); const cursorStateChanged = viewModel.setCursorStates(args.source, 3, [ CursorMoveCommands.moveTo(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position, args.viewPosition) ]); if (cursorStateChanged && args.revealType !== 2) { viewModel.revealAllCursors(args.source, true, true); } } } CoreNavigationCommands2.MoveTo = registerEditorCommand(new BaseMoveToCommand({ id: "_moveTo", inSelectionMode: false, precondition: void 0 })); CoreNavigationCommands2.MoveToSelect = registerEditorCommand(new BaseMoveToCommand({ id: "_moveToSelect", inSelectionMode: true, precondition: void 0 })); class ColumnSelectCommand extends CoreEditorCommand { runCoreEditorCommand(viewModel, args) { viewModel.model.pushStackElement(); const result = this._getColumnSelectResult(viewModel, viewModel.getPrimaryCursorState(), viewModel.getCursorColumnSelectData(), args); if (result === null) { return; } viewModel.setCursorStates(args.source, 3, result.viewStates.map((viewState) => CursorState$1.fromViewState(viewState))); viewModel.setCursorColumnSelectData({ isReal: true, fromViewLineNumber: result.fromLineNumber, fromViewVisualColumn: result.fromVisualColumn, toViewLineNumber: result.toLineNumber, toViewVisualColumn: result.toVisualColumn }); if (result.reversed) { viewModel.revealTopMostCursor(args.source); } else { viewModel.revealBottomMostCursor(args.source); } } } CoreNavigationCommands2.ColumnSelect = registerEditorCommand(new class extends ColumnSelectCommand { constructor() { super({ id: "columnSelect", precondition: void 0 }); } _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) { if (typeof args.position === "undefined" || typeof args.viewPosition === "undefined" || typeof args.mouseColumn === "undefined") { return null; } const validatedPosition = viewModel.model.validatePosition(args.position); const validatedViewPosition = viewModel.coordinatesConverter.validateViewPosition(new Position$1(args.viewPosition.lineNumber, args.viewPosition.column), validatedPosition); const fromViewLineNumber = args.doColumnSelect ? prevColumnSelectData.fromViewLineNumber : validatedViewPosition.lineNumber; const fromViewVisualColumn = args.doColumnSelect ? prevColumnSelectData.fromViewVisualColumn : args.mouseColumn - 1; return ColumnSelection.columnSelect(viewModel.cursorConfig, viewModel, fromViewLineNumber, fromViewVisualColumn, validatedViewPosition.lineNumber, args.mouseColumn - 1); } }()); CoreNavigationCommands2.CursorColumnSelectLeft = registerEditorCommand(new class extends ColumnSelectCommand { constructor() { super({ id: "cursorColumnSelectLeft", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 1024 | 512 | 15, linux: { primary: 0 } } }); } _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) { return ColumnSelection.columnSelectLeft(viewModel.cursorConfig, viewModel, prevColumnSelectData); } }()); CoreNavigationCommands2.CursorColumnSelectRight = registerEditorCommand(new class extends ColumnSelectCommand { constructor() { super({ id: "cursorColumnSelectRight", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 1024 | 512 | 17, linux: { primary: 0 } } }); } _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) { return ColumnSelection.columnSelectRight(viewModel.cursorConfig, viewModel, prevColumnSelectData); } }()); class ColumnSelectUpCommand extends ColumnSelectCommand { constructor(opts) { super(opts); this._isPaged = opts.isPaged; } _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) { return ColumnSelection.columnSelectUp(viewModel.cursorConfig, viewModel, prevColumnSelectData, this._isPaged); } } CoreNavigationCommands2.CursorColumnSelectUp = registerEditorCommand(new ColumnSelectUpCommand({ isPaged: false, id: "cursorColumnSelectUp", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 1024 | 512 | 16, linux: { primary: 0 } } })); CoreNavigationCommands2.CursorColumnSelectPageUp = registerEditorCommand(new ColumnSelectUpCommand({ isPaged: true, id: "cursorColumnSelectPageUp", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 1024 | 512 | 11, linux: { primary: 0 } } })); class ColumnSelectDownCommand extends ColumnSelectCommand { constructor(opts) { super(opts); this._isPaged = opts.isPaged; } _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) { return ColumnSelection.columnSelectDown(viewModel.cursorConfig, viewModel, prevColumnSelectData, this._isPaged); } } CoreNavigationCommands2.CursorColumnSelectDown = registerEditorCommand(new ColumnSelectDownCommand({ isPaged: false, id: "cursorColumnSelectDown", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 1024 | 512 | 18, linux: { primary: 0 } } })); CoreNavigationCommands2.CursorColumnSelectPageDown = registerEditorCommand(new ColumnSelectDownCommand({ isPaged: true, id: "cursorColumnSelectPageDown", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 1024 | 512 | 12, linux: { primary: 0 } } })); class CursorMoveImpl extends CoreEditorCommand { constructor() { super({ id: "cursorMove", precondition: void 0, metadata: CursorMove.metadata }); } runCoreEditorCommand(viewModel, args) { const parsed = CursorMove.parse(args); if (!parsed) { return; } this._runCursorMove(viewModel, args.source, parsed); } _runCursorMove(viewModel, source, args) { viewModel.model.pushStackElement(); viewModel.setCursorStates(source, 3, CursorMoveImpl._move(viewModel, viewModel.getCursorStates(), args)); viewModel.revealAllCursors(source, true); } static _move(viewModel, cursors, args) { const inSelectionMode = args.select; const value = args.value; switch (args.direction) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: return CursorMoveCommands.simpleMove(viewModel, cursors, args.direction, inSelectionMode, value, args.unit); case 11: case 13: case 12: case 14: return CursorMoveCommands.viewportMove(viewModel, cursors, args.direction, inSelectionMode, value); default: return null; } } } CoreNavigationCommands2.CursorMoveImpl = CursorMoveImpl; CoreNavigationCommands2.CursorMove = registerEditorCommand(new CursorMoveImpl()); class CursorMoveBasedCommand extends CoreEditorCommand { constructor(opts) { super(opts); this._staticArgs = opts.args; } runCoreEditorCommand(viewModel, dynamicArgs) { let args = this._staticArgs; if (this._staticArgs.value === -1) { args = { direction: this._staticArgs.direction, unit: this._staticArgs.unit, select: this._staticArgs.select, value: dynamicArgs.pageSize || viewModel.cursorConfig.pageSize }; } viewModel.model.pushStackElement(); viewModel.setCursorStates(dynamicArgs.source, 3, CursorMoveCommands.simpleMove(viewModel, viewModel.getCursorStates(), args.direction, args.select, args.value, args.unit)); viewModel.revealAllCursors(dynamicArgs.source, true); } } CoreNavigationCommands2.CursorLeft = registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 0, unit: 0, select: false, value: 1 }, id: "cursorLeft", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 15, mac: { primary: 15, secondary: [ 256 | 32 /* KeyCode.KeyB */ ] } } })); CoreNavigationCommands2.CursorLeftSelect = registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 0, unit: 0, select: true, value: 1 }, id: "cursorLeftSelect", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 1024 | 15 /* KeyCode.LeftArrow */ } })); CoreNavigationCommands2.CursorRight = registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 1, unit: 0, select: false, value: 1 }, id: "cursorRight", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 17, mac: { primary: 17, secondary: [ 256 | 36 /* KeyCode.KeyF */ ] } } })); CoreNavigationCommands2.CursorRightSelect = registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 1, unit: 0, select: true, value: 1 }, id: "cursorRightSelect", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 1024 | 17 /* KeyCode.RightArrow */ } })); CoreNavigationCommands2.CursorUp = registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 2, unit: 2, select: false, value: 1 }, id: "cursorUp", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 16, mac: { primary: 16, secondary: [ 256 | 46 /* KeyCode.KeyP */ ] } } })); CoreNavigationCommands2.CursorUpSelect = registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 2, unit: 2, select: true, value: 1 }, id: "cursorUpSelect", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 1024 | 16, secondary: [ 2048 | 1024 | 16 /* KeyCode.UpArrow */ ], mac: { primary: 1024 | 16 /* KeyCode.UpArrow */ }, linux: { primary: 1024 | 16 /* KeyCode.UpArrow */ } } })); CoreNavigationCommands2.CursorPageUp = registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 2, unit: 2, select: false, value: -1 /* Constants.PAGE_SIZE_MARKER */ }, id: "cursorPageUp", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 11 /* KeyCode.PageUp */ } })); CoreNavigationCommands2.CursorPageUpSelect = registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 2, unit: 2, select: true, value: -1 /* Constants.PAGE_SIZE_MARKER */ }, id: "cursorPageUpSelect", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 1024 | 11 /* KeyCode.PageUp */ } })); CoreNavigationCommands2.CursorDown = registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 3, unit: 2, select: false, value: 1 }, id: "cursorDown", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 18, mac: { primary: 18, secondary: [ 256 | 44 /* KeyCode.KeyN */ ] } } })); CoreNavigationCommands2.CursorDownSelect = registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 3, unit: 2, select: true, value: 1 }, id: "cursorDownSelect", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 1024 | 18, secondary: [ 2048 | 1024 | 18 /* KeyCode.DownArrow */ ], mac: { primary: 1024 | 18 /* KeyCode.DownArrow */ }, linux: { primary: 1024 | 18 /* KeyCode.DownArrow */ } } })); CoreNavigationCommands2.CursorPageDown = registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 3, unit: 2, select: false, value: -1 /* Constants.PAGE_SIZE_MARKER */ }, id: "cursorPageDown", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 12 /* KeyCode.PageDown */ } })); CoreNavigationCommands2.CursorPageDownSelect = registerEditorCommand(new CursorMoveBasedCommand({ args: { direction: 3, unit: 2, select: true, value: -1 /* Constants.PAGE_SIZE_MARKER */ }, id: "cursorPageDownSelect", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 1024 | 12 /* KeyCode.PageDown */ } })); CoreNavigationCommands2.CreateCursor = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "createCursor", precondition: void 0 }); } runCoreEditorCommand(viewModel, args) { if (!args.position) { return; } let newState; if (args.wholeLine) { newState = CursorMoveCommands.line(viewModel, viewModel.getPrimaryCursorState(), false, args.position, args.viewPosition); } else { newState = CursorMoveCommands.moveTo(viewModel, viewModel.getPrimaryCursorState(), false, args.position, args.viewPosition); } const states = viewModel.getCursorStates(); if (states.length > 1) { const newModelPosition = newState.modelState ? newState.modelState.position : null; const newViewPosition = newState.viewState ? newState.viewState.position : null; for (let i2 = 0, len = states.length; i2 < len; i2++) { const state = states[i2]; if (newModelPosition && !state.modelState.selection.containsPosition(newModelPosition)) { continue; } if (newViewPosition && !state.viewState.selection.containsPosition(newViewPosition)) { continue; } states.splice(i2, 1); viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, states); return; } } states.push(newState); viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, states); } }()); CoreNavigationCommands2.LastCursorMoveToSelect = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "_lastCursorMoveToSelect", precondition: void 0 }); } runCoreEditorCommand(viewModel, args) { if (!args.position) { return; } const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex(); const states = viewModel.getCursorStates(); const newStates = states.slice(0); newStates[lastAddedCursorIndex] = CursorMoveCommands.moveTo(viewModel, states[lastAddedCursorIndex], true, args.position, args.viewPosition); viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, newStates); } }()); class HomeCommand extends CoreEditorCommand { constructor(opts) { super(opts); this._inSelectionMode = opts.inSelectionMode; } runCoreEditorCommand(viewModel, args) { viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, CursorMoveCommands.moveToBeginningOfLine(viewModel, viewModel.getCursorStates(), this._inSelectionMode)); viewModel.revealAllCursors(args.source, true); } } CoreNavigationCommands2.CursorHome = registerEditorCommand(new HomeCommand({ inSelectionMode: false, id: "cursorHome", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 14, mac: { primary: 14, secondary: [ 2048 | 15 /* KeyCode.LeftArrow */ ] } } })); CoreNavigationCommands2.CursorHomeSelect = registerEditorCommand(new HomeCommand({ inSelectionMode: true, id: "cursorHomeSelect", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 1024 | 14, mac: { primary: 1024 | 14, secondary: [ 2048 | 1024 | 15 /* KeyCode.LeftArrow */ ] } } })); class LineStartCommand extends CoreEditorCommand { constructor(opts) { super(opts); this._inSelectionMode = opts.inSelectionMode; } runCoreEditorCommand(viewModel, args) { viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, this._exec(viewModel.getCursorStates())); viewModel.revealAllCursors(args.source, true); } _exec(cursors) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; const lineNumber = cursor.modelState.position.lineNumber; result[i2] = CursorState$1.fromModelState(cursor.modelState.move(this._inSelectionMode, lineNumber, 1, 0)); } return result; } } CoreNavigationCommands2.CursorLineStart = registerEditorCommand(new LineStartCommand({ inSelectionMode: false, id: "cursorLineStart", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 | 31 /* KeyCode.KeyA */ } } })); CoreNavigationCommands2.CursorLineStartSelect = registerEditorCommand(new LineStartCommand({ inSelectionMode: true, id: "cursorLineStartSelect", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 | 1024 | 31 /* KeyCode.KeyA */ } } })); class EndCommand extends CoreEditorCommand { constructor(opts) { super(opts); this._inSelectionMode = opts.inSelectionMode; } runCoreEditorCommand(viewModel, args) { viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, CursorMoveCommands.moveToEndOfLine(viewModel, viewModel.getCursorStates(), this._inSelectionMode, args.sticky || false)); viewModel.revealAllCursors(args.source, true); } } CoreNavigationCommands2.CursorEnd = registerEditorCommand(new EndCommand({ inSelectionMode: false, id: "cursorEnd", precondition: void 0, kbOpts: { args: { sticky: false }, weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 13, mac: { primary: 13, secondary: [ 2048 | 17 /* KeyCode.RightArrow */ ] } }, metadata: { description: `Go to End`, args: [{ name: "args", schema: { type: "object", properties: { "sticky": { description: localize(61, "Stick to the end even when going to longer lines"), type: "boolean", default: false } } } }] } })); CoreNavigationCommands2.CursorEndSelect = registerEditorCommand(new EndCommand({ inSelectionMode: true, id: "cursorEndSelect", precondition: void 0, kbOpts: { args: { sticky: false }, weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 1024 | 13, mac: { primary: 1024 | 13, secondary: [ 2048 | 1024 | 17 /* KeyCode.RightArrow */ ] } }, metadata: { description: `Select to End`, args: [{ name: "args", schema: { type: "object", properties: { "sticky": { description: localize(62, "Stick to the end even when going to longer lines"), type: "boolean", default: false } } } }] } })); class LineEndCommand extends CoreEditorCommand { constructor(opts) { super(opts); this._inSelectionMode = opts.inSelectionMode; } runCoreEditorCommand(viewModel, args) { viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, this._exec(viewModel, viewModel.getCursorStates())); viewModel.revealAllCursors(args.source, true); } _exec(viewModel, cursors) { const result = []; for (let i2 = 0, len = cursors.length; i2 < len; i2++) { const cursor = cursors[i2]; const lineNumber = cursor.modelState.position.lineNumber; const maxColumn = viewModel.model.getLineMaxColumn(lineNumber); result[i2] = CursorState$1.fromModelState(cursor.modelState.move(this._inSelectionMode, lineNumber, maxColumn, 0)); } return result; } } CoreNavigationCommands2.CursorLineEnd = registerEditorCommand(new LineEndCommand({ inSelectionMode: false, id: "cursorLineEnd", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 | 35 /* KeyCode.KeyE */ } } })); CoreNavigationCommands2.CursorLineEndSelect = registerEditorCommand(new LineEndCommand({ inSelectionMode: true, id: "cursorLineEndSelect", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 | 1024 | 35 /* KeyCode.KeyE */ } } })); class TopCommand extends CoreEditorCommand { constructor(opts) { super(opts); this._inSelectionMode = opts.inSelectionMode; } runCoreEditorCommand(viewModel, args) { viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, CursorMoveCommands.moveToBeginningOfBuffer(viewModel, viewModel.getCursorStates(), this._inSelectionMode)); viewModel.revealAllCursors(args.source, true); } } CoreNavigationCommands2.CursorTop = registerEditorCommand(new TopCommand({ inSelectionMode: false, id: "cursorTop", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 14, mac: { primary: 2048 | 16 /* KeyCode.UpArrow */ } } })); CoreNavigationCommands2.CursorTopSelect = registerEditorCommand(new TopCommand({ inSelectionMode: true, id: "cursorTopSelect", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 1024 | 14, mac: { primary: 2048 | 1024 | 16 /* KeyCode.UpArrow */ } } })); class BottomCommand extends CoreEditorCommand { constructor(opts) { super(opts); this._inSelectionMode = opts.inSelectionMode; } runCoreEditorCommand(viewModel, args) { viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, CursorMoveCommands.moveToEndOfBuffer(viewModel, viewModel.getCursorStates(), this._inSelectionMode)); viewModel.revealAllCursors(args.source, true); } } CoreNavigationCommands2.CursorBottom = registerEditorCommand(new BottomCommand({ inSelectionMode: false, id: "cursorBottom", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 13, mac: { primary: 2048 | 18 /* KeyCode.DownArrow */ } } })); CoreNavigationCommands2.CursorBottomSelect = registerEditorCommand(new BottomCommand({ inSelectionMode: true, id: "cursorBottomSelect", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 1024 | 13, mac: { primary: 2048 | 1024 | 18 /* KeyCode.DownArrow */ } } })); class EditorScrollImpl extends CoreEditorCommand { constructor() { super({ id: "editorScroll", precondition: void 0, metadata: EditorScroll_.metadata }); } determineScrollMethod(args) { const horizontalUnits = [ 6 /* EditorScroll_.Unit.Column */ ]; const verticalUnits = [ 1, 2, 3, 4, 5, 6 /* EditorScroll_.Unit.Column */ ]; const horizontalDirections = [ 4, 2 /* EditorScroll_.Direction.Right */ ]; const verticalDirections = [ 1, 3 /* EditorScroll_.Direction.Down */ ]; if (horizontalUnits.includes(args.unit) && horizontalDirections.includes(args.direction)) { return this._runHorizontalEditorScroll.bind(this); } if (verticalUnits.includes(args.unit) && verticalDirections.includes(args.direction)) { return this._runVerticalEditorScroll.bind(this); } return null; } runCoreEditorCommand(viewModel, args) { const parsed = EditorScroll_.parse(args); if (!parsed) { return; } const runEditorScroll = this.determineScrollMethod(parsed); if (!runEditorScroll) { return; } runEditorScroll(viewModel, args.source, parsed); } _runVerticalEditorScroll(viewModel, source, args) { const desiredScrollTop = this._computeDesiredScrollTop(viewModel, args); if (args.revealCursor) { const desiredVisibleViewRange = viewModel.getCompletelyVisibleViewRangeAtScrollTop(desiredScrollTop); viewModel.setCursorStates(source, 3, [ CursorMoveCommands.findPositionInViewportIfOutside(viewModel, viewModel.getPrimaryCursorState(), desiredVisibleViewRange, args.select) ]); } viewModel.viewLayout.setScrollPosition( { scrollTop: desiredScrollTop }, 0 /* ScrollType.Smooth */ ); } _computeDesiredScrollTop(viewModel, args) { if (args.unit === 1) { const futureViewport = viewModel.viewLayout.getFutureViewport(); const visibleViewRange = viewModel.getCompletelyVisibleViewRangeAtScrollTop(futureViewport.top); const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange); let desiredTopModelLineNumber; if (args.direction === 1) { desiredTopModelLineNumber = Math.max(1, visibleModelRange.startLineNumber - args.value); } else { desiredTopModelLineNumber = Math.min(viewModel.model.getLineCount(), visibleModelRange.startLineNumber + args.value); } const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(new Position$1(desiredTopModelLineNumber, 1)); return viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber); } if (args.unit === 5) { let desiredTopModelLineNumber = 0; if (args.direction === 3) { desiredTopModelLineNumber = viewModel.model.getLineCount() - viewModel.cursorConfig.pageSize; } return viewModel.viewLayout.getVerticalOffsetForLineNumber(desiredTopModelLineNumber); } let noOfLines; if (args.unit === 3) { noOfLines = viewModel.cursorConfig.pageSize * args.value; } else if (args.unit === 4) { noOfLines = Math.round(viewModel.cursorConfig.pageSize / 2) * args.value; } else { noOfLines = args.value; } const deltaLines = (args.direction === 1 ? -1 : 1) * noOfLines; return viewModel.viewLayout.getCurrentScrollTop() + deltaLines * viewModel.cursorConfig.lineHeight; } _runHorizontalEditorScroll(viewModel, source, args) { const desiredScrollLeft = this._computeDesiredScrollLeft(viewModel, args); viewModel.viewLayout.setScrollPosition( { scrollLeft: desiredScrollLeft }, 0 /* ScrollType.Smooth */ ); } _computeDesiredScrollLeft(viewModel, args) { const deltaColumns = (args.direction === 4 ? -1 : 1) * args.value; return viewModel.viewLayout.getCurrentScrollLeft() + deltaColumns * viewModel.cursorConfig.typicalHalfwidthCharacterWidth; } } CoreNavigationCommands2.EditorScrollImpl = EditorScrollImpl; CoreNavigationCommands2.EditorScroll = registerEditorCommand(new EditorScrollImpl()); CoreNavigationCommands2.ScrollLineUp = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "scrollLineUp", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 16, mac: { primary: 256 | 11 /* KeyCode.PageUp */ } } }); } runCoreEditorCommand(viewModel, args) { CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, { to: EditorScroll_.RawDirection.Up, by: EditorScroll_.RawUnit.WrappedLine, value: 1, revealCursor: false, select: false, source: args.source }); } }()); CoreNavigationCommands2.ScrollPageUp = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "scrollPageUp", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 11, win: { primary: 512 | 11 /* KeyCode.PageUp */ }, linux: { primary: 512 | 11 /* KeyCode.PageUp */ } } }); } runCoreEditorCommand(viewModel, args) { CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, { to: EditorScroll_.RawDirection.Up, by: EditorScroll_.RawUnit.Page, value: 1, revealCursor: false, select: false, source: args.source }); } }()); CoreNavigationCommands2.ScrollEditorTop = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "scrollEditorTop", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus } }); } runCoreEditorCommand(viewModel, args) { CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, { to: EditorScroll_.RawDirection.Up, by: EditorScroll_.RawUnit.Editor, value: 1, revealCursor: false, select: false, source: args.source }); } }()); CoreNavigationCommands2.ScrollLineDown = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "scrollLineDown", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 18, mac: { primary: 256 | 12 /* KeyCode.PageDown */ } } }); } runCoreEditorCommand(viewModel, args) { CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, { to: EditorScroll_.RawDirection.Down, by: EditorScroll_.RawUnit.WrappedLine, value: 1, revealCursor: false, select: false, source: args.source }); } }()); CoreNavigationCommands2.ScrollPageDown = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "scrollPageDown", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 2048 | 12, win: { primary: 512 | 12 /* KeyCode.PageDown */ }, linux: { primary: 512 | 12 /* KeyCode.PageDown */ } } }); } runCoreEditorCommand(viewModel, args) { CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, { to: EditorScroll_.RawDirection.Down, by: EditorScroll_.RawUnit.Page, value: 1, revealCursor: false, select: false, source: args.source }); } }()); CoreNavigationCommands2.ScrollEditorBottom = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "scrollEditorBottom", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus } }); } runCoreEditorCommand(viewModel, args) { CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, { to: EditorScroll_.RawDirection.Down, by: EditorScroll_.RawUnit.Editor, value: 1, revealCursor: false, select: false, source: args.source }); } }()); CoreNavigationCommands2.ScrollLeft = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "scrollLeft", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus } }); } runCoreEditorCommand(viewModel, args) { CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, { to: EditorScroll_.RawDirection.Left, by: EditorScroll_.RawUnit.Column, value: 2, revealCursor: false, select: false, source: args.source }); } }()); CoreNavigationCommands2.ScrollRight = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "scrollRight", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus } }); } runCoreEditorCommand(viewModel, args) { CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, { to: EditorScroll_.RawDirection.Right, by: EditorScroll_.RawUnit.Column, value: 2, revealCursor: false, select: false, source: args.source }); } }()); class WordCommand extends CoreEditorCommand { constructor(opts) { super(opts); this._inSelectionMode = opts.inSelectionMode; } runCoreEditorCommand(viewModel, args) { if (!args.position) { return; } viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, [ CursorMoveCommands.word(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position) ]); if (args.revealType !== 2) { viewModel.revealAllCursors(args.source, true, true); } } } CoreNavigationCommands2.WordSelect = registerEditorCommand(new WordCommand({ inSelectionMode: false, id: "_wordSelect", precondition: void 0 })); CoreNavigationCommands2.WordSelectDrag = registerEditorCommand(new WordCommand({ inSelectionMode: true, id: "_wordSelectDrag", precondition: void 0 })); CoreNavigationCommands2.LastCursorWordSelect = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "lastCursorWordSelect", precondition: void 0 }); } runCoreEditorCommand(viewModel, args) { if (!args.position) { return; } const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex(); const states = viewModel.getCursorStates(); const newStates = states.slice(0); const lastAddedState = states[lastAddedCursorIndex]; newStates[lastAddedCursorIndex] = CursorMoveCommands.word(viewModel, lastAddedState, lastAddedState.modelState.hasSelection(), args.position); viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, newStates); } }()); class LineCommand extends CoreEditorCommand { constructor(opts) { super(opts); this._inSelectionMode = opts.inSelectionMode; } runCoreEditorCommand(viewModel, args) { if (!args.position) { return; } viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, [ CursorMoveCommands.line(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position, args.viewPosition) ]); if (args.revealType !== 2) { viewModel.revealAllCursors(args.source, false, true); } } } CoreNavigationCommands2.LineSelect = registerEditorCommand(new LineCommand({ inSelectionMode: false, id: "_lineSelect", precondition: void 0 })); CoreNavigationCommands2.LineSelectDrag = registerEditorCommand(new LineCommand({ inSelectionMode: true, id: "_lineSelectDrag", precondition: void 0 })); class LastCursorLineCommand extends CoreEditorCommand { constructor(opts) { super(opts); this._inSelectionMode = opts.inSelectionMode; } runCoreEditorCommand(viewModel, args) { if (!args.position) { return; } const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex(); const states = viewModel.getCursorStates(); const newStates = states.slice(0); newStates[lastAddedCursorIndex] = CursorMoveCommands.line(viewModel, states[lastAddedCursorIndex], this._inSelectionMode, args.position, args.viewPosition); viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, newStates); } } CoreNavigationCommands2.LastCursorLineSelect = registerEditorCommand(new LastCursorLineCommand({ inSelectionMode: false, id: "lastCursorLineSelect", precondition: void 0 })); CoreNavigationCommands2.LastCursorLineSelectDrag = registerEditorCommand(new LastCursorLineCommand({ inSelectionMode: true, id: "lastCursorLineSelectDrag", precondition: void 0 })); CoreNavigationCommands2.CancelSelection = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "cancelSelection", precondition: EditorContextKeys.hasNonEmptySelection, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 9, secondary: [ 1024 | 9 /* KeyCode.Escape */ ] } }); } runCoreEditorCommand(viewModel, args) { viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, [ CursorMoveCommands.cancelSelection(viewModel, viewModel.getPrimaryCursorState()) ]); viewModel.revealAllCursors(args.source, true); } }()); CoreNavigationCommands2.RemoveSecondaryCursors = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "removeSecondaryCursors", precondition: EditorContextKeys.hasMultipleSelections, kbOpts: { weight: CORE_WEIGHT + 1, kbExpr: EditorContextKeys.textInputFocus, primary: 9, secondary: [ 1024 | 9 /* KeyCode.Escape */ ] } }); } runCoreEditorCommand(viewModel, args) { viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, [ viewModel.getPrimaryCursorState() ]); viewModel.revealAllCursors(args.source, true); status(localize(63, "Removed secondary cursors")); } }()); CoreNavigationCommands2.RevealLine = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "revealLine", precondition: void 0, metadata: RevealLine_.metadata }); } runCoreEditorCommand(viewModel, args) { const revealLineArg = args; const lineNumberArg = revealLineArg.lineNumber || 0; let lineNumber = typeof lineNumberArg === "number" ? lineNumberArg + 1 : parseInt(lineNumberArg) + 1; if (lineNumber < 1) { lineNumber = 1; } const lineCount = viewModel.model.getLineCount(); if (lineNumber > lineCount) { lineNumber = lineCount; } const range2 = new Range$2(lineNumber, 1, lineNumber, viewModel.model.getLineMaxColumn(lineNumber)); let revealAt = 0; if (revealLineArg.at) { switch (revealLineArg.at) { case RevealLine_.RawAtArgument.Top: revealAt = 3; break; case RevealLine_.RawAtArgument.Center: revealAt = 1; break; case RevealLine_.RawAtArgument.Bottom: revealAt = 4; break; } } const viewRange = viewModel.coordinatesConverter.convertModelRangeToViewRange(range2); viewModel.revealRange( args.source, false, viewRange, revealAt, 0 /* ScrollType.Smooth */ ); } }()); CoreNavigationCommands2.SelectAll = new class extends EditorOrNativeTextInputCommand { constructor() { super(SelectAllCommand); } runDOMCommand(activeElement) { if (isFirefox$1) { activeElement.focus(); activeElement.select(); } activeElement.ownerDocument.execCommand("selectAll"); } runEditorCommand(accessor, editor2, args) { const viewModel = editor2._getViewModel(); if (!viewModel) { return; } this.runCoreEditorCommand(viewModel, args); } runCoreEditorCommand(viewModel, args) { viewModel.model.pushStackElement(); viewModel.setCursorStates("keyboard", 3, [ CursorMoveCommands.selectAll(viewModel, viewModel.getPrimaryCursorState()) ]); } }(); CoreNavigationCommands2.SetSelection = registerEditorCommand(new class extends CoreEditorCommand { constructor() { super({ id: "setSelection", precondition: void 0 }); } runCoreEditorCommand(viewModel, args) { if (!args.selection) { return; } viewModel.model.pushStackElement(); viewModel.setCursorStates(args.source, 3, [ CursorState$1.fromModelSelection(args.selection) ]); } }()); })(CoreNavigationCommands || (CoreNavigationCommands = {})); const columnSelectionCondition = ContextKeyExpr.and(EditorContextKeys.textInputFocus, EditorContextKeys.columnSelection); function registerColumnSelection(id, keybinding) { KeybindingsRegistry.registerKeybindingRule({ id, primary: keybinding, when: columnSelectionCondition, weight: CORE_WEIGHT + 1 }); } registerColumnSelection( CoreNavigationCommands.CursorColumnSelectLeft.id, 1024 | 15 /* KeyCode.LeftArrow */ ); registerColumnSelection( CoreNavigationCommands.CursorColumnSelectRight.id, 1024 | 17 /* KeyCode.RightArrow */ ); registerColumnSelection( CoreNavigationCommands.CursorColumnSelectUp.id, 1024 | 16 /* KeyCode.UpArrow */ ); registerColumnSelection( CoreNavigationCommands.CursorColumnSelectPageUp.id, 1024 | 11 /* KeyCode.PageUp */ ); registerColumnSelection( CoreNavigationCommands.CursorColumnSelectDown.id, 1024 | 18 /* KeyCode.DownArrow */ ); registerColumnSelection( CoreNavigationCommands.CursorColumnSelectPageDown.id, 1024 | 12 /* KeyCode.PageDown */ ); function registerCommand$2(command) { command.register(); return command; } var CoreEditingCommands; (function(CoreEditingCommands2) { class CoreEditingCommand extends EditorCommand { runEditorCommand(accessor, editor2, args) { const viewModel = editor2._getViewModel(); if (!viewModel) { return; } this.runCoreEditingCommand(editor2, viewModel, args || {}); } } CoreEditingCommands2.CoreEditingCommand = CoreEditingCommand; CoreEditingCommands2.LineBreakInsert = registerEditorCommand(new class extends CoreEditingCommand { constructor() { super({ id: "lineBreakInsert", precondition: EditorContextKeys.writable, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 0, mac: { primary: 256 | 45 /* KeyCode.KeyO */ } } }); } runCoreEditingCommand(editor2, viewModel, args) { editor2.pushUndoStop(); editor2.executeCommands(this.id, EnterOperation.lineBreakInsert(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection))); } }()); CoreEditingCommands2.Outdent = registerEditorCommand(new class extends CoreEditingCommand { constructor() { super({ id: "outdent", precondition: EditorContextKeys.writable, kbOpts: { weight: CORE_WEIGHT, kbExpr: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus), primary: 1024 | 2 /* KeyCode.Tab */ } }); } runCoreEditingCommand(editor2, viewModel, args) { editor2.pushUndoStop(); editor2.executeCommands(this.id, TypeOperations.outdent(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection))); editor2.pushUndoStop(); } }()); CoreEditingCommands2.Tab = registerEditorCommand(new class extends CoreEditingCommand { constructor() { super({ id: "tab", precondition: EditorContextKeys.writable, kbOpts: { weight: CORE_WEIGHT, kbExpr: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus), primary: 2 /* KeyCode.Tab */ } }); } runCoreEditingCommand(editor2, viewModel, args) { editor2.pushUndoStop(); editor2.executeCommands(this.id, TypeOperations.tab(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection))); editor2.pushUndoStop(); } }()); CoreEditingCommands2.DeleteLeft = registerEditorCommand(new class extends CoreEditingCommand { constructor() { super({ id: "deleteLeft", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 1, secondary: [ 1024 | 1 /* KeyCode.Backspace */ ], mac: { primary: 1, secondary: [ 1024 | 1, 256 | 38, 256 | 1 /* KeyCode.Backspace */ ] } } }); } runCoreEditingCommand(editor2, viewModel, args) { const [shouldPushStackElementBefore, commands] = DeleteOperations.deleteLeft(viewModel.getPrevEditOperationType(), viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection), viewModel.getCursorAutoClosedCharacters()); if (shouldPushStackElementBefore) { editor2.pushUndoStop(); } editor2.executeCommands(this.id, commands); viewModel.setPrevEditOperationType( 2 /* EditOperationType.DeletingLeft */ ); } }()); CoreEditingCommands2.DeleteRight = registerEditorCommand(new class extends CoreEditingCommand { constructor() { super({ id: "deleteRight", precondition: void 0, kbOpts: { weight: CORE_WEIGHT, kbExpr: EditorContextKeys.textInputFocus, primary: 20, mac: { primary: 20, secondary: [ 256 | 34, 256 | 20 /* KeyCode.Delete */ ] } } }); } runCoreEditingCommand(editor2, viewModel, args) { const [shouldPushStackElementBefore, commands] = DeleteOperations.deleteRight(viewModel.getPrevEditOperationType(), viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection)); if (shouldPushStackElementBefore) { editor2.pushUndoStop(); } editor2.executeCommands(this.id, commands); viewModel.setPrevEditOperationType( 3 /* EditOperationType.DeletingRight */ ); } }()); CoreEditingCommands2.Undo = new class extends EditorOrNativeTextInputCommand { constructor() { super(UndoCommand); } runDOMCommand(activeElement) { activeElement.ownerDocument.execCommand("undo"); } runEditorCommand(accessor, editor2, args) { if (!editor2.hasModel() || editor2.getOption( 104 /* EditorOption.readOnly */ ) === true) { return; } return editor2.getModel().undo(); } }(); CoreEditingCommands2.Redo = new class extends EditorOrNativeTextInputCommand { constructor() { super(RedoCommand); } runDOMCommand(activeElement) { activeElement.ownerDocument.execCommand("redo"); } runEditorCommand(accessor, editor2, args) { if (!editor2.hasModel() || editor2.getOption( 104 /* EditorOption.readOnly */ ) === true) { return; } return editor2.getModel().redo(); } }(); })(CoreEditingCommands || (CoreEditingCommands = {})); class EditorHandlerCommand extends Command$1 { constructor(id, handlerId, metadata) { super({ id, precondition: void 0, metadata }); this._handlerId = handlerId; } runCommand(accessor, args) { const editor2 = accessor.get(ICodeEditorService).getFocusedCodeEditor(); if (!editor2) { return; } editor2.trigger("keyboard", this._handlerId, args); } } function registerOverwritableCommand(handlerId, metadata) { registerCommand$2(new EditorHandlerCommand("default:" + handlerId, handlerId)); registerCommand$2(new EditorHandlerCommand(handlerId, handlerId, metadata)); } registerOverwritableCommand("type", { description: `Type`, args: [{ name: "args", schema: { "type": "object", "required": ["text"], "properties": { "text": { "type": "string" } } } }] }); registerOverwritableCommand( "replacePreviousChar" /* Handler.ReplacePreviousChar */ ); registerOverwritableCommand( "compositionType" /* Handler.CompositionType */ ); registerOverwritableCommand( "compositionStart" /* Handler.CompositionStart */ ); registerOverwritableCommand( "compositionEnd" /* Handler.CompositionEnd */ ); registerOverwritableCommand( "paste" /* Handler.Paste */ ); registerOverwritableCommand( "cut" /* Handler.Cut */ ); const IMarkerDecorationsService = createDecorator("markerDecorationsService"); var __decorate$32 = function(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d = decorators[i2]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __param$2X = function(paramIndex, decorator) { return function(target, key) { decorator(target, key, paramIndex); }; }; let MarkerDecorationsContribution = (_d = class { constructor(_editor, _markerDecorationsService) { } dispose() { } }, _d.ID = "editor.contrib.markerDecorations", _d); MarkerDecorationsContribution = __decorate$32([ __param$2X(1, IMarkerDecorationsService) ], MarkerDecorationsContribution); registerEditorContribution( MarkerDecorationsContribution.ID, MarkerDecorationsContribution, 0 /* EditorContributionInstantiation.Eager */ ); class FastDomNode { constructor(domNode) { this.domNode = domNode; this._maxWidth = ""; this._width = ""; this._height = ""; this._top = ""; this._left = ""; this._bottom = ""; this._right = ""; this._paddingLeft = ""; this._fontFamily = ""; this._fontWeight = ""; this._fontSize = ""; this._fontStyle = ""; this._fontFeatureSettings = ""; this._fontVariationSettings = ""; this._textDecoration = ""; this._lineHeight = ""; this._letterSpacing = ""; this._className = ""; this._display = ""; this._position = ""; this._visibility = ""; this._color = ""; this._backgroundColor = ""; this._layerHint = false; this._contain = "none"; this._boxShadow = ""; } focus() { this.domNode.focus(); } setMaxWidth(_maxWidth) { const maxWidth = numberAsPixels(_maxWidth); if (this._maxWidth === maxWidth) { return; } this._maxWidth = maxWidth; this.domNode.style.maxWidth = this._maxWidth; } setWidth(_width) { const width2 = numberAsPixels(_width); if (this._width === width2) { return; } this._width = width2; this.domNode.style.width = this._width; } setHeight(_height) { const height = numberAsPixels(_height); if (this._height === height) { return; } this._height = height; this.domNode.style.height = this._height; } setTop(_top) { const top = numberAsPixels(_top); if (this._top === top) { return; } this._top = top; this.domNode.style.top = this._top; } setLeft(_left) { const left = numberAsPixels(_left); if (this._left === left) { return; } this._left = left; this.domNode.style.left = this._left; } setBottom(_bottom) { const bottom = numberAsPixels(_bottom); if (this._bottom === bottom) { return; } this._bottom = bottom; this.domNode.style.bottom = this._bottom; } setRight(_right) { const right = numberAsPixels(_right); if (this._right === right) { return; } this._right = right; this.domNode.style.right = this._right; } setPaddingLeft(_paddingLeft) { const paddingLeft = numberAsPixels(_paddingLeft); if (this._paddingLeft === paddingLeft) { return; } this._paddingLeft = paddingLeft; this.domNode.style.paddingLeft = this._paddingLeft; } setFontFamily(fontFamily) { if (this._fontFamily === fontFamily) { return; } this._fontFamily = fontFamily; this.domNode.style.fontFamily = this._fontFamily; } setFontWeight(fontWeight) { if (this._fontWeight === fontWeight) { return; } this._fontWeight = fontWeight; this.domNode.style.fontWeight = this._fontWeight; } setFontSize(_fontSize) { const fontSize = numberAsPixels(_fontSize); if (this._fontSize === fontSize) { return; } this._fontSize = fontSize; this.domNode.style.fontSize = this._fontSize; } setFontStyle(fontStyle) { if (this._fontStyle === fontStyle) { return; } this._fontStyle = fontStyle; this.domNode.style.fontStyle = this._fontStyle; } setFontFeatureSettings(fontFeatureSettings) { if (this._fontFeatureSettings === fontFeatureSettings) { return; } this._fontFeatureSettings = fontFeatureSettings; this.domNode.style.fontFeatureSettings = this._fontFeatureSettings; } setFontVariationSettings(fontVariationSettings) { if (this._fontVariationSettings === fontVariationSettings) { return; } this._fontVariationSettings = fontVariationSettings; this.domNode.style.fontVariationSettings = this._fontVariationSettings; } setTextDecoration(textDecoration) { if (this._textDecoration === textDecoration) { return; } this._textDecoration = textDecoration; this.domNode.style.textDecoration = this._textDecoration; } setLineHeight(_lineHeight) { const lineHeight = numberAsPixels(_lineHeight); if (this._lineHeight === lineHeight) { return; } this._lineHeight = lineHeight; this.domNode.style.lineHeight = this._lineHeight; } setLetterSpacing(_letterSpacing) { const letterSpacing = numberAsPixels(_letterSpacing); if (this._letterSpacing === letterSpacing) { return; } this._letterSpacing = letterSpacing; this.domNode.style.letterSpacing = this._letterSpacing; } setClassName(className2) { if (this._className === className2) { return; } this._className = className2; this.domNode.className = this._className; } toggleClassName(className2, shouldHaveIt) { this.domNode.classList.toggle(className2, shouldHaveIt); this._className = this.domNode.className; } setDisplay(display) { if (this._display === display) { return; } this._display = display; this.domNode.style.display = this._display; } setPosition(position) { if (this._position === position) { return; } this._position = position; this.domNode.style.position = this._position; } setVisibility(visibility) { if (this._visibility === visibility) { return; } this._visibility = visibility; this.domNode.style.visibility = this._visibility; } setColor(color) { if (this._color === color) { return; } this._color = color; this.domNode.style.color = this._color; } setBackgroundColor(backgroundColor) { if (this._backgroundColor === backgroundColor) { return; } this._backgroundColor = backgroundColor; this.domNode.style.backgroundColor = this._backgroundColor; } setLayerHinting(layerHint) { if (this._layerHint === layerHint) { return; } this._layerHint = layerHint; this.domNode.style.transform = this._layerHint ? "translate3d(0px, 0px, 0px)" : ""; } setBoxShadow(boxShadow) { if (this._boxShadow === boxShadow) { return; } this._boxShadow = boxShadow; this.domNode.style.boxShadow = boxShadow; } setContain(contain) { if (this._contain === contain) { return; } this._contain = contain; this.domNode.style.contain = this._contain; } setAttribute(name, value) { this.domNode.setAttribute(name, value); } removeAttribute(name) { this.domNode.removeAttribute(name); } appendChild(child) { this.domNode.appendChild(child.domNode); } removeChild(child) { this.domNode.removeChild(child.domNode); } } function numberAsPixels(value) { return typeof value === "number" ? `${value}px` : value; } function createFastDomNode(domNode) { return new FastDomNode(domNode); } function applyFontInfo(domNode, fontInfo) { if (domNode instanceof FastDomNode) { domNode.setFontFamily(fontInfo.getMassagedFontFamily()); domNode.setFontWeight(fontInfo.fontWeight); domNode.setFontSize(fontInfo.fontSize); domNode.setFontFeatureSettings(fontInfo.fontFeatureSettings); domNode.setFontVariationSettings(fontInfo.fontVariationSettings); domNode.setLineHeight(fontInfo.lineHeight); domNode.setLetterSpacing(fontInfo.letterSpacing); } else { domNode.style.fontFamily = fontInfo.getMassagedFontFamily(); domNode.style.fontWeight = fontInfo.fontWeight; domNode.style.fontSize = fontInfo.fontSize + "px"; domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings; domNode.style.fontVariationSettings = fontInfo.fontVariationSettings; domNode.style.lineHeight = fontInfo.lineHeight + "px"; domNode.style.letterSpacing = fontInfo.letterSpacing + "px"; } } class ElementSizeObserver extends Disposable { constructor(referenceDomElement, dimension) { super(); this._onDidChange = this._register(new Emitter$1()); this.onDidChange = this._onDidChange.event; this._referenceDomElement = referenceDomElement; this._width = -1; this._height = -1; this._resizeObserver = null; this.measureReferenceDomElement(false, dimension); } dispose() { this.stopObserving(); super.dispose(); } getWidth() { return this._width; } getHeight() { return this._height; } startObserving() { if (!this._resizeObserver && this._referenceDomElement) { let observedDimenstion = null; const observeNow = () => { if (observedDimenstion) { this.observe({ width: observedDimenstion.width, height: observedDimenstion.height }); } else { this.observe(); } }; let shouldObserve = false; let alreadyObservedThisAnimationFrame = false; const update = () => { if (shouldObserve && !alreadyObservedThisAnimationFrame) { try { shouldObserve = false; alreadyObservedThisAnimationFrame = true; observeNow(); } finally { scheduleAtNextAnimationFrame(getWindow(this._referenceDomElement), () => { alreadyObservedThisAnimationFrame = false; update(); }); } } }; this._resizeObserver = new ResizeObserver((entries2) => { if (entries2 && entries2[0] && entries2[0].contentRect) { observedDimenstion = { width: entries2[0].contentRect.width, height: entries2[0].contentRect.height }; } else { observedDimenstion = null; } shouldObserve = true; update(); }); this._resizeObserver.observe(this._referenceDomElement); } } stopObserving() { if (this._resizeObserver) { this._resizeObserver.disconnect(); this._resizeObserver = null; } } observe(dimension) { this.measureReferenceDomElement(true, dimension); } measureReferenceDomElement(emitEvent, dimension) { let observedWidth = 0; let observedHeight = 0; if (dimension) { observedWidth = dimension.width; observedHeight = dimension.height; } else if (this._referenceDomElement) { observedWidth = this._referenceDomElement.clientWidth; observedHeight = this._referenceDomElement.clientHeight; } observedWidth = Math.max(5, observedWidth); observedHeight = Math.max(5, observedHeight); if (this._width !== observedWidth || this._height !== observedHeight) { this._width = observedWidth; this._height = observedHeight; if (emitEvent) { this._onDidChange.fire(); } } } } class DevicePixelRatioMonitor extends Disposable { constructor(targetWindow) { super(); this._onDidChange = this._register(new Emitter$1()); this.onDidChange = this._onDidChange.event; this._listener = () => this._handleChange(targetWindow, true); this._mediaQueryList = null; this._handleChange(targetWindow, false); } _handleChange(targetWindow, fireEvent) { this._mediaQueryList?.removeEventListener("change", this._listener); this._mediaQueryList = targetWindow.matchMedia(`(resolution: ${targetWindow.devicePixelRatio}dppx)`); this._mediaQueryList.addEventListener("change", this._listener); if (fireEvent) { this._onDidChange.fire(); } } } class PixelRatioMonitorImpl extends Disposable { get value() { return this._value; } constructor(targetWindow) { super(); this._onDidChange = this._register(new Emitter$1()); this.onDidChange = this._onDidChange.event; this._value = this._getPixelRatio(targetWindow); const dprMonitor = this._register(new DevicePixelRatioMonitor(targetWindow)); this._register(dprMonitor.onDidChange(() => { this._value = this._getPixelRatio(targetWindow); this._onDidChange.fire(this._value); })); } _getPixelRatio(targetWindow) { const ctx = document.createElement("canvas").getContext("2d"); const dpr = targetWindow.devicePixelRatio || 1; const bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; return dpr / bsr; } } class PixelRatioMonitorFacade { constructor() { this.mapWindowIdToPixelRatioMonitor = /* @__PURE__ */ new Map(); } _getOrCreatePixelRatioMonitor(targetWindow) { const targetWindowId = getWindowId(targetWindow); let pixelRatioMonitor = this.mapWindowIdToPixelRatioMonitor.get(targetWindowId); if (!pixelRatioMonitor) { pixelRatioMonitor = markAsSingleton(new PixelRatioMonitorImpl(targetWindow)); this.mapWindowIdToPixelRatioMonitor.set(targetWindowId, pixelRatioMonitor); markAsSingleton(Event.once(onDidUnregisterWindow)(({ vscodeWindowId }) => { if (vscodeWindowId === targetWindowId) { pixelRatioMonitor?.dispose(); this.mapWindowIdToPixelRatioMonitor.delete(targetWindowId); } })); } return pixelRatioMonitor; } getInstance(targetWindow) { return this._getOrCreatePixelRatioMonitor(targetWindow); } } const PixelRatio = new PixelRatioMonitorFacade(); class CharWidthRequest { constructor(chr, type) { this.chr = chr; this.type = type; this.width = 0; } fulfill(width2) { this.width = width2; } } class DomCharWidthReader { constructor(bareFontInfo, requests) { this._bareFontInfo = bareFontInfo; this._requests = requests; this._container = null; this._testElements = null; } read(targetWindow) { this._createDomElements(); targetWindow.document.body.appendChild(this._container); this._readFromDomElements(); this._container?.remove(); this._container = null; this._testElements = null; } _createDomElements() { const container = document.createElement("div"); container.style.position = "absolute"; container.style.top = "-50000px"; container.style.width = "50000px"; const regularDomNode = document.createElement("div"); applyFontInfo(regularDomNode, this._bareFontInfo); container.appendChild(regularDomNode); const boldDomNode = document.createElement("div"); applyFontInfo(boldDomNode, this._bareFontInfo); boldDomNode.style.fontWeight = "bold"; container.appendChild(boldDomNode); const italicDomNode = document.createElement("div"); applyFontInfo(italicDomNode, this._bareFontInfo); italicDomNode.style.fontStyle = "italic"; container.appendChild(italicDomNode); const testElements = []; for (const request of this._requests) { let parent; if (request.type === 0) { parent = regularDomNode; } if (request.type === 2) { parent = boldDomNode; } if (request.type === 1) { parent = italicDomNode; } parent.appendChild(document.createElement("br")); const testElement = document.createElement("span"); DomCharWidthReader._render(testElement, request); parent.appendChild(testElement); testElements.push(testElement); } this._container = container; this._testElements = testElements; } static _render(testElement, request) { if (request.chr === " ") { let htmlString = " "; for (let i2 = 0; i2 < 8; i2++) { htmlString += htmlString; } testElement.innerText = htmlString; } else { let testString = request.chr; for (let i2 = 0; i2 < 8; i2++) { testString += testString; } testElement.textContent = testString; } } _readFromDomElements() { for (let i2 = 0, len = this._requests.length; i2 < len; i2++) { const request = this._requests[i2]; const testElement = this._testElements[i2]; request.fulfill(testElement.offsetWidth / 256); } } } function readCharWidths(targetWindow, bareFontInfo, requests) { const reader = new DomCharWidthReader(bareFontInfo, requests); reader.read(targetWindow); } const EDITOR_MODEL_DEFAULTS = { tabSize: 4, indentSize: 4, insertSpaces: true, detectIndentation: true, trimAutoWhitespace: true, largeFileOptimizations: true, bracketPairColorizationOptions: { enabled: true, independentColorPoolPerBracketType: false } }; const MINIMAP_GUTTER_WIDTH = 8; class ConfigurationChangedEvent { /** * @internal */ constructor(values) { this._values = values; } hasChanged(id) { return this._values[id]; } } class ComputeOptionsMemory { constructor() { this.stableMinimapLayoutInput = null; this.stableFitMaxMinimapScale = 0; this.stableFitRemainingWidth = 0; } } class BaseEditorOption { constructor(id, name, defaultValue, schema) { this.id = id; this.name = name; this.defaultValue = defaultValue; this.schema = schema; } applyUpdate(value, update) { return applyUpdate(value, update); } compute(env2, options, value) { return value; } } class ApplyUpdateResult { constructor(newValue, didChange) { this.newValue = newValue; this.didChange = didChange; } } function applyUpdate(value, update) { if (typeof value !== "object" || typeof update !== "object" || !value || !update) { return new ApplyUpdateResult(update, value !== update); } if (Array.isArray(value) || Array.isArray(update)) { const arrayEquals = Array.isArray(value) && Array.isArray(update) && equals$1(value, update); return new ApplyUpdateResult(update, !arrayEquals); } let didChange = false; for (const key in update) { if (update.hasOwnProperty(key)) { const result = applyUpdate(value[key], update[key]); if (result.didChange) { value[key] = result.newValue; didChange = true; } } } return new ApplyUpdateResult(value, didChange); } class ComputedEditorOption { constructor(id) { this.schema = void 0; this.id = id; this.name = "_never_"; this.defaultValue = void 0; } applyUpdate(value, update) { return applyUpdate(value, update); } validate(input) { return this.defaultValue; } } class SimpleEditorOption { constructor(id, name, defaultValue, schema) { this.id = id; this.name = name; this.defaultValue = defaultValue; this.schema = schema; } applyUpdate(value, update) { return applyUpdate(value, update); } validate(input) { if (typeof input === "undefined") { return this.defaultValue; } return input; } compute(env2, options, value) { return value; } } function boolean(value, defaultValue) { if (typeof value === "undefined") { return defaultValue; } if (value === "false") { return false; } return Boolean(value); } class EditorBooleanOption extends SimpleEditorOption { constructor(id, name, defaultValue, schema = void 0) { if (typeof schema !== "undefined") { schema.type = "boolean"; schema.default = defaultValue; } super(id, name, defaultValue, schema); } validate(input) { return boolean(input, this.defaultValue); } } function clampedInt(value, defaultValue, minimum, maximum) { if (typeof value === "undefined") { return defaultValue; } let r = parseInt(value, 10); if (isNaN(r)) { return defaultValue; } r = Math.max(minimum, r); r = Math.min(maximum, r); return r | 0; } class EditorIntOption extends SimpleEditorOption { static clampedInt(value, defaultValue, minimum, maximum) { return clampedInt(value, defaultValue, minimum, maximum); } constructor(id, name, defaultValue, minimum, maximum, schema = void 0) { if (typeof schema !== "undefined") { schema.type = "integer"; schema.default = defaultValue; schema.minimum = minimum; schema.maximum = maximum; } super(id, name, defaultValue, schema); this.minimum = minimum; this.maximum = maximum; } validate(input) { return EditorIntOption.clampedInt(input, this.defaultValue, this.minimum, this.maximum); } } function clampedFloat(value, defaultValue, minimum, maximum) { if (typeof value === "undefined") { return defaultValue; } const r = EditorFloatOption.float(value, defaultValue); return EditorFloatOption.clamp(r, minimum, maximum); } class EditorFloatOption extends SimpleEditorOption { static clamp(n2, min, max) { if (n2 < min) { return min; } if (n2 > max) { return max; } return n2; } static float(value, defaultValue) { if (typeof value === "number") { return value; } if (typeof value === "undefined") { return defaultValue; } const r = parseFloat(value); return isNaN(r) ? defaultValue : r; } constructor(id, name, defaultValue, validationFn, schema, minimum, maximum) { if (typeof schema !== "undefined") { schema.type = "number"; schema.default = defaultValue; schema.minimum = minimum; schema.maximum = maximum; } super(id, name, defaultValue, schema); this.validationFn = validationFn; this.minimum = minimum; this.maximum = maximum; } validate(input) { return this.validationFn(EditorFloatOption.float(input, this.defaultValue)); } } class EditorStringOption extends SimpleEditorOption { static string(value, defaultValue) { if (typeof value !== "string") { return defaultValue; } return value; } constructor(id, name, defaultValue, schema = void 0) { if (typeof schema !== "undefined") { schema.type = "string"; schema.default = defaultValue; } super(id, name, defaultValue, schema); } validate(input) { return EditorStringOption.string(input, this.defaultValue); } } function stringSet(value, defaultValue, allowedValues, renamedValues) { if (typeof value !== "string") { return defaultValue; } if (renamedValues && value in renamedValues) { return renamedValues[value]; } if (allowedValues.indexOf(value) === -1) { return defaultValue; } return value; } class EditorStringEnumOption extends SimpleEditorOption { constructor(id, name, defaultValue, allowedValues, schema = void 0) { if (typeof schema !== "undefined") { schema.type = "string"; schema.enum = allowedValues; schema.default = defaultValue; } super(id, name, defaultValue, schema); this._allowedValues = allowedValues; } validate(input) { return stringSet(input, this.defaultValue, this._allowedValues); } } class EditorEnumOption extends BaseEditorOption { constructor(id, name, defaultValue, defaultStringValue, allowedValues, convert, schema = void 0) { if (typeof schema !== "undefined") { schema.type = "string"; schema.enum = allowedValues; schema.default = defaultStringValue; } super(id, name, defaultValue, schema); this._allowedValues = allowedValues; this._convert = convert; } validate(input) { if (typeof input !== "string") { return this.defaultValue; } if (this._allowedValues.indexOf(input) === -1) { return this.defaultValue; } return this._convert(input); } } function _autoIndentFromString(autoIndent) { switch (autoIndent) { case "none": return 0; case "keep": return 1; case "brackets": return 2; case "advanced": return 3; case "full": return 4; } } class EditorAccessibilitySupport extends BaseEditorOption { constructor() { super(2, "accessibilitySupport", 0, { type: "string", enum: ["auto", "on", "off"], enumDescriptions: [ localize(198, "Use platform APIs to detect when a Screen Reader is attached."), localize(199, "Optimize for usage with a Screen Reader."), localize(200, "Assume a screen reader is not attached.") ], default: "auto", tags: ["accessibility"], description: localize(201, "Controls if the UI should run in a mode where it is optimized for screen readers.") }); } validate(input) { switch (input) { case "auto": return 0; case "off": return 1; case "on": return 2; } return this.defaultValue; } compute(env2, options, value) { if (value === 0) { return env2.accessibilitySupport; } return value; } } class EditorComments extends BaseEditorOption { constructor() { const defaults = { insertSpace: true, ignoreEmptyLines: true }; super(29, "comments", defaults, { "editor.comments.insertSpace": { type: "boolean", default: defaults.insertSpace, description: localize(202, "Controls whether a space character is inserted when commenting.") }, "editor.comments.ignoreEmptyLines": { type: "boolean", default: defaults.ignoreEmptyLines, description: localize(203, "Controls if empty lines should be ignored with toggle, add or remove actions for line comments.") } }); } validate(_input) { if (!_input || typeof _input !== "object") { return this.defaultValue; } const input = _input; return { insertSpace: boolean(input.insertSpace, this.defaultValue.insertSpace), ignoreEmptyLines: boolean(input.ignoreEmptyLines, this.defaultValue.ignoreEmptyLines) }; } } function cursorBlinkingStyleFromString(cursorBlinkingStyle) { switch (cursorBlinkingStyle) { case "blink": return 1; case "smooth": return 2; case "phase": return 3; case "expand": return 4; case "solid": return 5; } } var TextEditorCursorStyle$1; (function(TextEditorCursorStyle2) { TextEditorCursorStyle2[TextEditorCursorStyle2["Line"] = 1] = "Line"; TextEditorCursorStyle2[TextEditorCursorStyle2["Block"] = 2] = "Block"; TextEditorCursorStyle2[TextEditorCursorStyle2["Underline"] = 3] = "Underline"; TextEditorCursorStyle2[TextEditorCursorStyle2["LineThin"] = 4] = "LineThin"; TextEditorCursorStyle2[TextEditorCursorStyle2["BlockOutline"] = 5] = "BlockOutline"; TextEditorCursorStyle2[TextEditorCursorStyle2["UnderlineThin"] = 6] = "UnderlineThin"; })(TextEditorCursorStyle$1 || (TextEditorCursorStyle$1 = {})); function cursorStyleFromString(cursorStyle) { switch (cursorStyle) { case "line": return TextEditorCursorStyle$1.Line; case "block": return TextEditorCursorStyle$1.Block; case "underline": return TextEditorCursorStyle$1.Underline; case "line-thin": return TextEditorCursorStyle$1.LineThin; case "block-outline": return TextEditorCursorStyle$1.BlockOutline; case "underline-thin": return TextEditorCursorStyle$1.UnderlineThin; } } class EditorClassName extends ComputedEditorOption { constructor() { super( 162 /* EditorOption.editorClassName */ ); } compute(env2, options, _) { const classNames2 = ["monaco-editor"]; if (options.get( 48 /* EditorOption.extraEditorClassName */ )) { classNames2.push(options.get( 48 /* EditorOption.extraEditorClassName */ )); } if (env2.extraEditorClassName) { classNames2.push(env2.extraEditorClassName); } if (options.get( 82 /* EditorOption.mouseStyle */ ) === "default") { classNames2.push("mouse-default"); } else if (options.get( 82 /* EditorOption.mouseStyle */ ) === "copy") { classNames2.push("mouse-copy"); } if (options.get( 127 /* EditorOption.showUnused */ )) { classNames2.push("showUnused"); } if (options.get( 157 /* EditorOption.showDeprecated */ )) { classNames2.push("showDeprecated"); } return classNames2.join(" "); } } class EditorEmptySelectionClipboard extends EditorBooleanOption { constructor() { super(45, "emptySelectionClipboard", true, { description: localize(204, "Controls whether copying without a selection copies the current line.") }); } compute(env2, options, value) { return value && env2.emptySelectionClipboard; } } class EditorFind extends BaseEditorOption { constructor() { const defaults = { cursorMoveOnType: true, findOnType: true, seedSearchStringFromSelection: "always", autoFindInSelection: "never", globalFindClipboard: false, addExtraSpaceOnTop: true, loop: true, history: "workspace", replaceHistory: "workspace" }; super(50, "find", defaults, { "editor.find.cursorMoveOnType": { type: "boolean", default: defaults.cursorMoveOnType, description: localize(205, "Controls whether the cursor should jump to find matches while typing.") }, "editor.find.seedSearchStringFromSelection": { type: "string", enum: ["never", "always", "selection"], default: defaults.seedSearchStringFromSelection, enumDescriptions: [ localize(206, "Never seed search string from the editor selection."), localize(207, "Always seed search string from the editor selection, including word at cursor position."), localize(208, "Only seed search string from the editor selection.") ], description: localize(209, "Controls whether the search string in the Find Widget is seeded from the editor selection.") }, "editor.find.autoFindInSelection": { type: "string", enum: ["never", "always", "multiline"], default: defaults.autoFindInSelection, enumDescriptions: [ localize(210, "Never turn on Find in Selection automatically (default)."), localize(211, "Always turn on Find in Selection automatically."), localize(212, "Turn on Find in Selection automatically when multiple lines of content are selected.") ], description: localize(213, "Controls the condition for turning on Find in Selection automatically.") }, "editor.find.globalFindClipboard": { type: "boolean", default: defaults.globalFindClipboard, description: localize(214, "Controls whether the Find Widget should read or modify the shared find clipboard on macOS."), included: isMacintosh }, "editor.find.addExtraSpaceOnTop": { type: "boolean", default: defaults.addExtraSpaceOnTop, description: localize(215, "Controls whether the Find Widget should add extra lines on top of the editor. When true, you can scroll beyond the first line when the Find Widget is visible.") }, "editor.find.loop": { type: "boolean", default: defaults.loop, description: localize(216, "Controls whether the search automatically restarts from the beginning (or the end) when no further matches can be found.") }, "editor.find.history": { type: "string", enum: ["never", "workspace"], default: "workspace", enumDescriptions: [ localize(217, "Do not store search history from the find widget."), localize(218, "Store search history across the active workspace") ], description: localize(219, "Controls how the find widget history should be stored") }, "editor.find.replaceHistory": { type: "string", enum: ["never", "workspace"], default: "workspace", enumDescriptions: [ localize(220, "Do not store history from the replace widget."), localize(221, "Store replace history across the active workspace") ], description: localize(222, "Controls how the replace widget history should be stored") }, "editor.find.findOnType": { type: "boolean", default: defaults.findOnType, description: localize(223, "Controls whether the Find Widget should search as you type.") } }); } validate(_input) { if (!_input || typeof _input !== "object") { return this.defaultValue; } const input = _input; return { cursorMoveOnType: boolean(input.cursorMoveOnType, this.defaultValue.cursorMoveOnType), findOnType: boolean(input.findOnType, this.defaultValue.findOnType), seedSearchStringFromSelection: typeof _input.seedSearchStringFromSelection === "boolean" ? _input.seedSearchStringFromSelection ? "always" : "never" : stringSet(input.seedSearchStringFromSelection, this.defaultValue.seedSearchStringFromSelection, ["never", "always", "selection"]), autoFindInSelection: typeof _input.autoFindInSelection === "boolean" ? _input.autoFindInSelection ? "always" : "never" : stringSet(input.autoFindInSelection, this.defaultValue.autoFindInSelection, ["never", "always", "multiline"]), globalFindClipboard: boolean(input.globalFindClipboard, this.defaultValue.globalFindClipboard), addExtraSpaceOnTop: boolean(input.addExtraSpaceOnTop, this.defaultValue.addExtraSpaceOnTop), loop: boolean(input.loop, this.defaultValue.loop), history: stringSet(input.history, this.defaultValue.history, ["never", "workspace"]), replaceHistory: stringSet(input.replaceHistory, this.defaultValue.replaceHistory, ["never", "workspace"]) }; } } const _EditorFontLigatures = class _EditorFontLigatures extends BaseEditorOption { constructor() { super(60, "fontLigatures", _EditorFontLigatures.OFF, { anyOf: [ { type: "boolean", description: localize(224, "Enables/Disables font ligatures ('calt' and 'liga' font features). Change this to a string for fine-grained control of the 'font-feature-settings' CSS property.") }, { type: "string", description: localize(225, "Explicit 'font-feature-settings' CSS property. A boolean can be passed instead if one only needs to turn on/off ligatures.") } ], description: localize(226, "Configures font ligatures or font features. Can be either a boolean to enable/disable ligatures or a string for the value of the CSS 'font-feature-settings' property."), default: false }); } validate(input) { if (typeof input === "undefined") { return this.defaultValue; } if (typeof input === "string") { if (input === "false" || input.length === 0) { return _EditorFontLigatures.OFF; } if (input === "true") { return _EditorFontLigatures.ON; } return input; } if (Boolean(input)) { return _EditorFontLigatures.ON; } return _EditorFontLigatures.OFF; } }; _EditorFontLigatures.OFF = '"liga" off, "calt" off'; _EditorFontLigatures.ON = '"liga" on, "calt" on'; let EditorFontLigatures = _EditorFontLigatures; const _EditorFontVariations = class _EditorFontVariations extends BaseEditorOption { constructor() { super(63, "fontVariations", _EditorFontVariations.OFF, { anyOf: [ { type: "boolean", description: localize(227, "Enables/Disables the translation from font-weight to font-variation-settings. Change this to a string for fine-grained control of the 'font-variation-settings' CSS property.") }, { type: "string", description: localize(228, "Explicit 'font-variation-settings' CSS property. A boolean can be passed instead if one only needs to translate font-weight to font-variation-settings.") } ], description: localize(229, "Configures font variations. Can be either a boolean to enable/disable the translation from font-weight to font-variation-settings or a string for the value of the CSS 'font-variation-settings' property."), default: false }); } validate(input) { if (typeof input === "undefined") { return this.defaultValue; } if (typeof input === "string") { if (input === "false") { return _EditorFontVariations.OFF; } if (input === "true") { return _EditorFontVariations.TRANSLATE; } return input; } if (Boolean(input)) { return _EditorFontVariations.TRANSLATE; } return _EditorFontVariations.OFF; } compute(env2, options, value) { return env2.fontInfo.fontVariationSettings; } }; _EditorFontVariations.OFF = "normal"; _EditorFontVariations.TRANSLATE = "translate"; let EditorFontVariations = _EditorFontVariations; class EditorFontInfo extends ComputedEditorOption { constructor() { super( 59 /* EditorOption.fontInfo */ ); } compute(env2, options, _) { return env2.fontInfo; } } class EffectiveCursorStyle extends ComputedEditorOption { constructor() { super( 161 /* EditorOption.effectiveCursorStyle */ ); } compute(env2, options, _) { return env2.inputMode === "overtype" ? options.get( 92 /* EditorOption.overtypeCursorStyle */ ) : options.get( 34 /* EditorOption.cursorStyle */ ); } } class EffectiveEditContextEnabled extends ComputedEditorOption { constructor() { super( 170 /* EditorOption.effectiveEditContext */ ); } compute(env2, options) { return env2.editContextSupported && options.get( 44 /* EditorOption.editContext */ ); } } class EffectiveAllowVariableFonts extends ComputedEditorOption { constructor() { super( 172 /* EditorOption.effectiveAllowVariableFonts */ ); } compute(env2, options) { const accessibilitySupport = env2.accessibilitySupport; if (accessibilitySupport === 2) { return options.get( 7 /* EditorOption.allowVariableFontsInAccessibilityMode */ ); } else { return options.get( 6 /* EditorOption.allowVariableFonts */ ); } } } class EditorFontSize extends SimpleEditorOption { constructor() { super(61, "fontSize", EDITOR_FONT_DEFAULTS.fontSize, { type: "number", minimum: 6, maximum: 100, default: EDITOR_FONT_DEFAULTS.fontSize, description: localize(230, "Controls the font size in pixels.") }); } validate(input) { const r = EditorFloatOption.float(input, this.defaultValue); if (r === 0) { return EDITOR_FONT_DEFAULTS.fontSize; } return EditorFloatOption.clamp(r, 6, 100); } compute(env2, options, value) { return env2.fontInfo.fontSize; } } const _EditorFontWeight = class _EditorFontWeight extends BaseEditorOption { constructor() { super(62, "fontWeight", EDITOR_FONT_DEFAULTS.fontWeight, { anyOf: [ { type: "number", minimum: _EditorFontWeight.MINIMUM_VALUE, maximum: _EditorFontWeight.MAXIMUM_VALUE, errorMessage: localize(231, 'Only "normal" and "bold" keywords or numbers between 1 and 1000 are allowed.') }, { type: "string", pattern: "^(normal|bold|1000|[1-9][0-9]{0,2})$" }, { enum: _EditorFontWeight.SUGGESTION_VALUES } ], default: EDITOR_FONT_DEFAULTS.fontWeight, description: localize(232, 'Controls the font weight. Accepts "normal" and "bold" keywords or numbers between 1 and 1000.') }); } validate(input) { if (input === "normal" || input === "bold") { return input; } return String(EditorIntOption.clampedInt(input, EDITOR_FONT_DEFAULTS.fontWeight, _EditorFontWeight.MINIMUM_VALUE, _EditorFontWeight.MAXIMUM_VALUE)); } }; _EditorFontWeight.SUGGESTION_VALUES = ["normal", "bold", "100", "200", "300", "400", "500", "600", "700", "800", "900"]; _EditorFontWeight.MINIMUM_VALUE = 1; _EditorFontWeight.MAXIMUM_VALUE = 1e3; let EditorFontWeight = _EditorFontWeight; class EditorGoToLocation extends BaseEditorOption { constructor() { const defaults = { multiple: "peek", multipleDefinitions: "peek", multipleTypeDefinitions: "peek", multipleDeclarations: "peek", multipleImplementations: "peek", multipleReferences: "peek", multipleTests: "peek", alternativeDefinitionCommand: "editor.action.goToReferences", alternativeTypeDefinitionCommand: "editor.action.goToReferences", alternativeDeclarationCommand: "editor.action.goToReferences", alternativeImplementationCommand: "", alternativeReferenceCommand: "", alternativeTestsCommand: "" }; const jsonSubset = { type: "string", enum: ["peek", "gotoAndPeek", "goto"], default: defaults.multiple, enumDescriptions: [ localize(233, "Show Peek view of the results (default)"), localize(234, "Go to the primary result and show a Peek view"), localize(235, "Go to the primary result and enable Peek-less navigation to others") ] }; const alternativeCommandOptions = ["", "editor.action.referenceSearch.trigger", "editor.action.goToReferences", "editor.action.peekImplementation", "editor.action.goToImplementation", "editor.action.peekTypeDefinition", "editor.action.goToTypeDefinition", "editor.action.peekDeclaration", "editor.action.revealDeclaration", "editor.action.peekDefinition", "editor.action.revealDefinitionAside", "editor.action.revealDefinition"]; super(67, "gotoLocation", defaults, { "editor.gotoLocation.multiple": { deprecationMessage: localize(236, "This setting is deprecated, please use separate settings like 'editor.editor.gotoLocation.multipleDefinitions' or 'editor.editor.gotoLocation.multipleImplementations' instead.") }, "editor.gotoLocation.multipleDefinitions": { description: localize(237, "Controls the behavior the 'Go to Definition'-command when multiple target locations exist."), ...jsonSubset }, "editor.gotoLocation.multipleTypeDefinitions": { description: localize(238, "Controls the behavior the 'Go to Type Definition'-command when multiple target locations exist."), ...jsonSubset }, "editor.gotoLocation.multipleDeclarations": { description: localize(239, "Controls the behavior the 'Go to Declaration'-command when multiple target locations exist."), ...jsonSubset }, "editor.gotoLocation.multipleImplementations": { description: localize(240, "Controls the behavior the 'Go to Implementations'-command when multiple target locations exist."), ...jsonSubset }, "editor.gotoLocation.multipleReferences": { description: localize(241, "Controls the behavior the 'Go to References'-command when multiple target locations exist."), ...jsonSubset }, "editor.gotoLocation.alternativeDefinitionCommand": { type: "string", default: defaults.alternativeDefinitionCommand, enum: alternativeCommandOptions, description: localize(242, "Alternative command id that is being executed when the result of 'Go to Definition' is the current location.") }, "editor.gotoLocation.alternativeTypeDefinitionCommand": { type: "string", default: defaults.alternativeTypeDefinitionCommand, enum: alternativeCommandOptions, description: localize(243, "Alternative command id that is being executed when the result of 'Go to Type Definition' is the current location.") }, "editor.gotoLocation.alternativeDeclarationCommand": { type: "string", default: defaults.alternativeDeclarationCommand, enum: alternativeCommandOptions, description: localize(244, "Alternative command id that is being executed when the result of 'Go to Declaration' is the current location.") }, "editor.gotoLocation.alternativeImplementationCommand": { type: "string", default: defaults.alternativeImplementationCommand, enum: alternativeCommandOptions, description: localize(245, "Alternative command id that is being executed when the result of 'Go to Implementation' is the current location.") }, "editor.gotoLocation.alternativeReferenceCommand": { type: "string", default: defaults.alternativeReferenceCommand, enum: alternativeCommandOptions, description: localize(246, "Alternative command id that is being executed when the result of 'Go to Reference' is the current location.") } }); } validate(_input) { if (!_input || typeof _input !== "object") { return this.defaultValue; } const input = _input; return { multiple: stringSet(input.multiple, this.defaultValue.multiple, ["peek", "gotoAndPeek", "goto"]), multipleDefinitions: input.multipleDefinitions ?? stringSet(input.multipleDefinitions, "peek", ["peek", "gotoAndPeek", "goto"]), multipleTypeDefinitions: input.multipleTypeDefinitions ?? stringSet(input.multipleTypeDefinitions, "peek", ["peek", "gotoAndPeek", "goto"]), multipleDeclarations: input.multipleDeclarations ?? stringSet(input.multipleDeclarations, "peek", ["peek", "gotoAndPeek", "goto"]), multipleImplementations: input.multipleImplementations ?? stringSet(input.multipleImplementations, "peek", ["peek", "gotoAndPeek", "goto"]), multipleReferences: input.multipleReferences ?? stringSet(input.multipleReferences, "peek", ["peek", "gotoAndPeek", "goto"]), multipleTests: input.multipleTests ?? stringSet(input.multipleTests, "peek", ["peek", "gotoAndPeek", "goto"]), alternativeDefinitionCommand: EditorStringOption.string(input.alternativeDefinitionCommand, this.defaultValue.alternativeDefinitionCommand), alternativeTypeDefinitionCommand: EditorStringOption.string(input.alternativeTypeDefinitionCommand, this.defaultValue.alternativeTypeDefinitionCommand), alternativeDeclarationCommand: EditorStringOption.string(input.alternativeDeclarationCommand, this.defaultValue.alternativeDeclarationCommand), alternativeImplementationCommand: EditorStringOption.string(input.alternativeImplementationCommand, this.defaultValue.alternativeImplementationCommand), alternativeReferenceCommand: EditorStringOption.string(input.alternativeReferenceCommand, this.defaultValue.alternativeReferenceCommand), alternativeTestsCommand: EditorStringOption.string(input.alternativeTestsCommand, this.defaultValue.alternativeTestsCommand) }; } } class EditorHover extends BaseEditorOption { constructor() { const defaults = { enabled: true, delay: 300, hidingDelay: 300, sticky: true, above: true }; super(69, "hover", defaults, { "editor.hover.enabled": { type: "boolean", default: defaults.enabled, description: localize(247, "Controls whether the hover is shown.") }, "editor.hover.delay": { type: "number", default: defaults.delay, minimum: 0, maximum: 1e4, description: localize(248, "Controls the delay in milliseconds after which the hover is shown.") }, "editor.hover.sticky": { type: "boolean", default: defaults.sticky, description: localize(249, "Controls whether the hover should remain visible when mouse is moved over it.") }, "editor.hover.hidingDelay": { type: "integer", minimum: 0, default: defaults.hidingDelay, markdownDescription: localize(250, "Controls the delay in milliseconds after which the hover is hidden. Requires `#editor.hover.sticky#` to be enabled.") }, "editor.hover.above": { type: "boolean", default: defaults.above, description: localize(251, "Prefer showing hovers above the line, if there's space.") } }); } validate(_input) { if (!_input || typeof _input !== "object") { return this.defaultValue; } const input = _input; return { enabled: boolean(input.enabled, this.defaultValue.enabled), delay: EditorIntOption.clampedInt(input.delay, this.defaultValue.delay, 0, 1e4), sticky: boolean(input.sticky, this.defaultValue.sticky), hidingDelay: EditorIntOption.clampedInt(input.hidingDelay, this.defaultValue.hidingDelay, 0, 6e5), above: boolean(input.above, this.defaultValue.above) }; } } class EditorLayoutInfoComputer extends ComputedEditorOption { constructor() { super( 165 /* EditorOption.layoutInfo */ ); } compute(env2, options, _) { return EditorLayoutInfoComputer.computeLayout(options, { memory: env2.memory, outerWidth: env2.outerWidth, outerHeight: env2.outerHeight, isDominatedByLongLines: env2.isDominatedByLongLines, lineHeight: env2.fontInfo.lineHeight, viewLineCount: env2.viewLineCount, lineNumbersDigitCount: env2.lineNumbersDigitCount, typicalHalfwidthCharacterWidth: env2.fontInfo.typicalHalfwidthCharacterWidth, maxDigitWidth: env2.fontInfo.maxDigitWidth, pixelRatio: env2.pixelRatio, glyphMarginDecorationLaneCount: env2.glyphMarginDecorationLaneCount }); } static computeContainedMinimapLineCount(input) { const typicalViewportLineCount = input.height / input.lineHeight; const extraLinesBeforeFirstLine = Math.floor(input.paddingTop / input.lineHeight); let extraLinesBeyondLastLine = Math.floor(input.paddingBottom / input.lineHeight); if (input.scrollBeyondLastLine) { extraLinesBeyondLastLine = Math.max(extraLinesBeyondLastLine, typicalViewportLineCount - 1); } const desiredRatio = (extraLinesBeforeFirstLine + input.viewLineCount + extraLinesBeyondLastLine) / (input.pixelRatio * input.height); const minimapLineCount = Math.floor(input.viewLineCount / desiredRatio); return { typicalViewportLineCount, extraLinesBeforeFirstLine, extraLinesBeyondLastLine, desiredRatio, minimapLineCount }; } static _computeMinimapLayout(input, memory) { const outerWidth = input.outerWidth; const outerHeight = input.outerHeight; const pixelRatio = input.pixelRatio; if (!input.minimap.enabled) { return { renderMinimap: 0, minimapLeft: 0, minimapWidth: 0, minimapHeightIsEditorHeight: false, minimapIsSampling: false, minimapScale: 1, minimapLineHeight: 1, minimapCanvasInnerWidth: 0, minimapCanvasInnerHeight: Math.floor(pixelRatio * outerHeight), minimapCanvasOuterWidth: 0, minimapCanvasOuterHeight: outerHeight }; } const stableMinimapLayoutInput = memory.stableMinimapLayoutInput; const couldUseMemory = stableMinimapLayoutInput && input.outerHeight === stableMinimapLayoutInput.outerHeight && input.lineHeight === stableMinimapLayoutInput.lineHeight && input.typicalHalfwidthCharacterWidth === stableMinimapLayoutInput.typicalHalfwidthCharacterWidth && input.pixelRatio === stableMinimapLayoutInput.pixelRatio && input.scrollBeyondLastLine === stableMinimapLayoutInput.scrollBeyondLastLine && input.paddingTop === stableMinimapLayoutInput.paddingTop && input.paddingBottom === stableMinimapLayoutInput.paddingBottom && input.minimap.enabled === stableMinimapLayoutInput.minimap.enabled && input.minimap.side === stableMinimapLayoutInput.minimap.side && input.minimap.size === stableMinimapLayoutInput.minimap.size && input.minimap.showSlider === stableMinimapLayoutInput.minimap.showSlider && input.minimap.renderCharacters === stableMinimapLayoutInput.minimap.renderCharacters && input.minimap.maxColumn === stableMinimapLayoutInput.minimap.maxColumn && input.minimap.scale === stableMinimapLayoutInput.minimap.scale && input.verticalScrollbarWidth === stableMinimapLayoutInput.verticalScrollbarWidth && input.isViewportWrapping === stableMinimapLayoutInput.isViewportWrapping; const lineHeight = input.lineHeight; const typicalHalfwidthCharacterWidth = input.typicalHalfwidthCharacterWidth; const scrollBeyondLastLine = input.scrollBeyondLastLine; const minimapRenderCharacters = input.minimap.renderCharacters; let minimapScale = pixelRatio >= 2 ? Math.round(input.minimap.scale * 2) : input.minimap.scale; const minimapMaxColumn = input.minimap.maxColumn; const minimapSize = input.minimap.size; const minimapSide = input.minimap.side; const verticalScrollbarWidth = input.verticalScrollbarWidth; const viewLineCount = input.viewLineCount; const remainingWidth = input.remainingWidth; const isViewportWrapping = input.isViewportWrapping; const baseCharHeight = minimapRenderCharacters ? 2 : 3; let minimapCanvasInnerHeight = Math.floor(pixelRatio * outerHeight); const minimapCanvasOuterHeight = minimapCanvasInnerHeight / pixelRatio; let minimapHeightIsEditorHeight = false; let minimapIsSampling = false; let minimapLineHeight = baseCharHeight * minimapScale; let minimapCharWidth = minimapScale / pixelRatio; let minimapWidthMultiplier = 1; if (minimapSize === "fill" || minimapSize === "fit") { const { typicalViewportLineCount, extraLinesBeforeFirstLine, extraLinesBeyondLastLine, desiredRatio, minimapLineCount } = EditorLayoutInfoComputer.computeContainedMinimapLineCount({ viewLineCount, scrollBeyondLastLine, paddingTop: input.paddingTop, paddingBottom: input.paddingBottom, height: outerHeight, lineHeight, pixelRatio }); const ratio = viewLineCount / minimapLineCount; if (ratio > 1) { minimapHeightIsEditorHeight = true; minimapIsSampling = true; minimapScale = 1; minimapLineHeight = 1; minimapCharWidth = minimapScale / pixelRatio; } else { let fitBecomesFill = false; let maxMinimapScale = minimapScale + 1; if (minimapSize === "fit") { const effectiveMinimapHeight = Math.ceil((extraLinesBeforeFirstLine + viewLineCount + extraLinesBeyondLastLine) * minimapLineHeight); if (isViewportWrapping && couldUseMemory && remainingWidth <= memory.stableFitRemainingWidth) { fitBecomesFill = true; maxMinimapScale = memory.stableFitMaxMinimapScale; } else { fitBecomesFill = effectiveMinimapHeight > minimapCanvasInnerHeight; } } if (minimapSize === "fill" || fitBecomesFill) { minimapHeightIsEditorHeight = true; const configuredMinimapScale = minimapScale; minimapLineHeight = Math.min(lineHeight * pixelRatio, Math.max(1, Math.floor(1 / desiredRatio))); if (isViewportWrapping && couldUseMemory && remainingWidth <= memory.stableFitRemainingWidth) { maxMinimapScale = memory.stableFitMaxMinimapScale; } minimapScale = Math.min(maxMinimapScale, Math.max(1, Math.floor(minimapLineHeight / baseCharHeight))); if (minimapScale > configuredMinimapScale) { minimapWidthMultiplier = Math.min(2, minimapScale / configuredMinimapScale); } minimapCharWidth = minimapScale / pixelRatio / minimapWidthMultiplier; minimapCanvasInnerHeight = Math.ceil(Math.max(typicalViewportLineCount, extraLinesBeforeFirstLine + viewLineCount + extraLinesBeyondLastLine) * minimapLineHeight); if (isViewportWrapping) { memory.stableMinimapLayoutInput = input; memory.stableFitRemainingWidth = remainingWidth; memory.stableFitMaxMinimapScale = minimapScale; } else { memory.stableMinimapLayoutInput = null; memory.stableFitRemainingWidth = 0; } } } } const minimapMaxWidth = Math.floor(minimapMaxColumn * minimapCharWidth); const minimapWidth = Math.min(minimapMaxWidth, Math.max(0, Math.floor((remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth / (typicalHalfwidthCharacterWidth + minimapCharWidth))) + MINIMAP_GUTTER_WIDTH); let minimapCanvasInnerWidth = Math.floor(pixelRatio * minimapWidth); const minimapCanvasOuterWidth = minimapCanvasInnerWidth / pixelRatio; minimapCanvasInnerWidth = Math.floor(minimapCanvasInnerWidth * minimapWidthMultiplier); const renderMinimap = minimapRenderCharacters ? 1 : 2; const minimapLeft = minimapSide === "left" ? 0 : outerWidth - minimapWidth - verticalScrollbarWidth; return { renderMinimap, minimapLeft, minimapWidth, minimapHeightIsEditorHeight, minimapIsSampling, minimapScale, minimapLineHeight, minimapCanvasInnerWidth, minimapCanvasInnerHeight, minimapCanvasOuterWidth, minimapCanvasOuterHeight }; } static computeLayout(options, env2) { const outerWidth = env2.outerWidth | 0; const outerHeight = env2.outerHeight | 0; const lineHeight = env2.lineHeight | 0; const lineNumbersDigitCount = env2.lineNumbersDigitCount | 0; const typicalHalfwidthCharacterWidth = env2.typicalHalfwidthCharacterWidth; const maxDigitWidth = env2.maxDigitWidth; const pixelRatio = env2.pixelRatio; const viewLineCount = env2.viewLineCount; const wordWrapOverride2 = options.get( 154 /* EditorOption.wordWrapOverride2 */ ); const wordWrapOverride1 = wordWrapOverride2 === "inherit" ? options.get( 153 /* EditorOption.wordWrapOverride1 */ ) : wordWrapOverride2; const wordWrap = wordWrapOverride1 === "inherit" ? options.get( 149 /* EditorOption.wordWrap */ ) : wordWrapOverride1; const wordWrapColumn = options.get( 152 /* EditorOption.wordWrapColumn */ ); const isDominatedByLongLines = env2.isDominatedByLongLines; const showGlyphMargin = options.get( 66 /* EditorOption.glyphMargin */ ); const showLineNumbers = options.get( 76 /* EditorOption.lineNumbers */ ).renderType !== 0; const lineNumbersMinChars = options.get( 77 /* EditorOption.lineNumbersMinChars */ ); const scrollBeyondLastLine = options.get( 119 /* EditorOption.scrollBeyondLastLine */ ); const padding = options.get( 96 /* EditorOption.padding */ ); const minimap = options.get( 81 /* EditorOption.minimap */ ); const scrollbar = options.get( 117 /* EditorOption.scrollbar */ ); const verticalScrollbarWidth = scrollbar.verticalScrollbarSize; const verticalScrollbarHasArrows = scrollbar.verticalHasArrows; const scrollbarArrowSize = scrollbar.arrowSize; const horizontalScrollbarHeight = scrollbar.horizontalScrollbarSize; const folding = options.get( 52 /* EditorOption.folding */ ); const showFoldingDecoration = options.get( 126 /* EditorOption.showFoldingControls */ ) !== "never"; let lineDecorationsWidth = options.get( 74 /* EditorOption.lineDecorationsWidth */ ); if (folding && showFoldingDecoration) { lineDecorationsWidth += 16; } let lineNumbersWidth = 0; if (showLineNumbers) { const digitCount2 = Math.max(lineNumbersDigitCount, lineNumbersMinChars); lineNumbersWidth = Math.round(digitCount2 * maxDigitWidth); } let glyphMarginWidth = 0; if (showGlyphMargin) { glyphMarginWidth = lineHeight * env2.glyphMarginDecorationLaneCount; } let glyphMarginLeft = 0; let lineNumbersLeft = glyphMarginLeft + glyphMarginWidth; let decorationsLeft = lineNumbersLeft + lineNumbersWidth; let contentLeft = decorationsLeft + lineDecorationsWidth; const remainingWidth = outerWidth - glyphMarginWidth - lineNumbersWidth - lineDecorationsWidth; let isWordWrapMinified = false; let isViewportWrapping = false; let wrappingColumn = -1; if (options.get( 2 /* EditorOption.accessibilitySupport */ ) === 2 && wordWrapOverride1 === "inherit" && isDominatedByLongLines) { isWordWrapMinified = true; isViewportWrapping = true; } else if (wordWrap === "on" || wordWrap === "bounded") { isViewportWrapping = true; } else if (wordWrap === "wordWrapColumn") { wrappingColumn = wordWrapColumn; } const minimapLayout = EditorLayoutInfoComputer._computeMinimapLayout({ outerWidth, outerHeight, lineHeight, typicalHalfwidthCharacterWidth, pixelRatio, scrollBeyondLastLine, paddingTop: padding.top, paddingBottom: padding.bottom, minimap, verticalScrollbarWidth, viewLineCount, remainingWidth, isViewportWrapping }, env2.memory || new ComputeOptionsMemory()); if (minimapLayout.renderMinimap !== 0 && minimapLayout.minimapLeft === 0) { glyphMarginLeft += minimapLayout.minimapWidth; lineNumbersLeft += minimapLayout.minimapWidth; decorationsLeft += minimapLayout.minimapWidth; contentLeft += minimapLayout.minimapWidth; } const contentWidth = remainingWidth - minimapLayout.minimapWidth; const viewportColumn = Math.max(1, Math.floor((contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth)); const verticalArrowSize = verticalScrollbarHasArrows ? scrollbarArrowSize : 0; if (isViewportWrapping) { wrappingColumn = Math.max(1, viewportColumn); if (wordWrap === "bounded") { wrappingColumn = Math.min(wrappingColumn, wordWrapColumn); } } return { width: outerWidth, height: outerHeight, glyphMarginLeft, glyphMarginWidth, glyphMarginDecorationLaneCount: env2.glyphMarginDecorationLaneCount, lineNumbersLeft, lineNumbersWidth, decorationsLeft, decorationsWidth: lineDecorationsWidth, contentLeft, contentWidth, minimap: minimapLayout, viewportColumn, isWordWrapMinified, isViewportWrapping, wrappingColumn, verticalScrollbarWidth, horizontalScrollbarHeight, overviewRuler: { top: verticalArrowSize, width: verticalScrollbarWidth, height: outerHeight - 2 * verticalArrowSize, right: 0 } }; } } class WrappingStrategy extends BaseEditorOption { constructor() { super(156, "wrappingStrategy", "simple", { "editor.wrappingStrategy": { enumDescriptions: [ localize(252, "Assumes that all characters are of the same width. This is a fast algorithm that works correctly for monospace fonts and certain scripts (like Latin characters) where glyphs are of equal width."), localize(253, "Delegates wrapping points computation to the browser. This is a slow algorithm, that might cause freezes for large files, but it works correctly in all cases.") ], type: "string", enum: ["simple", "advanced"], default: "simple", description: localize(254, "Controls the algorithm that computes wrapping points. Note that when in accessibility mode, advanced will be used for the best experience.") } }); } validate(input) { return stringSet(input, "simple", ["simple", "advanced"]); } compute(env2, options, value) { const accessibilitySupport = options.get( 2 /* EditorOption.accessibilitySupport */ ); if (accessibilitySupport === 2) { return "advanced"; } return value; } } var ShowLightbulbIconMode$1; (function(ShowLightbulbIconMode2) { ShowLightbulbIconMode2["Off"] = "off"; ShowLightbulbIconMode2["OnCode"] = "onCode"; ShowLightbulbIconMode2["On"] = "on"; })(ShowLightbulbIconMode$1 || (ShowLightbulbIconMode$1 = {})); class EditorLightbulb extends BaseEditorOption { constructor() { const defaults = { enabled: ShowLightbulbIconMode$1.OnCode }; super(73, "lightbulb", defaults, { "editor.lightbulb.enabled": { type: "string", enum: [ShowLightbulbIconMode$1.Off, ShowLightbulbIconMode$1.OnCode, ShowLightbulbIconMode$1.On], default: defaults.enabled, enumDescriptions: [ localize(255, "Disable the code action menu."), localize(256, "Show the code action menu when the cursor is on lines with code."), localize(257, "Show the code action menu when the cursor is on lines with code or on empty lines.") ], description: localize(258, "Enables the Code Action lightbulb in the editor.") } }); } validate(_input) { if (!_input || typeof _input !== "object") { return this.defaultValue; } const input = _input; return { enabled: stringSet(input.enabled, this.defaultValue.enabled, [ShowLightbulbIconMode$1.Off, ShowLightbulbIconMode$1.OnCode, ShowLightbulbIconMode$1.On]) }; } } class EditorStickyScroll extends BaseEditorOption { constructor() { const defaults = { enabled: true, maxLineCount: 5, defaultModel: "outlineModel", scrollWithEditor: true }; super(131, "stickyScroll", defaults, { "editor.stickyScroll.enabled": { type: "boolean", default: defaults.enabled, description: localize(259, "Shows the nested current scopes during the scroll at the top of the editor.") }, "editor.stickyScroll.maxLineCount": { type: "number", default: defaults.maxLineCount, minimum: 1, maximum: 20, description: localize(260, "Defines the maximum number of sticky lines to show.") }, "editor.stickyScroll.defaultModel": { type: "string", enum: ["outlineModel", "foldingProviderModel", "indentationModel"], default: defaults.defaultModel, description: localize(261, "Defines the model to use for determining which lines to stick. If the outline model does not exist, it will fall back on the folding provider model which falls back on the indentation model. This order is respected in all three cases.") }, "editor.stickyScroll.scrollWithEditor": { type: "boolean", default: defaults.scrollWithEditor, description: localize(262, "Enable scrolling of Sticky Scroll with the editor's horizontal scrollbar.") } }); } validate(_input) { if (!_input || typeof _input !== "object") { return this.defaultValue; } const input = _input; return { enabled: boolean(input.enabled, this.defaultValue.enabled), maxLineCount: EditorIntOption.clampedInt(input.maxLineCount, this.defaultValue.maxLineCount, 1, 20), defaultModel: stringSet(input.defaultModel, this.defaultValue.defaultModel, ["outlineModel", "foldingProviderModel", "indentationModel"]), scrollWithEditor: boolean(input.scrollWithEditor, this.defaultValue.scrollWithEditor) }; } } class EditorInlayHints extends BaseEditorOption { constructor() { const defaults = { enabled: "on", fontSize: 0, fontFamily: "", padding: false, maximumLength: 43 }; super(159, "inlayHints", defaults, { "editor.inlayHints.enabled": { type: "string", default: defaults.enabled, description: localize(263, "Enables the inlay hints in the editor."), enum: ["on", "onUnlessPressed", "offUnlessPressed", "off"], markdownEnumDescriptions: [ localize(264, "Inlay hints are enabled"), localize(265, "Inlay hints are showing by default and hide when holding {0}", isMacintosh ? `Ctrl+Option` : `Ctrl+Alt`), localize(266, "Inlay hints are hidden by default and show when holding {0}", isMacintosh ? `Ctrl+Option` : `Ctrl+Alt`), localize(267, "Inlay hints are disabled") ] }, "editor.inlayHints.fontSize": { type: "number", default: defaults.fontSize, markdownDescription: localize(268, "Controls font size of inlay hints in the editor. As default the {0} is used when the configured value is less than {1} or greater than the editor font size.", "`#editor.fontSize#`", "`5`") }, "editor.inlayHints.fontFamily": { type: "string", default: defaults.fontFamily, markdownDescription: localize(269, "Controls font family of inlay hints in the editor. When set to empty, the {0} is used.", "`#editor.fontFamily#`") }, "editor.inlayHints.padding": { type: "boolean", default: defaults.padding, description: localize(270, "Enables the padding around the inlay hints in the editor.") }, "editor.inlayHints.maximumLength": { type: "number", default: defaults.maximumLength, markdownDescription: localize(271, "Maximum overall length of inlay hints, for a single line, before they get truncated by the editor. Set to `0` to never truncate") } }); } validate(_input) { if (!_input || typeof _input !== "object") { return this.defaultValue; } const input = _input; if (typeof input.enabled === "boolean") { input.enabled = input.enabled ? "on" : "off"; } return { enabled: stringSet(input.enabled, this.defaultValue.enabled, ["on", "off", "offUnlessPressed", "onUnlessPressed"]), fontSize: EditorIntOption.clampedInt(input.fontSize, this.defaultValue.fontSize, 0, 100), fontFamily: EditorStringOption.string(input.fontFamily, this.defaultValue.fontFamily), padding: boolean(input.padding, this.defaultValue.padding), maximumLength: EditorIntOption.clampedInt(input.maximumLength, this.defaultValue.maximumLength, 0, Number.MAX_SAFE_INTEGER) }; } } class EditorLineDecorationsWidth extends BaseEditorOption { constructor() { super(74, "lineDecorationsWidth", 10); } validate(input) { if (typeof input === "string" && /^\d+(\.\d+)?ch$/.test(input)) { const multiple = parseFloat(input.substring(0, input.length - 2)); return -multiple; } else { return EditorIntOption.clampedInt(input, this.defaultValue, 0, 1e3); } } compute(env2, options, value) { if (value < 0) { return EditorIntOption.clampedInt(-value * env2.fontInfo.typicalHalfwidthCharacterWidth, this.defaultValue, 0, 1e3); } else { return value; } } } class EditorLineHeight extends EditorFloatOption { constructor() { super(75, "lineHeight", EDITOR_FONT_DEFAULTS.lineHeight, (x) => EditorFloatOption.clamp(x, 0, 150), { markdownDescription: localize(272, "Controls the line height. \n - Use 0 to automatically compute the line height from the font size.\n - Values between 0 and 8 will be used as a multiplier with the font size.\n - Values greater than or equal to 8 will be used as effective values.") }, 0, 150); } compute(env2, options, value) { return env2.fontInfo.lineHeight; } } class EditorMinimap extends BaseEditorOption { constructor() { const defaults = { enabled: true, size: "proportional", side: "right", showSlider: "mouseover", autohide: "none", renderCharacters: true, maxColumn: 120, scale: 1, showRegionSectionHeaders: true, showMarkSectionHeaders: true, markSectionHeaderRegex: "\\bMARK:\\s*(?-?)\\s*(?